Skip to content
Prev 68752 / 398506 Next

Getting the name of an object as character

If you're trying to find the textual form of an actual argument, here's 
one way:

 > foo <- function(x) {
+     xn <- substitute(x)
+     if (is.name(xn) && !exists(as.character(xn)))
+         as.character(xn)
+     else
+         x
+ }
 > foo(x)
[1] 3
 > foo(xx)
[1] "xx"
 > foo(list(xx))
Error in foo(list(xx)) : Object "xx" not found
 >

If you want the textual form of arguments that are expressions, use 
deparse() and a different test (& beware that deparse() can return a 
vector of character data).

Although you can do this in R, it is not always advisable practice. 
Many people who have written functions with non-standard evaluation 
rules like this have come to regret it (one reason is that it makes 
these functions difficult to use in programs, another is that the 
behavior of the function can depend upon what global variables exists, 
another is that when the function works as intended, that's great, but 
when it doesn't, users can get quite confused trying to figure out what 
it's doing.)  The R function help() is an example of a commonly used 
function with a non-standard evaluation rule.

-- Tony Plate
Ali - wrote: