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

sla*_*ine 6 r dplyr

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

最终目标是让这个工作的dplyr版本,并阅读我遇到了非常有用的summarise_each()功能,在使用regroup()(因为这是在一个函数内)子集后,我可以用来解析所有列.

我遇到的问题(到目前为止)是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
Run Code Online (Sandbox Code Playgroud)

运行这个失败,它的调用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
Run Code Online (Sandbox Code Playgroud)

真正的问题是我不需要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))
Run Code Online (Sandbox Code Playgroud)

但问题是,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
Run Code Online (Sandbox Code Playgroud)

我尝试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
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议或指向文档的指示.

谢谢,

slackline

Hen*_*rik 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
Run Code Online (Sandbox Code Playgroud)

并且因为您要求指向文档:.指向每个数据部分,并在一些示例中使用?summarize_each.它在Arguments部分中?funs描述为"伪参数",并用于实施例.该.还简要描述参数的部分?do":...您可以使用.来指代当前组"