我有两个具有相同结构的 data.table。两个关键列,后面跟着一些数据列。数据列的数量可能会有所不同。
我想将第二个 data.table 中的值添加到第一个 data.table 中的相应行/列。
DT1 <- cbind(data.table(loc=c("L1","L2","L3"), product=c("P1","P2","P1")), matrix(10,nrow=3,ncol=12))
setkey(DT1, loc, product)
DT1
loc product V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
1: L1 P1 10 10 10 10 10 10 10 10 10 10 10 10
2: L2 P2 10 10 10 10 10 10 10 10 10 10 10 10
3: L3 P1 10 10 10 10 10 10 10 10 10 10 10 10
DT2 <- cbind(data.table(loc=c("L2","L3"), product=c("P2","P1")), matrix(1:24,nrow=2,ncol=12))
setkey(DT2, loc, product)
loc product V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
1: L2 P2 1 3 5 7 9 11 13 15 17 19 21 23
2: L3 P1 2 4 6 8 10 12 14 16 18 20 22 24
到目前为止我最好的选择是以下
DT1[DT2, 3:14 := as.data.table(DT1[DT2, 3:14, with=FALSE] + DT2[, 3:14, with=FALSE]), with=FALSE]
loc product V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
1: L1 P1 10 10 10 10 10 10 10 10 10 10 10 10
2: L2 P2 11 13 15 17 19 21 23 25 27 29 31 33
3: L3 P1 12 14 16 18 20 22 24 26 28 30 32 34
请注意,nrow 和 ncol 以及 loc 和 Product 条目都是可变的,具体取决于源数据。
如果 DT2 中的每一行都与 DT1 中的每一行匹配,则此方法有效,但否则会产生意外结果。
是否有更严格/优雅的方式来表达 RHS 以执行引用 DT1 和 DT2 的可变数量的列分配?