Reputation: 3477
I have a vector with the following data:
data<-c('ab','ab','ab','cd','cd','cd','ef','ef')
how can I convert that data by using R so that it gets transformed with the following pattern:
ab=1
cd=2
ef=3
so that the vector will be converted to:
data=[1,1,1,2,2,2,3,3]
Upvotes: 1
Views: 48
Reputation: 887431
Another option is match
match(data, unique(data))
#[1] 1 1 1 2 2 2 3 3
Or in place of unique(data)
, you can specify the vector of elements to match.
match(data, c('ab', 'cd', 'ef'))
Upvotes: 3
Reputation: 206391
That's basically what a "factor" is in R. you can do
as.numeric(factor(data, levels=c("ab","cd","ef")))
You could also use a named lookup vector
vv<-c(ab=1, cd=2, ef=3)
vv[data]
# or unname(vv[data]) if the names really bother you
Upvotes: 2