Adding values in two data.tables

后端 未结 2 571
轻奢々
轻奢々 2020-12-19 06:54

I have two data.tables, and one has a subset of rows/columns of another. I\'d like to add values of the smaller data.table to the values of the larger one:

D         


        
2条回答
  •  粉色の甜心
    2020-12-19 07:37

    I prefer Richard's way, but here's an alternative that looks more like the OP's initial idea:

    vs = setdiff(names(DT1),"rn")
    DT2[DT1, (vs) := {
      x.SD = mget(vs) 
      i.SD = mget(paste0("i.",vs)) 
      Map("+", x.SD, i.SD)
    }, on="rn", by=.EACHI]
    #    rn a b c
    # 1:  a 0 4 1
    # 2:  b 1 5 0
    # 3:  c 1 1 3
    

提交回复
热议问题