I have two data tables, DT1 and DT2:
set.seed(1)
DT1<-data.table(id1=rep(1:3,2),id2=sample(letters,6), v1=rnorm(6), key=\"id2\")
DT1
## id1 id2
This is similar to mnel's solution but uses ifelse
instead of a second key.
DT1[DT2, v1 := ifelse(id1==3, i.v1, v1),nomatch=0]
The easiest way I can think of is to key by id1
as well.
eg
setkey(DT1, id2,id1)
DT2[, id1 := 3]
setkey(DT2, id2, id1)
# use i.v1 to reference v1 from the i component
DT1[DT2, v1 := i.v1 ]
DT1
id1 id2 v1
1: 2 e 0.7383247
2: 1 g 1.5952808
3: 2 j 0.3295078
4: 3 n 0.0000000
5: 3 s 0.5757814
6: 1 u 0.4874291
I have been thinking of this question these days. Following is my solution.
DT1[DT2, names(DT2):= DT2, on= 'id']
Or, if you don't want to add new variables to DT1 when there are variables private to DT2:
common.var <- intersect(names(DT1), names(DT2))
DT1[DT2, c(common.var) := DT2[, common.var, with= FALSE] ,on= 'id']