0

How do you make a function with piping that takes a variable name as an input? I am trying to make a more complicated version of the below function usable. Thanks!

test <- function(var){
  iris %>%
    group_by(Species) %>%
    summarise(mean(var, na.rm=TRUE))
}
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
gecko
  • 109
  • 5

1 Answers1

2

You just need to use the operator {{}}, here a reference for more details.

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
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32