R dplyr: 如何在使用 summarize(across()) 时引用数据中的变量名?

7

我想使用summarize函数编写一个灵活的函数,满足以下要求:

  1. 聚合函数由用户提供
  2. 聚合函数可能使用数据本身中的变量作为进一步的参数。

一个很好的例子是用户提供fun=weighted.mean()并指定权重参数w

目前,我正在尝试使用...,但问题在于我没有找到一种方式使...引用数据框中的变量?下面的示例使用across()给出,但如果改用summarize_at(),情况也是一样的。

谢谢!

library(tidyverse)
fo1 <- function(df, fun=mean, ...){
  df %>% 
    group_by(Species) %>% 
    summarise(across(starts_with("sepal"), fun, ...))
}

fo1(iris)
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#>   Species    Sepal.Length Sepal.Width
#>   <fct>             <dbl>       <dbl>
#> 1 setosa             5.01        3.43
#> 2 versicolor         5.94        2.77
#> 3 virginica          6.59        2.97
fo1(iris, fun=weighted.mean)
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#>   Species    Sepal.Length Sepal.Width
#>   <fct>             <dbl>       <dbl>
#> 1 setosa             5.01        3.43
#> 2 versicolor         5.94        2.77
#> 3 virginica          6.59        2.97
fo1(iris, fun=weighted.mean, w=Petal.Length)
#> Error: Problem with `summarise()` input `..1`.
#> x object 'Petal.Length' not found
#> ℹ Input `..1` is `across(starts_with("sepal"), fun, ...)`.
#> ℹ The error occurred in group 1: Species = "setosa".
fo1(iris, fun=weighted.mean, w=.data$Petal.Length)
#> Error: Problem with `summarise()` input `..1`.
#> x 'x' and 'w' must have the same length
#> ℹ Input `..1` is `across(starts_with("sepal"), fun, ...)`.
#> ℹ The error occurred in group 1: Species = "setosa".

这段内容是由reprex软件包 (v0.3.0)创建于2020年11月10日。

3个回答

3

enquos 将返回一个引用表达式的列表。反引号展开操作符!!!将每个元素作为函数调用的参数进行反引用。

library(tidyverse)

fo1 <- function(df, fun = mean, ...) {
  df %>% 
    summarise(across(starts_with("sepal"), fun, !!!enquos(...)))
}

iris %>%
  group_by(Species) %>%
  fo1(fun = weighted.mean, w = Petal.Length, na.rm = TRUE)
#> # A tibble: 3 x 3
#>   Species    Sepal.Length Sepal.Width
#>   <fct>             <dbl>       <dbl>
#> 1 setosa             5.02        3.44
#> 2 versicolor         5.98        2.79
#> 3 virginica          6.64        2.99

更多信息请参见此处


2

您需要传递准确的附加参数值。.data$Petal.LengthNULL

library(dplyr)

fo1 <- function(df, fun=mean, ...){
  df %>% 
    summarise(across(starts_with("sepal"), fun, ...))
}


fo1(iris, fun=weighted.mean, w= iris$Petal.Length)
#  Sepal.Length Sepal.Width
#1     6.180167    2.970197

谢谢Ronak!不幸的是,如果数据被分组,这个方法将失败!我更新了示例以明确这个限制。 - Matifou
我明白了。是的,没错。但我认为weighted.mean是一个独特的例子,因为它有额外的参数以向量的形式存在。通常,额外的参数会采用na.rm = TRUE这样的形式,可以直接与...一起使用。 - Ronak Shah
3
summarize函数中,请使用!!!enquos(...)代替...。这样它就可以处理iris %>% group_by(Species) %>% fo1(fun = weighted.mean, w = Petal.Length, na.rm = TRUE) - Paul
@Paul:这绝对是目前为止最好的解决方案。 - Limey
1
@Paul,我认为你实际上得到了答案!想把你的评论变成答案吗? - Matifou

2

这看起来很丑,但是它能够正常工作。

> fo1 <- function(df, fun=mean, ...){
+   w <- df %>% pull(...)
+   df %>% 
+     summarise(across(starts_with("Sepal"), fun, w))
+ }
> fo1(iris, fun=weighted.mean, Petal.Length)
  Sepal.Length Sepal.Width
1     6.180167    2.970197

继承Paul在上面评论中的建议后,以下似乎是一个通用解决方案:

fo1 <- function(df, fun=mean, ...){
  df %>% 
    summarise(across(starts_with("Sepal"), fun, !!!enquos(...)))
}
> fo1(iris, fun=weighted.mean, Petal.Length)
  Sepal.Length Sepal.Width
1     6.180167    2.970197
> fo1(iris, fun=mean)
  Sepal.Length Sepal.Width
1     5.843333    3.057333

我尝试了几种组合,包括!!!!!enquo()enquos(),但可能错过了其中的一种。


谢谢Limey!不幸的是,这假设w总是存在,但如果使用不需要它的函数,则会失败! - Matifou
我同意。这就是为什么它很丑陋! :) - Limey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接