dplyr中的自定义求和函数返回不一致的结果

时间:2014-10-14 01:14:01

标签: r dplyr

我已经制作了一个忽略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 

1 个答案:

答案 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