1

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

2 Answers2

3

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"
benson23
  • 16,369
  • 9
  • 19
  • 38
0

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
TarJae
  • 72,363
  • 6
  • 19
  • 66
  • Surely the last expression `new_object[[1]]` is just evaluating the global variable `new_object`, it has nothing to do with `fun1`. It wouldn't work if `new_object` was in some other environment. – user2554330 Jan 28 '22 at 09:50
  • but then the output would be a "symbol" but not string, which could be a problem if you direct the output to some other function (e.g. `data.frame()` do not accept "symbol") – benson23 Jan 28 '22 at 11:55