Search code examples
rdplyrquotesquasiquotes

Unquoting argument inside of function in R


I cannot figure out why the bang-bang operator in my function is not unquoting my grp argument. Any help would be much appreciated!

library(dplyr)

test_func <- function(dat, grp){
  dat %>%
    group_by(!!grp) %>%
    summarise(N =  n())
}

test_func(dat = iris, grp = "Species")

Instead of grouping by species it just produces the summary for the entire data: Output


Solution

  • If we are passing a string, then convert to symbol and evaluate (!!)

    test_func <- function(dat, grp){
     dat %>%
        group_by(!! rlang::ensym(grp)) %>%
        summarise(N =  n(), .groups = 'drop')
     }
    

    -testing

    test_func(dat = iris, grp = "Species")
    # A tibble: 3 x 2
    #  Species        N
    #* <fct>      <int>
    #1 setosa        50
    #2 versicolor    50
    #3 virginica     50
    

    Or another option is to use across

    test_func <- function(dat, grp){
        dat %>%
           group_by(across(all_of(grp))) %>%
           summarise(N =  n(), .groups = 'drop')
     }