Re: [R] Getting the name of an object as character

From: Tony Plate <>
Date: Fri 29 Apr 2005 - 04:05:23 EST

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

 > foo <- function(x) {

+     xn <- substitute(x)
+     if ( && !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.

Ali - wrote:
> This could be really trivial, but I cannot find the right function to
> get the name of an object as a character.
> Assume we have a function like:
> getName <- function(obj)
> Now if we call the function like:
> getName(blabla)
> and 'blabla' is not a defined object, I want getName to return "blabla".
> In other word, if
> paste("blabla")
> returns
> "blabla"
> I want to define a paste function which returns the same character by:
> paste(blabla)
> ______________________________________________
> mailing list
> PLEASE do read the posting guide!
> mailing list PLEASE do read the posting guide! Received on Fri Apr 29 04:11:15 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:28 EST