【发布时间】:2020-04-20 13:03:54
【问题描述】:
我正在尝试编写一个自定义函数,该函数使用rlang 的非标准评估来按多个变量对数据框进行分组。
这就是我的-
library(rlang)
# function definition
tryfn <- function(data, groups, ...) {
# preparing data
df <- dplyr::group_by(data, !!!rlang::enquos(groups))
print(head(df))
# applying some function `.f` on df that absorbs `...`
# .f(df, ...)
}
这适用于单个分组变量-
# works
tryfn(mtcars, am)
#> # A tibble: 6 x 11
#> # Groups: am [2]
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 21 6 160 110 3.9 2.62 16.5 0 1 4 4
#> 2 21 6 160 110 3.9 2.88 17.0 0 1 4 4
#> 3 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
#> 4 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
#> 5 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
#> 6 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1
但是如果尝试使用多个分组变量,这不起作用-
# doesn't work
tryfn(mtcars, c(am, cyl))
#> Error: Column `c(am, cyl)` must be length 32 (the number of rows) or one, not 64
# doesn't work
tryfn(mtcars, list(am, cyl))
#> Error: Column `list(am, cyl)` must be length 32 (the number of rows) or one, not 2
【问题讨论】:
-
一个选项可能是切换到
group_by_at(),因为vars()可以非常方便地在“at”变体(裸、向量、字符串)中传递所有不同类型的变量:dplyr::group_by_at(data, dplyr::vars( !! rlang::enquo(groups) ) ) -
见stackoverflow.com/questions/52718604/…。它有你正在寻找的答案。类似于:
sum_fun <- function(d, grp) d %>% group_by_at(grp); sum_fun(mtcars, grp = vars(cyl, am)) -
我重新打开它是因为链接的问题解决方案修改了 OP 的输入以使其与
group_by_at一起使用。在这里,OP 正在寻找一种解决方案,将输入作为c(...)传递 -
当我已经接受了stackoverflow.com/questions/52718604/… 已经提供了这个问题的解决方案的建议时,为什么这个问题被否决了?!
标签: r tidyverse rlang tidyeval