Search code examples
rdplyrrlangnon-standard-evaluation

Is there a way to input dplyr::summarise variables?


This is a non-standard-evaluation problem I can't seem to solve. I want to make a function that inputs a column name and outputs a summary. For this function, it's important that the summarise(name,...) can be assigned as input like so:

mtcars %>% 
  summarise(mpg = mean(mpg))

This works:

get <- function(col){
  mtcars %>% 
    summarise(mean = mean({{ col }}))
}

get(mpg)

But this does not, and this is what I need.

get <- function(col){
  mtcars %>% 
    summarise({{ col }} = mean({{ col }}))
}

Any help is greatly appreciated.


Solution

  • Use := notation to assign column names

    library(dplyr)
    
    get_summarised<- function(df, col){
      df %>% summarise({{col}} := mean({{ col }}))
    }
    
    get_summarised(mtcars, mpg)
    #       mpg
    #1 20.09062