I have this dataframe:
set.seed(50)
data <- data.frame(age=c(rep(\"juv\", 10), rep(\"ad\", 10)),
sex=c(rep(\"m\", 10), rep(\"f\", 10)),
A data.table approach:
library(data.table)
DT <- data.table(data)
DT[, lapply(.SD, function(x) sum(is.na(x))) , by = list(age,sex,size)]
## age sex size length width height
## 1: juv m large 5 4 4
## 2: ad f small 3 4 4
and the plyr equivalent using colwise and ddply
ddply(data, .(age,sex,size), colwise(.fun = function(x) sum(is.na(x))))
## age sex size length width height
## 1 ad f small 3 4 4
## 2 juv m large 5 4 4
You could always use a vector of column names for the by components
by.cols <- c('age', 'sex' ,'size')
# then the following will work....
DT[, lapply(.SD, function(x) sum(is.na(x))), by = by.cols]
ddply(data, by.cols, colwise(.fun = function(x) sum(is.na(x))))