[R] Substitute in function calling a function

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Oct 22 10:45:18 CEST 2007


I am not sure what the general rule you are looking for is.  Using 
deparse(substitute()) gets you the print-value of the expression (in your 
case a name) for the actual argument.  But if you want to go back 
generations of calls, then just when do you stop?

What you can do is write fun2 to use substitute() to create a call with 
actual argument 'var', but then you need to ensure that var exists in the 
local frame.

I find your code unreadable: please follow the advice in 'Writing R 
Extensions' when posting code.  Here's a sketch:

fun <- function(x) deparse(substitute(x))

fun2 <- function(y)
{
    nm <- deparse(substitute(y))
    assign(nm, y)
    eval(substitute(fun(x), list(x = nm)))
}



On Mon, 22 Oct 2007, Steve Powell wrote:

> Dear list members,
> I am writing some functions to help with printing graphs.
> If I want to return the name of a variable within a function, for instance
> to print the label for a graph, I know that I can use substitute:
> fun=function(x) substitute(x)   #plus of course some other processing
> var=1:3
> fun(var) #prints "var" as required, not "x".
>
> But if I call this function in another function
> fun2=function(y) fun(y) #plus of course some other processing
> fun2(var) #prints "y" when what I wanted was "var"
>
> I have tried lots of tricks using eval and expression but can't seem to get
> it right. Any ideas?
> Thanks in advance
>
> Steve Powell
>
> proMENTE social research
> research | evaluation | training & consulting
>
> Kranj?evi?eva 35, 71000 Sarajevo
> mobile: +387 61 215 997 | office: +387 33 556 865 | fax: +387 33 556 866
> skype: stevepowell99
> www.promente.org
>
>
>
>
> Checked by AVG Free Edition.
>
> 19.10.2007
> 05:10
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list