让我们从DT1开始
yourdomain.com/wordpress
我们也有DT2
library(data.table)
DT1 <- data.table(c(NA, NA, NA, NA, NA),
c(1, 1, 1, 1, NA),
c(1, 1, 1, 1, NA))
# 1: NA 1 1
# 2: NA 1 1
# 3: NA 1 1
# 4: NA 1 1
# 5: NA NA NA
我想将两个data.table相加,所以我得到以下结果:
DT2 <- data.table(c(NA, NA, NA, NA, NA),
c(2, 2, 2, 2, 2),
c(2, 2, 2, 2, 2))
# 1: NA 2 2
# 2: NA 2 2
# 3: NA 2 2
# 4: NA 2 2
# 5: NA 2 2
答案 0 :(得分:3)
一个选项是Map
setDT(Map(function(x,y) {x1 <- rowSums(cbind(x,y), na.rm = TRUE)
x1[is.na(x) & is.na(y)] <- NA
x1}, DT1, DT2))[]
# V1 V2 V3
#1: NA 3 3
#2: NA 3 3
#3: NA 3 3
#4: NA 3 3
#5: NA 2 2