我已经制作了一个忽略NA
的自定义和函数,除非所有函数都是NA
。当我在dplyr
中使用它时会返回奇怪的结果,我不知道为什么。
require(dplyr)
dta <- data.frame(year=2007:2013, rrconf=c(79, NaN ,474,2792,1686,3313,3456), enrolled=c(NaN,NaN,458,1222,1155,1906,2184))
sum0 <- function(x, ...){
# remove NAs unless all are NA
if(is.na(mean(x, na.rm=TRUE))) return(NA)
else(sum(x, ..., na.rm=TRUE))
}
dta %>%
group_by(year) %>%
summarize(rrconf=sum0(rrconf), enrolled=sum0(enrolled))
给了我
Source: local data frame [7 x 3]
year rrconf enrolled
1 2007 79 NA
2 2008 NA NA
3 2009 474 TRUE
4 2010 2792 TRUE
5 2011 1686 TRUE
6 2012 3313 TRUE
7 2013 3456 TRUE
在这种情况下,它只是在一个值上求和,但在我的更大的应用程序中,可能是夏天的多个值。将sum0
函数包装在as.integer()
中似乎可以修复它,但我无法告诉您原因。
这是解决此问题的正确方法吗?有什么明显的东西我不见了吗?
> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: i386-w64-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.2
loaded via a namespace (and not attached):
[1] assertthat_0.1 magrittr_1.0.1 parallel_3.1.0 Rcpp_0.11.2 tools_3.1.0
答案 0 :(得分:10)
问题似乎是dplyr
确定引用第一个返回结果的列类型。如果您将NA
值(默认情况下为逻辑值)强制为NA_real_
或NA_integer_
,则您将被排序:
##Just to show what NA normally does first:
class(NA)
#[1] "logical"
sum0 <- function(x, ...){
# remove NAs unless all are NA
if(is.na(mean(x, na.rm=TRUE))) return(NA_real_)
else(sum(x, ..., na.rm=TRUE))
}
dta %>%
group_by(year) %>%
summarize(rrconf=sum0(rrconf), enrolled=sum0(enrolled))
#Source: local data frame [7 x 3]
#
# year rrconf enrolled
#1 2007 79 NA
#2 2008 NA NA
#3 2009 474 458
#4 2010 2792 1222
#5 2011 1686 1155
#6 2012 3313 1906
#7 2013 3456 2184