Home > Mobile >  How to Pass a Column Name into a function that uses summary in R
How to Pass a Column Name into a function that uses summary in R

Time:07-21

I was wondering how to write a function that summarizes a value based off a function argument.

Here is what I would like to write a function for:

iris %>% 
  group_by(Species) %>% 
  summarize(mean = mean(Petal.Length))

find_mean <- function(search_term){
  iris %>% 
    group_by(Species) %>% 
    summarize(mean = mean(search_term))
}

find_mean("Petal.Length")

Thanks!

CodePudding user response:

Use get

find_mean <- function(search_term){
  iris %>% 
    group_by(Species) %>% 
    summarize(mean = mean(get(search_term)))
}

CodePudding user response:

... or you can make use of the bang-bang operator !!as.name() as I just learned in this post.

find_mean <- function(search_term){
  iris |>  
    dplyr::group_by(Species) |>  
    dplyr::summarize(mean = mean(!!as.name(search_term)))
}

find_mean("Petal.Length")
#> # A tibble: 3 × 2
#>   Species     mean
#>   <fct>      <dbl>
#> 1 setosa      1.46
#> 2 versicolor  4.26
#> 3 virginica   5.55
  •  Tags:  
  • r
  • Related