2014-09-24 127 views
6

我试图包装一些函数内的dplyr魔术产生data.frame,然后我用xtable打印。使用dplyr summarise_each()与is.na()

的最终目的是有this一个dplyr版本的工作,阅读各地我遇到了非常有用的summarise_each()功能与regroup()子集化后(因为这是一个函数内),然后我就可以用它来得到解析的列来。

我遇到的问题(迄今为止)是从​​内呼叫is.na(),因为我被告知Error: expecting a single value

我故意不张贴我的功能,只是还没有,但一个小例子如下(注: - 这使用group_by()而在我的功能我regroup()替换此)...

library(dplyr) 
library(magrittr) 
> t <- data.frame(grp = rbinom(10, 1, 0.5), 
       a = as.factor(round(rnorm(10))), 
       b = rnorm(10), 
       c = rnorm(10)) 
t %>% 
group_by(grp) %>% ## This is replaced with regroup() in my function 
summarise_each(funs(is.na)) 
Error: expecting a single value 

运行失败,其调用is.na()这是问题,因为如果我工作,而不是从观测的数量在每它的工作原理(推导缺失的比例要求)...

> t %>% 
group_by(grp) %>% ## This is replaced with regroup() in my function 
summarise_each(funs(length)) 
Source: local data frame [2 x 4] 

    grp a b c 
1 0 8 8 8 
2 1 2 2 2 

真正的问题是,虽然我并不需要每一列中只是is.na(),但sum(is.na())按照链接的例子所以我真的希望是......

> t %>% 
group_by(grp) %>% ## This is replaced with regroup() in my function 
summarise_each(funs(propmiss = sum(is.na)/length)) 

但问题是,没有按sum(is.na) “T工作,我期待它(可能是因为我的期望是错误的!)......

> t %>% 
group_by(grp) %>% ## This is replaced with regroup() in my function 
summarise_each(funs(nmiss = sum(is.na))) 
Error in sum(.Primitive("is.na")) : invalid 'type' (builtin) of argument 

我打过电话明确用括号is.na(),但同样会返回一个错误......

> t %>% 
+ group_by(grp) %>% ## This is replaced with regroup() in my function 
+ summarise_each(funs(nmiss  = sum(is.na()))) 
Error in is.na() : 0 arguments passed to 'is.na' which requires 1 

任何建议或文档指针将非常感激地收到。

感谢,

slackline

+0

+1一个真棒图标 – 2014-09-24 13:14:56

回答

8

这是有可能的,在一个小的数据与一些NA设置进行测试:

df <- data.frame(a = rep(1:2, each = 3), 
       b = c(1, 1, NA, 1, NA, NA), 
       c = c(1, 1, 1, NA, NA, NA)) 

df 
# a b c 
# 1 1 1 1 
# 2 1 1 1 
# 3 1 NA 1 
# 4 2 1 NA 
# 5 2 NA NA 
# 6 2 NA NA 


df %>% 
    group_by(a) %>% 
    summarise_each(funs(sum(is.na(.))/length(.))) 
# a   b c 
# 1 1 0.3333333 0 
# 2 2 0.6666667 1 

因为你问指向文档:在.是指每个部分数据,并在一些中使用示例 in ?summarize_each。在参数部分?funs中描述为“虚拟参数”,并且使用示例。该.也进行了简要地参数的?do节中描述:“...您可以使用.指当前组”

+0

优秀,为表示感谢。我之前遇到过'.',因为它用于表示应该转换为'plyr()'中的因子的变量,我已经看到它在某些'dplyr()'示例中使用。我觉得困惑的事情(但现在要记住)是许多命令不需要使用它来指代当前的组,而且它并不总是清楚哪些组合不需要它。无论如何,这在我正在工作的功能中很有效,再次感谢。 – slackline 2014-09-24 15:19:13