> 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:
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)
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
