我试图用这个典型的例子来说明卷曲运算符的工作原理
mean_by <- function(data, by, var) {
data %>%
dplyr::group_by({{ by }}) %>%
dplyr::summarise(avg = mean({{ var }}, na.rm = TRUE))
}
mtcars %>% mean_by(by = cyl, var = disp)
并通过向分组添加附加变量来修改它。唉,我可能永远无法理解那个运算符实际上做了什么;我尝试做类似的事情
mean_by <- function(data, by, var) {
data %>%
dplyr::group_by({{ c(by, hp) }}) %>%
dplyr::summarise(avg = mean({{ var }}, na.rm = TRUE))
}
mtcars %>% mean_by(by = cyl, var = disp)
显然不起作用
如果您想编写一个函数来按
hp
以及传递给它的其他任何内容进行分组,那么使用 ...
: 会更容易
mean_by_hp <- function(data, ..., var) {
data |>
dplyr::group_by(hp, ...) |>
dplyr::summarise(avg = mean({{ var }}, na.rm = TRUE))
}
mean_by_hp(mtcars, cyl, var = disp)
# hp cyl avg
# <dbl> <dbl> <dbl>
# 1 52 4 75.7
# 2 62 4 147.
# 3 65 4 71.1
# 4 66 4 78.8
# 5 91 4 120.
# 6 93 4 108
# 7 95 4 141.
# 8 97 4 120.
# 9 105 6 225
# 10 109 4 121