根据另一个data.table值递增data.table值

Sta*_*tan 1 r data.table

我有两个data.tables,一个有另一个的行/列子集.对于较小的表中的每个非零值,我想将较大的data.table的值递增1:

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
Run Code Online (Sandbox Code Playgroud)

我想在DT2中增加值,以便我得到

#   rn a b c
#1:  a 0 3 1
#2:  b 1 3 0
#3:  c 1 1 3
Run Code Online (Sandbox Code Playgroud)

(这类似于我之前关于添加DT1和DT2的问题:在两个data.tables中添加值 ...我需要同时执行:))

Aru*_*run 5

其他方式:

require(data.table) # v1.9.6+
xcols = c("a", "b")
icols = paste0("i.", xcols) # "i.*" to refer to DT1's cols
DT2[DT1, (xcols) := Map(function(x, y) x + (y > 0L), mget(xcols), mget(icols)), on="rn"]
Run Code Online (Sandbox Code Playgroud)

这应该是怎样的:

DT2[DT1, (xcols) := Map(function(x, y) x + (y > 0L), .SD, i.SD), .SDcols=xcols, i.SDcols = icols]
Run Code Online (Sandbox Code Playgroud)

甚至更好的是:

DT2[DT1, (xcols) := .SD + (i.SD > 0L), .SDcols=xcols, i.SDcols=icols]
Run Code Online (Sandbox Code Playgroud)