Reputation: 47058
In R, I want to use a key-value list to convert a column of keys to values. It's similar to: How to map a column through a dictionary in R, but I want to use a list not a data.frame.
I've tried to do this using list and columns:
d = list('a'=1, 'b'=2, 'c'=3)
d[c('a', 'a', 'c', 'b')] # I want this to return c(1,1,3,2) but it doesn't
However, the above returns a list:
list('a'=1, 'a'=1, 'c'=3, 'b'=2)
Upvotes: 2
Views: 3553
Reputation: 886948
unlist
is a useful function in this situation
unlist(d[c('a', 'a', 'c', 'b')], use.names=FALSE)
#[1] 1 1 3 2
Or another option is stack
which returns the 'key/value' as columns in a 'data.frame'. By subsetting the values column, we get
stack( d[c('a', 'a', 'c', 'b')])[,1]
#[1] 1 1 3 2
Upvotes: 4