将变量从数据集传递到调用 dplyr 的函数中

Pass variable from dataset into a function that calls dplyr

如何使用将变量名称作为输入的管道创建函数?我正在尝试使以下功能的更复杂版本可用。谢谢!

test <- function(var){
  iris %>%
    group_by(Species) %>%
    summarise(mean(var, na.rm=TRUE))
}

您只需要使用运算符 {{}},这里是 reference 了解更多详情。

test<-function(var){
  iris %>% group_by(Species) %>% summarise(mean({{var}}, na.rm=TRUE))
}

test(Sepal.Width)

# A tibble: 3 x 2
  Species    `mean(Sepal.Width, na.rm = TRUE)`
  <fct>                                  <dbl>
1 setosa                                  3.43
2 versicolor                              2.77
3 virginica                               2.97