sum non NA elements only, but if all NA then return NA
Following the suggestions from other users, I will post the answer to my question. The solution was provided by @sandipan in the comments above:
As noted in the question, if you need to sum the values of one column which contains NAs,there are two good approaches:
1) using ifelse:
A[, (ifelse(all(is.na(col2)), col2[NA_integer_], sum(col2, na.rm = T))),
by = .(col1)]
2) define a function as suggested by @Frank:
suma = function(x) if (all(is.na(x))) x[NA_integer_] else sum(x, na.rm = TRUE)
A[, suma(col2), by = .(col1)]
Note that I added NA_integer_ as @Frank pointed out because I kept getting errors about the types.
Using sum_
from hablar
library(hablar)
A[, as.numeric(sum_(col2)), .(col1)]
# col1 V1
#1: A NA
#2: B 5
#3: C 4