How can I capture function arguments as strings in R?

Viewed 145

I want to capture the incoming arguments that I'm passing to a function. How can I do this? The function below isn't quite what I want. The output I want is "Using mtcars and am". I was under the impression rlang could help with this, but I haven't been able to find a function to get the job done.

fx_capture<- function(fx_data, fx_var) {
  name_data <- quote(fx_data)
  name_var  <- quote(fx_var)
  paste("Using", name_data, "and", name_var)
}

fx_capture(mtcars, am)
> "Using fx_data and fx_var"
2 Answers

We can use deparse(substitute

fx_capture<- function(fx_data, fx_var) {

     name_data <- deparse(substitute(fx_data))
     name_var <- deparse(substitute(fx_var))

     paste("Using", name_data, "and", name_var)
}

fx_capture(mtcars, am)

Or with match.call

fx_capture<- function(fx_data, fx_var) {

   paste0("Using ", do.call(paste, c(lapply(match.call()[-1], 
              as.character), sep = ' and ')))
  
  
}

fx_capture(mtcars, am)

Here is an option using sys.call

fx_capture<- function(fx_data, fx_var) {
  paste0("Using ", paste0(sys.call()[-1],collapse = " and "))
}

such that

> fx_capture(mtcars, am)
[1] "Using mtcars and am"
Related