R 分组依据,计算非 NA 值

R group by, counting non-NA values

我有一个分散了 NA

的数据框
toy_df
# Y  X1 X2 Label
# 5  3  3  A
# 3  NA 2  B
# 3  NA NA C
# 2  NA 6  B

我想按标签字段对其进行分组,并计算每个标签的每个变量中有多少个非 NA 值。

desired output:
# Label Y  X1 X2
# A     1  1  1
# B     2  0  2
# C     1  0  0

目前我已经使用循环完成了此操作,但速度缓慢且不整洁,我相信有更好的方法。

总和似乎达到了一半,但它包括 NA 的计数。

aggregate(toy_df, list(toy_df$label), FUN=length)

任何想法表示赞赏...

aggregate(cbind(toy_df$Y, toy_df$X1, toy_df$X2), list(toy_df$label),
          FUN = function (x) sum(!is.na(x)))

我们可以使用data.table。将 'data.frame' 转换为 'data.table' (setDT(toy_df)),按 'Label' 分组,遍历 Data.table (.SD) 的子集并得到 sum 个非 NA 值 (!is.na(x))

library(data.table)
setDT(toy_df)[, lapply(.SD, function(x) sum(!is.na(x))), by = Label]
#   Label Y X1 X2
#1:     A 1  1  1
#2:     B 2  0  2
#3:     C 1  0  0

或者 dplyr 使用相同的方法

library(dplyr)
toy_df %>% 
      group_by(Label) %>%
      summarise_each(funs(sum(!is.na(.))))

base R 选项,其中 bycolSums 按逻辑矩阵 (!is.na(toy_df[-4]))

的第 4 列分组
by(!is.na(toy_df[-4]), toy_df[4], FUN = colSums)

或者使用 rowsumby 类似的方法,除了使用 rowsum 函数。

rowsum(+(!is.na(toy_df[-4])), group=toy_df[,4])
#  Y X1 X2
#A 1  1  1
#B 2  0  2
#C 1  0  0

或以 R 为基数

aggregate(toy_df[,1:3], by=list(toy_df$Label), FUN=function(x) { sum(!is.na(x))})