R count NA by group
Solution 1:
The help page at ?aggregate
points out that the formula method has an argument na.action
which is set by default to na.omit
.
na.action
: a function which indicates what should happen when the data containNA
values. The default is to ignore missing values in the given variables.
Change that argument to NULL
or na.pass
instead to get the results you are probably expecting:
# aggregate(X ~ YEAR, data=DF, function(x) {sum(is.na(x))}, na.action = na.pass)
aggregate(X ~ YEAR, data=DF, function(x) {sum(is.na(x))}, na.action = NULL)
# YEAR X
# 1 2000 1
# 2 2001 3
# 3 2002 0