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

Duncan Murdoch murdoch.duncan at gmail.com
Sun May 2 14:00:34 CEST 2010


On 02/05/2010 4:07 AM, Jim Lemon wrote:
> On 05/02/2010 11:56 AM, R K wrote:
>   
>> Hello,
>>
>> I was wondering if someone could tell me how I can make text dependent on a variable in a R function I have created.
>>
>> The function will create plots, thus I would like each plot to have a unique title based on the inputted variable as well as a unique file name when saved using the savePlot function.
>>
>>     
> Hi Rachel,
> I think what you are looking for is the somewhat obscure:
>
> deparse(substitute(x))
>
>   

Yes.

> that returns the name of a variable as a character string.
>   

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).

Duncan Murdoch



More information about the R-help mailing list