Alessandro Bitetto
Alessandro Bitetto

Reputation: 129

R get object name when is input of another function

I'd like to get the name of an object that is inputed into a function with another name. Given

new_object = 10
fun1 <- function(fun_input){
  ...
}

fun1(fun_input = new_object)

The desired output of fun1 should be the string "new_object".

I tried deparse and substitute as suggested in the solution posted here but I only get "fun_input" as output. Thanks

Upvotes: 1

Views: 332

Answers (2)

TarJae
TarJae

Reputation: 78937

Maybe you are looking for this:

I suspect that in your function you are doing (evaluating) fun_input with further steps (for example a loop etc...) The thing is that from the time you first use fun_input it is an evaluated expression (quasi the result). To avoid this we have to capture fun_input with substitute.

Now you get an object new_object that can be treated as a list:

fun1 <- function(fun_input) {
  substitute(fun_input)
}

fun1(new_object)
new_object

new_object[[1]]
[1] 10

Upvotes: 0

benson23
benson23

Reputation: 19097

Can you share your code? I have no problem getting the output.

new_object = 10
new_object
[1] 10

fun1 <- function(fun_input) {
   deparse(substitute(fun_input))
}

fun1(new_object)
[1] "new_object"

Upvotes: 3

Related Questions