[R] substitute question
Thomas Lumley
tlumley at u.washington.edu
Thu Mar 18 18:00:02 CET 2004
On Wed, 17 Mar 2004, Gabor Grothendieck wrote:
>
>
> I left out the brackets in my last email but the problem
> (a reappears after have been substituted out) still remains:
>
> > z <- substitute( function(){a+1}, list(a=quote(b)) )
> > z
> function() {
> b + 1
> }
> > eval(z)
> function(){a+1}
Interesting.
Appearances are misleading, however:
> z <- substitute( function(){a+1}, list(a=quote(b)) )
> z
function() {
b + 1
}
> f<-eval(z)
> f()
Error in f() : Object "b" not found
> f
function(){a+1}
> attr(f,"source")<-NULL
> f
function ()
{
b + 1
}
So it isn't that eval(z) has a+1 inside, it just has a "source" attribute
with a+1.
Looking more carefully at z
> as.list(z)
[[1]]
`function`
[[2]]
NULL
[[3]]
{
b + 1
}
[[4]]
[1] "function(){a+1}"
so the original construction of z has kept the source (not, however, as a
"source" attribute).
There is method to our madness here. It is impossible (or at least too
complicated) to keep comments in the right place as a function is
parsed and deparsed. In the old days, comments would occasionally move
around, sometimes in very misleading ways (IIRC with if(){}else{} cases)
Now we keep a copy of the source code with functions created interactively
or with source(), and drop the comments on parsing. This is controlled by
options("keep.source").
If you do a lot of substitute()-style programming you may want
options(keep.source=FALSE).
-thomas
PS: There are, of course, interesting possibilities for creative abuse of
the source attribute....
More information about the R-help
mailing list