Update subset of data.table based on join

后端 未结 3 618
轮回少年
轮回少年 2020-11-28 12:43

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                 


        
相关标签:
3条回答
  • 2020-11-28 13:22

    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]
    
    0 讨论(0)
  • 2020-11-28 13:33

    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
    
    0 讨论(0)
  • 2020-11-28 13:33

    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']
    
    0 讨论(0)
提交回复
热议问题