I have two map/data.tables. One consists of key-values and another one just of some keys. I want to map the values from the first map to the keys of the second. How can this be done?
Here is some example code:
map1<-data.table( k=c("A","B"), v=c(2,3) )
map2<-data.table( k2=c("A","B","A","A"))
How can I produce a new column v2 in map2 which contains c(2,3,2,2)?
Use a data.table join:
map1[map2, v, on = c(k = "k2")]
#[1] 2 3 2 2
map2[map1, v2 := v, on = c(k2 = "k")]
# k2 v2
#1: A 2
#2: B 3
#3: A 2
#4: A 2
Try this using base R
map2$v2 <- map1$v[match(map2$k2,map1$k)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With