When calculating the sum of two data tables, NA+n=NA
.
> dt1 <- data.table(Name=c(\"Joe\",\"Ann\"), \"1\"=c(0,NA), \"2\"=c(3,NA))
> dt1
dtsum <- rbind(dt1, dt2)[, lapply(.SD, function(x) ifelse(all(is.na(x)), as.numeric(NA), sum(x, na.rm=T))), by=Name]
(includes @Arun's suggestion)
na.rm=TRUE
is very useful to remember
You can define your own function to act as you want
plus <- function(x) {
if(all(is.na(x))){
c(x[0],NA)} else {
sum(x,na.rm = TRUE)}
}
rbind(dt1, dt2)[,lapply(.SD, plus), by = Name]