1

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)

Samuel Saari
  • 1,023
  • 8
  • 13

1 Answers1

2

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)
  • Appreciated! And if I would like to use the dataframe "mi_d" inside "print_data_1", how would I do that? I would need to refer to the dataframe as text and in some other parts of the function refer to it as a data frame. – Samuel Saari May 14 '21 at 14:27
  • 1
    Well, you can just use the `DATA` variable on its own. Or you can use `!!` to unquote it inside of a function. Or you can use `eval_tidy()` on the quosure. –  May 14 '21 at 14:40
  • Exactly what i needed. – Samuel Saari May 18 '21 at 06:58