0

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.

ulfelder
  • 5,305
  • 1
  • 22
  • 40
Magnus Nordmo
  • 923
  • 7
  • 10

1 Answers1

4

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you Ronak! If you have a resource (book or website) that covers this topic i would like to learn more about it. – Magnus Nordmo Dec 06 '19 at 11:30
  • 1
    @MagnusNordmo I haven't gone through it myself but you could start from the official announcement here https://www.tidyverse.org/blog/2019/06/rlang-0-4-0/ where they explain curly-curly (`{{}}`) with some examples. – Ronak Shah Dec 06 '19 at 11:32