本文介绍了在两个 data.tables 中添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 data.tables,一个有另一个的行/列的子集.我想将较小的 data.table 的值添加到较大的值:
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:
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
我想将 DT1 添加到 DT2 以便我得到
I'd like to add DT1 to DT2 so that I get
# rn a b c
#1: a 0 4 1
#2: b 1 5 0
#3: c 1 1 3
我知道我可以很容易地用 DT1 覆盖 DT2 的值:
I know I can overwrite values of DT2 with DT1 very easily:
DT2[DT1, names(DT1) := DT1, on="rn"]
我希望这样的事情会起作用:
I was hoping that something like this would work:
DT2[DT1, names(DT1) := DT1 + .SD, on="rn"]
...但事实并非如此.不过,这可能有一些简单的变化会起作用,对吧?
...but it doesn't. There's probably some simple variation on this that would work, though, right?
推荐答案
我更喜欢 Richard 的方式,但这里有一个看起来更像 OP 最初想法的替代方案:
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
这篇关于在两个 data.tables 中添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!