Home > Software engineering >  Getting the name of the assigned variable to an argument in a function
Getting the name of the assigned variable to an argument in a function

Time:02-27

I'd like to state the variable that has been assigned to an argument in a function. Function is more complex, but an example scenario is below, where I want the function to return the name of the variable: x

e.g.

x <- 3
my_function <- function(arg1) {print(arg1)}

where: my_function(x) will return x

and: my_function(y) will return y

Is this possible?

CodePudding user response:

Use substitute to return a symbol object. If we wrap with deparse on the substitute, it returns a character

my_function <- function(arg1) substitute(arg1)

-testing

> my_function(x)
x
> my_function(y)
y
  • Related