Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

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

like image 272
Funkwecker Avatar asked Aug 15 '16 07:08

Funkwecker


2 Answers

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
like image 99
Roland Avatar answered Oct 01 '22 03:10

Roland


Try this using base R

map2$v2 <- map1$v[match(map2$k2,map1$k)]
like image 29
user2100721 Avatar answered Oct 01 '22 02:10

user2100721