Alexis Alexis - 4 months ago 29
R Question

nansum in R for data.table

Let's start with DT1

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


We also have DT2

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


I want to sum the two data.table, so I would get the following result:

# 1: NA 3 3
# 2: NA 3 3
# 3: NA 3 3
# 4: NA 3 3
# 5: NA 2 2

Answer

One option is 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
Comments