根据本文,最新版本的rlang
andglue
允许将隧道组合{{ myobj }}
成一个glue
字符串:
library(dplyr)
library(rlang)
library(glue)
mean_by <- function(data, by, var, prefix = "avg") {
data %>%
group_by({{ by }}) %>%
summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE))
}
iris %>% mean_by(Species, Sepal.Width)
#> # A tibble: 3 x 2
#> Species avg_Sepal.Width
#> <fct> <dbl>
#> 1 setosa 3.43
#> 2 versicolor 2.77
#> 3 virginica 2.97
但如果我想在等式的另一边结合,我不能这样做:
analyze_by <- function(data, by, var, prefix = "avg") {
data %>%
group_by({{ by }}) %>%
summarise(analysis = glue("{ prefix } by {{ var }}"))
}
iris %>% analyze_by(Species, Sepal.Width)
#> # A tibble: 3 x 2
#> Species analysis
#> <fct> <glue>
#> 1 setosa avg by { var }
#> 2 versicolor avg by { var }
#> 3 virginica avg by { var }
解决这个问题的最佳方法是什么?