Extracting parameter names in nested functions in R

Viewed 122

I would like to extract the name of a function parameter as a string.

It works fine unless the function is called from within another function (see below).

There must be a simple solution for this, just cannot seem to find one.

library(reprex)
print_data_1 <- function(DATA) {
  DATA_txt <- deparse(substitute(DATA))
  print(DATA_txt)
}

print_data_2 <- function(DF) {
  print_data_1(DF)
}

print_data_1(mi_d)
#> [1] "mi_d"
print_data_2(mi_d)
#> [1] "DF"

print_data_2 should return "mi_d".

Created on 2021-05-14 by the reprex package (v2.0.0)

1 Answers

Here is a way using rlang. This stuff gets pretty advanced in a hurry.

library(rlang)

print_data_1 <- function(DATA) {
  .DATA <- enquo(DATA)
  .DATA_txt <- as_name(.DATA)
  
  print(.DATA_txt)
}

print_data_2 <- function(DF) {
  .DF <- enquo(DF)
  
  print_data_1(!!.DF)
}

print_data_1(mi_d)
#> [1] "mi_d"
print_data_2(mi_d)
#> [1] "mi_d"

And so on...

print_data_3 <- function(X) {
  .X <- enquo(X)
  
  print_data_2(!!.X)
}

print_data_3(mi_d)
#> [1] "mi_d"
  • enquo() will quote the user argument.
  • !! will unquote the argument into the function.
  • as_name() will convert the quoted argument into character.

The cheatsheet is pretty helpful, as are the rlang vignettes.

To get the value of that object back, you can use eval_tidy() on the quosure.

print_data_1 <- function(DATA) {
  .DATA <- enquo(DATA)
  .DATA_txt <- as_name(.DATA)
  
  df <- eval_tidy(.DATA)
  
  print(.DATA_txt)
  df
}

print_data_2(mtcars)
Related