使用dplyr summarise_each()和is.na()

时间:2014-09-24 13:01:22

标签: r dplyr

我试图在函数中包含一些dplyr魔法来生成一个data.frame然后用xtable打印。

最终的目标是让this的dplyr版本正常工作,并且我在阅读时遇到了非常有用的summarise_each()函数,该函数在使用regroup()进行子集化之后(因为它位于function)然后我可以使用它来解析所有列。

我遇到的问题(到目前为止)是在is.na()内调用summarise_each(funs(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 %>%
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

1 个答案:

答案 0 :(得分: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

并且因为您要求提供文档指针:.引用了每条数据,并在?summarize_each中的某些示例中使用。它在?funs参数部分中描述为&#34;虚拟参数&#34; ,并使用示例.也在?do参数部分进行了简要描述:&#34; ...您可以使用.来引用当前组&#34;