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)

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Exactly what i needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.