Function to count NA values at each level of a factor

后端 未结 3 1272
眼角桃花
眼角桃花 2020-12-18 13:14

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)),         


        
3条回答
  •  旧巷少年郎
    2020-12-18 13:35

    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))))
    

提交回复
热议问题