Search code examples
rfunctiontidyeval

recording the passed value in a function call in R


When I write call a function, I would like to record in the output of the function one or more of the parameters that were passed to the function. When the function parameter points to another object, I can't figure out how to do that. I've tried various combinations of quo and expr etc...but seem to be missing the exact syntax to pass a string variable into a data.frame as follows:

 library(tidyverse)
 awesomedf <- data.frame(a = 1:5, b= "hihi")
 
 myfunction <- function(usedata = awesomedf){
   usedata %>% 
     summarize(meancol1 = mean(a)) %>% 
     mutate(datasetused = deparse(substitute(usedata)))
 }
 
 myfunction()

Returns:

  meancol1 datasetused
1        3     usedata

What I would like to see is:

  meancol1 datasetused
1        3     awesomedf

Solution

  • Use the deparse/substitute at the top to capture it before it becomes an evaluated expression

    myfunction <- function(usedata = awesomedf){ 
    val <- deparse(substitute(usedata))
      usedata %>% 
        summarize(meancol1 = mean(a)) %>% 
      mutate(datasetused = val)
     }
    

    -testing

    myfunction()
    #   meancol1 datasetused
    #1        3   awesomedf