2

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 Answer 1

2

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}})
   }   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.