Julian Julian - 2 months ago 7x
R Question

How to map values from a data.table to a data.table (R)

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