Search code examples
rdataframefunctiontidyverserlang

Capture the name of an input value in a function


I was wondering if there is a way to capture the input to the argument study_id in my function below.

For example, my desired output in the below example is: "study". Is this possible?

library(rlang)

foo <- function(data, study_id){
  
  study_id <- ensym(study_id)
  
# names(data[study_id]) # I tried this without success
}
  
# EXAMPLE OF USE:

dat = data.frame(a=1:3,study=4:6)

foo(dat, study_id = study)

# DESIRED OUTPUT:

> [1] "study"

Solution

  • We could use as_string

    foo <- function(data, study_id){
      
      study_id <- ensym(study_id)
      
      as_string(study_id)
    }
    

    -testing

    foo(dat, study_id = study)
    [1] "study"
    

    In base R, this can be done with deparse/substitute

    foo1 <- function(data, study_id) deparse(substitute(study_id))
    foo1(dat, study_id = study)
    [1] "study"