'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)?



Solution 1:[1]

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

Solution 2:[2]

Try this using base R

map2$v2 <- map1$v[match(map2$k2,map1$k)]

Solution 3:[3]

You could also do this. It's not quite as elegant, but I find it more intuitive:

map2 = merge(
  x = map2,
  y = map1,
  by.x = 'k2',
  by.y = 'k',
  all.x = T
)

setnames(map2, old = c('v'), new = c('v2')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roland
Solution 2
Solution 3