How to retain column name when passing strings as arguments in functions

Viewed 23

I have a function which takes a column name as an input:

library(tidyverse)

dat <- diamonds

ex_func <- function(df, grp) {
  df %>% 
    distinct(cut, get(grp))
}

ex_func(dat, grp = "color")

How exactly do I get the name of the second column in the resulting group to be the input (e.g. "color", rather than get(grp))?

1 Answers

If we are using both unquoted or quoted value, then use ensym and evaluate (!!)

library(dplyr)
ex_func <- function(df, grp) {
     df %>% 
           distinct(cut, !! rlang::ensym(grp))
   }   

-testing

ex_func(dat, "color")
# A tibble: 35 x 2
#   cut       color
#   <ord>     <ord>
# 1 Ideal     E    
# 2 Premium   E    
# 3 Good      E    
# 4 Premium   I    
# 5 Good      J    
# 6 Very Good J    
# 7 Very Good I    
# 8 Very Good H    
# 9 Fair      E    
#10 Ideal     J    
# … with 25 more rows

ex_func(dat, color)
# A tibble: 35 x 2
#   cut       color
#   <ord>     <ord>
# 1 Ideal     E    
# 2 Premium   E    
# 3 Good      E    
# 4 Premium   I    
# 5 Good      J    
# 6 Very Good J    
# 7 Very Good I    
# 8 Very Good H    
# 9 Fair      E    
#10 Ideal     J    
# … with 25 more rows

If we prefer to use only unquoted, the option is {{}}

ex_func <- function(df, grp) {
     df %>% 
           distinct(cut, {{grp}})
   }   
Related