在两个数据表中添加值 [英] Adding values in two data.tables

查看:114
本文介绍了在两个数据表中添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个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"]

...但不是。

推荐答案

我更喜欢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

这篇关于在两个数据表中添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆