Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

R count NA by group

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)) }))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: a function which indicates what should happen when the data contain NA values. The default is to ignore missing values in the given variables.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...