参考:http://dplyr.tidyverse.org/articles/programming.html
本守则运作良好:
df <- tibble(
g1 = c(1, 1, 2, 2, 2),
g2 = c(1, 2, 1, 2, 1),
a = sample(5),
b = sample(5)
)
my_summarise <- function(df, group_by) {
group_by <- enquo(group_by)
print(group_by)
df %>%
group_by(!!group_by) %>%
summarise(a = mean(a))
}
my_summarise(df, g1)
但是,如果我们将此函数包装在另一个函数中并进行调用,则它将无效。是因为名称只传递了一个级别吗?
wrapped_my_Summarize <- function(wdf, w_group_by){
my_summarise(wdf, w_group_by)
}
wrapped_my_Summarize(df, g1)
总的来说,我觉得上面的例子与
一起是冒险的答案 0 :(得分:8)
使用enquo
从符号转换为quosure,然后评估!!
的函数参数(my_summarise
)
wrapped_my_Summarize <- function(wdf, w_group_by){
w_group_by <- enquo(w_group_by)
my_summarise(wdf, !! w_group_by)
}
wrapped_my_Summarize(df, g1)
# A tibble: 2 x 2
# g1 a
# <dbl> <dbl>
#1 1.00 2.00
#2 2.00 3.67
identical(wrapped_my_Summarize(df, g1), my_summarise(df, g1))
#[1] TRUE