I think I already got really good answers on the comments, but I will rephrase the question for future reference.
I am trying to sum by groups using data.table. The
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.