Adding values in two data.tables

后端 未结 2 559
轻奢々
轻奢々 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
    
    0 讨论(0)
  • 2020-12-19 07:42

    You can use rbindlist() to bring the two together, then sum the values based on rn

    rbindlist(list(DT1, DT2), fill=TRUE)[, lapply(.SD, sum, na.rm = TRUE), by = rn]
    #    rn a b c
    # 1:  a 0 4 1
    # 2:  b 1 5 0
    # 3:  c 1 1 3
    
    0 讨论(0)
提交回复
热议问题