R按组计算NA

时间:2014-06-29 15:57:08

标签: r count aggregate na

有人可以解释为什么我使用聚合函数来获得不同的答案来按组计算缺失值吗?此外,是否有更好的方法使用本机R函数按组计算缺失值?

DF <- data.frame(YEAR=c(2000,2000,2000,2001,2001,2001,2001,2002,2002,2002), X=c(1,NA,3,NA,NA,NA,7,8,9,10))
DF

aggregate(X ~ YEAR, data=DF, function(x) { sum(is.na(x)) })
with(DF, aggregate(X, list(YEAR), function(x) { sum(is.na(x)) }))

aggregate(X ~ YEAR, data=DF, function(x) { sum(! is.na(x)) })
with(DF, aggregate(X, list(YEAR), function(x) { sum(! is.na(x)) }))

2 个答案:

答案 0 :(得分:13)

?aggregate处的帮助页面指出公式方法的参数na.action默认设置为na.omit

  

na.action一个函数,指示当数据包含NA值时应该发生什么。默认设置是忽略给定变量中的缺失值。

将该参数更改为NULLna.pass,以获得您可能期望的结果:

# 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

答案 1 :(得分:-3)

library(dplyr)
library(tidyr)

#say you want to get missing values from group 1
dataframe %>% filter(group = 1 & is.na(another_column))

#missing values from group 2
dataframe %>% filter(group = 2 & is.na(another_column))