Adding values ​​to two data.tables

I have two data.tables, and one has a subset of the rows / columns of the other. I would like to add the values ​​of the smaller data.table to the values ​​of the larger:

DT1 <- as.data.table(matrix(c(0, 1, 2, 3), nrow=2, ncol=2, 
       dimnames=list(c("a", "b"), c("a", "b"))), keep=T)
DT2 <- as.data.table(matrix(c(0, 0, 1, 2, 2, 1, 1, 0, 3), nrow=3, ncol=3, 
       dimnames=list(c("a", "b", "c"), c("a", "b", "c"))), keep=T)

DT1
#   rn a b
#1:  a 0 2
#2:  b 1 3
DT2
#   rn a b c
#1:  a 0 2 1
#2:  b 0 2 0
#3:  c 1 1 3

I want to add DT1 to DT2 to get

#   rn a b c
#1:  a 0 4 1
#2:  b 1 5 0
#3:  c 1 1 3

I know that I can easily overwrite DT2 values ​​with DT1:

DT2[DT1, names(DT1) := DT1, on="rn"]

I was hoping something like this would work:

DT2[DT1, names(DT1) := DT1 + .SD, on="rn"]

... but it is not. There are probably some simple variations of this that will work, right?

+4
source share
2 answers

I prefer Richard's way, but here's an alternative that looks more like the original OP 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
+5
source

rbindlist(), , 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
+7

Source: https://habr.com/ru/post/1609148/


All Articles