We can use aggregate
aggregate(.~grp, data=dat, FUN= function(x) sum(is.na(x)))
Or with dplyr
library(dplyr)
dat %>%
group_by(grp) %>%
summarise_each(funs(sum(is.na(.)))
Or using data.table
library(data.table)
setDT(dat)[, lapply(.SD, function(x) sum(is.na(x))), grp]
Or as @David Arenburg mentioned in the comments, rowsum
is another option where we can do the group by operation while summing. We used +
to coerce the logical matrix (is.na(dat)
) to binary as the function will not work with logical class.
rowsum(+(is.na(dat)), dat$grp)