From murdoch at stats.uwo.ca  Fri Sep 15 01:24:32 2006
From: murdoch at stats.uwo.ca (Duncan Murdoch)
Date: Thu, 14 Sep 2006 19:24:32 -0400
Subject: [Rd] Question about substitute() and function def
In-Reply-To: <4509B22D.1050604@fhcrc.org>
References: <m2d59y8e7o.fsf@ziti.fhcrc.org> <4509AFA4.6010203@stats.uwo.ca>
	<4509B22D.1050604@fhcrc.org>
Message-ID: <4509E4B0.4020702@stats.uwo.ca>

On 9/14/2006 3:49 PM, Robert Gentleman wrote:
> 
> Duncan Murdoch wrote:
>> On 9/14/2006 3:01 PM, Seth Falcon wrote:
>>> Hi,
>>>
>>> Can someone help me understand why
>>>
>>>   substitute(function(a) a + 1, list(a=quote(foo)))
>>>
>>> gives
>>>
>>>   function(a) foo + 1
>>>
>>> and not
>>>
>>>   function(foo) foo + 1
>>>
>>> The man page leads me to believe this is related to lazy evaluation of
>>> function arguments, but I'm not getting the big picture.
>> I think it's the same reason that this happens:
>>
>>  > substitute(c( a = 1, b = a), list(a = quote(foo)))
>> c(a = 1, b = foo)
>>
>> The "a" in function(a) is the name of the arg, it's not the arg itself 
> 
> yes, but the logic seems to be broken. In Seth's case there seems to be 
> no way to use substitute to globally change an argument and all 
> instances throughout a function, which seems like a task that would be 
> useful.

I think variables and argument names are fundamentally different things, 
so I don't see this as very surprising.  It should take two steps to 
make a change like that.  Use substitute() to change the variables, put 
the result in f, change the names of the formals using

names(formals(f)) <- "foo".

I'm not sure if there's a simple way to change the first "a" in the 
expression c(a=1, b=a), but there are probably convoluted ways to do it.

> 
> even here, I would have expected all instances of a to change, not some
> 
>> (which is missing).  Now a harder question to answer is why this happens:
>>
>>  > substitute(function(a=a) 1, list(a=quote(foo)))
>> function(a = a) 1
> 
>    a bug for sure

Yes.

Duncan




[Rd] Question about substitute() and function def
Duncan Murdoch