【问题标题】:Using dplyr summarise_each() with is.na()将 dplyr summarise_each() 与 is.na() 一起使用
【发布时间】:2014-09-24 13:01:22
【问题描述】:

我正在尝试将一些 dplyr 魔法包装在一个函数中以生成一个 data.frame,然后我使用 xtable 打印它。

最终目标是让 this 的 dplyr 版本工作,并阅读周围我发现了非常有用的 summarise_each() 函数,在使用 regroup() 子集后(因为它在函数内)我可以使用解析所有列。

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

我们将非常感激地收到任何有关文档的建议或指示。

谢谢,

松紧带

【问题讨论】:

  • +1 为一个很棒的图标

标签: r dplyr


【解决方案1】:

这是一种可能性,在一个带有一些 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 的Arguments 部分中描述为“虚拟参数”,并用于Examples。 . 在?do 的Arguments 部分也有简要描述:“... You can use . to refer to current group”

【讨论】:

  • 太好了,谢谢。我之前遇到过.,因为它用于表示应该转换为plyr() 中的因子的变量,并且我已经看到它在一些dplyr() 示例中使用过。我发现令人困惑的事情(但现在要记住)是许多命令无需使用它来引用当前组即可工作,并且并不总是清楚哪些命令需要/不需要它。无论如何,这在我正在处理的功能中非常有用,再次感谢。
猜你喜欢
  • 2014-11-03
  • 2015-10-27
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2017-12-29
相关资源
最近更新 更多