The function returns 0 if it is applied to an empty set. Is there an easy way to make it return NA if it applies to a set of NA values?
Here is an example borrowed :
test <- data.frame(name = rep(c("A", "B", "C"), each = 4), var1 = rep(c(1:3, NA), 3), var2 = 1:12, var3 = c(rep(NA, 4), 1:8)) test name var1 var2 var3 1 A 1 1 NA 2 A 2 2 NA 3 A 3 3 NA 4 A NA 4 NA 5 B 1 5 1 6 B 2 6 2 7 B 3 7 3 8 B NA 8 4 9 C 1 9 5 10 C 2 10 6 11 C 3 11 7 12 C NA 12 8
I would like to have the sum of three variables in one name. Here is what I tried:
var_to_aggr <- c("var1","var2","var3") aggr_by <- "name" summed <- aggregate(test[var_to_aggr],by=test[aggr_by],FUN="sum", na.rm = TRUE)
This gives me:
name var1 var2 var3 1 A 6 10 0 2 B 6 26 10 3 C 6 42 26
But I need:
name var1 var2 var3 1 A 6 10 NA 2 B 6 26 10 3 C 6 42 26
The sum for the name A, var3 should be NA, not 0. (just to be clear, this should not be NA for the name A, var1, where the set contains one NA, as well as valid values ββthat should be added). Any ideas?
I play with na.action, but the amount does not seem to accept them.