更新时间:2023-02-26 19:32:16
您可以使用dplyr::group_by()
、dplyr::across() 和 卷曲拥抱
{{
.这适用于 dplyr 1.0.0 及更高版本.
You can rewrite the function using a combination of dplyr::group_by()
, dplyr::across()
, and curly curly embracing {{
. This works with dplyr version 1.0.0 and greater.
为了清晰起见,我编辑了原始示例和代码.
I've edited the original example and code for clarity.
library(tidyverse)
my_data <- tribble(
~foo, ~bar, ~baz,
"A", "B", 3,
"A", "C", 5,
"D", "E", 6,
"D", "E", 1
)
sum_fun <- function(.data, group, sum_var) {
.data %>%
group_by(across({{ group }})) %>%
summarize("sum_{{sum_var}}" := sum({{ sum_var }}))
}
sum_fun(my_data, group = c(foo, bar), sum_var = baz)
#> `summarise()` has grouped output by 'foo'. You can override using the `.groups` argument.
#> # A tibble: 3 x 3
#> # Groups: foo [2]
#> foo bar sum_baz
#> <chr> <chr> <dbl>
#> 1 A B 3
#> 2 A C 5
#> 3 D E 7
由 reprex 包 (v2.0.0) 于 2021 年 9 月 6 日创建上>
Created on 2021-09-06 by the reprex package (v2.0.0)