R 计数 NA 按组 [英] R count NA by group

查看:34
本文介绍了R 计数 NA 按组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could someone please explain why I get different answers using the aggregate function to count missing values by group? Also, is there a better way to count missing values by group using a native R function?

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

推荐答案

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

The help page at ?aggregate points out that the formula method has an argument na.action which is set by default to na.omit.

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

na.action: a function which indicates what should happen when the data contain NA values. The default is to ignore missing values in the given variables.

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

Change that argument to NULL or na.pass instead to get the results you are probably expecting:

# 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

这篇关于R 计数 NA 按组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆