[R] Text dependent on a variable in a R function

Duncan Murdoch murdoch.duncan at gmail.com
Mon May 3 12:51:22 CEST 2010

Jim Lemon wrote:
> On 05/02/2010 10:00 PM, Duncan Murdoch wrote:
>> ...
>> I've seen this description a couple of times lately, and I think it's
>> worth pointing out that it's misleading. The deparse(substitute(x))
>> trick returns the *expression* that was passed to the argument x.
>> Sometimes that's the name of a variable, but not always, and I think
>> it's important to distinguish between names that need to be names, and
>> expressions that can consist of nothing but a name, but can also be
>> something else.
>> So this function
>> f <- function(x) deparse(substitute(x))
>> will return "1 + 1" if you call it as f(1 + 1).
> I'm very glad to know of this, but when I create a toy function like this:
> playdep<-function(x) print(str(deparse(substitute(x))))
> testvar<-1:5
> playdep(testvar)
> chr "testvar"
> which is the same as I get with a literal string, and consistent with 
> the help page for "deparse".
> "Turn unevaluated expressions into character strings."
> Unless I am mistaken, deparse just returns a string, whether or not it 
> is the name of a variable.

You aren't mistaken.  It returns a character vector (usually length 1, 
but it could be longer in case of a long expression) which is the 
deparsed version of the expression.

Duncan Murdoch

More information about the R-help mailing list