David
David

Reputation: 427

Merge for multiple columns and rows

Given the following data tables:

> d1 <- data.table(letter=c("A", "B", "A", "B"), V1=c(0,0,0,0),V2=c(0,0,0,0))
> d2 <- data.table(letter=c("A", "B"), value=c(1,2))
> d1
   letter V1 V2
1:      A  0  0
2:      B  0  0
3:      A  0  0
4:      B  0  0
> d2
   letter value
1:      A     1
2:      B     2

I seek to fill columns V1 and V2 from d1 using the values from d2, so that:

> d12
   letter V1 V2
1:      A  1  1
2:      B  2  2
3:      A  1  1
4:      B  2  2

I assume I have to use the function 'merge' somehow but I have not managed.

Any advice on how to achieve this?

Many thanks in advance!

Upvotes: 1

Views: 64

Answers (1)

mathematical.coffee
mathematical.coffee

Reputation: 56945

setkey(d1, letter)
setkey(d2, letter)
d1[d2, c('V1','V2'):=value]
# d1 holds the updated dt

The d1[d2] merges d1 to d2; the c('V1', 'V2'):=value assigns the value column to V1 and V2. rows in d1 that have letters not in d2 are left as-is.

Upvotes: 3

Related Questions