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
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
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