[R] substitute question
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Thu Mar 18 22:33:53 CET 2004
"Gabor Grothendieck" <ggrothendieck at myway.com> writes:
> Tony, Thomas, Thanks, again.
>
> If the problem with my last example was just that I was passing a function
> rather than an unevaluated expression, then why don't the following
> return f with b in place of a? In both cases, a is still there in the
> final output.
>
> f <- function() { a + 1 }
> z <- substitute(substitute(f=f,list(a=quote(b))),list(f=parse(text=deparse(f))))
> eval(eval(z))
>
> or
>
> f <- function() { a + 1 }
> z <- substitute(substitute(expression(f),list(a=quote(b))),list(f=f))
> eval(eval(eval(z)))
As far as I can see you don't quote *the expression that creates f* in
either of the above
f <- quote(function() { a + 1 })
attr(f,"source") <- NULL
g <- eval(substitute(substitute(f, list(a=quote(b))),list(f=f)))
g
g() # oops, g is not a function but a call to "function"
g <- eval(g)
b <- 500
g()
If you have only the function to begin with, try something along these
lines
f <- function() { a + 1 }
g <- f
attr(g,"source") <- NULL
body(g) <- eval(substitute(substitute(f, list(a=quote(b))),list(f=body(f))))
g
g()
(The real pain in these examples is that substitute autoquotes its
expr argument. Therefore, when you want to modify an expression that
is already stored in a variable, you need an extra outer layer of
eval(substitute(...)) to poke the content of the variable into the
inner substitute. An "esub" function with standard evaluation
semantics would make this much easier.)
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list