0

How do I tell a function to output the name of the input?

For example:

test <- function (thisisthename) {
print (thisisthename)
}

input <- apple

Now if I do:

test(input) 

it will output

"apple" 

but how do I make it output "input," as "input" is the name of the input?

SocraticDatum
  • 349
  • 2
  • 4
  • 15

2 Answers2

1

Try:

test <- function (thisisthename) {
    substitute(thisisthename)
}

or use deparse(substitute(thisisthename)) if you need it with quotes.

Fanny
  • 310
  • 3
  • 4
  • 8
0

Calling substitute(x) returns the parse tree (the internal representation of the argument x) to which the variable x refers, and deparese takes a parse tree and returns a string with an R code representation of that parse tree. Hence, FUN returns a string representation of the argument x:

FUN = function(x)deparse(substitute(x))

Just remember that deparse does the opposite of parsing - which is taking code and generating the symbolic tree that R can evaluate. Hence, FUN returns the expression, which can be the variable name as in:

FUN(x=foo)
#> "foo"

or an expression:

FUN(x=1:2 + 3)
#> 1:2 + 3

Note that deparsing does not exactly recapitulate the code text that was entered:

FUN(x=1:2+3)
#> 1:2 + 3
FUN(x=1:2      +       3)
#> 1:2 + 3

and that deparse(substitute(x)) works for ordinary variables, not just function arguments:

y = 1:2 + 3
deparse(substitute(y))
#> 1:2 + 3
Jthorpe
  • 9,756
  • 2
  • 49
  • 64