The problem is scope -- the environment in which substitute() looks for x.

Try:



foo <- function(x){ deparse(substitute(x,env=parent.frame()))}
a<-1
foo(a)

bar <- function(x)foo(x)
bar(a)

-- Bert

2011/8/18 David Winsemius <dwinsem...@comcast.net>:
>
> On Aug 18, 2011, at 5:11 PM, Ernest Adrogué wrote:
>
>> Hi,
>>
>> I don't know much about R's deparsing "magic", I simply use the
>> deparse(substitute(arg)) trick to get the names of the variables
>> passed as arguments to the function in order to set labels, etc.
>>
>> The problem is that this doesn't work with nested functions. For
>> example,
>>
>>> foo <- function(x) print(deparse(substitute(x)))
>>> a=1
>>> foo(a)
>>
>> [1] "a"
>>
>> This is OK. However,
>>
>>> bar <- function(x) foo(x)
>>> bar(a)
>>
>> [1] "x"
>>
>> this is not what I want. I wanted bar(a) to print "a" not "x". Is it
>> possible to do this?
>
>> bar <- function(x) class(substitute(foo(x)))
>> bar(a)
> [1] "call
>
> So...
>
>> bar <- function(x) substitute(foo(x))[[2]]
>> bar(a)
> a
>
> --
>
> David Winsemius, MD
> West Hartford, CT
>
> ______________________________________________
> R-help@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.
>



-- 
"Men by nature long to get on to the ultimate truths, and will often
be impatient with elementary studies or fight shy of them. If it were
possible to reach the ultimate truths without the elementary studies
usually prefixed to them, these would not be preparatory studies but
superfluous diversions."

-- Maimonides (1135-1204)

Bert Gunter
Genentech Nonclinical Biostatistics

______________________________________________
R-help@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.

Reply via email to