[R] Calling substitute(expr, list(a=1)) when expr <- expression(a+b+c)

Gabor Grothendieck ggrothendieck at gmail.com
Fri Nov 26 14:39:01 CET 2010


On Fri, Nov 26, 2010 at 8:31 AM, Søren Højsgaard
<Soren.Hojsgaard at agrsci.dk> wrote:
> # The result I am after is the result after a substitution in an expression, such as
>
> substitute(expression(a+b+c), list(a=1))
> expression(1 + b + c)
>  # However, the way I want to do it is for a an expression "stored as a variable" as
>
> (expr <- expression(a+b+c))
> expression(a + b + c)
>  # a) The following does not work
>
> (expr2 <- substitute(expr, list(a=1)))
> expr
>  # b) - whereas this does work:
>
> ans <- eval(substitute(substitute(qqq, list(a=1)), list(qqq=expr[[1]])))
> as.expression(ans)
> expression(1 + b + c)
>  # I have - at least - two problems:
> # I am not sure I understand 1) why a) does not work and 2) why b) does work.
> # Can anyone point me in the right direction?
>

It does not evaluate its argument so if expr is the first argument
about the only thing you can substitute is expr itself:

> substitute(expr, list(expr = 3))
[1] 3

Try this:

> expr <- expression(a+b+c)
> do.call("substitute", list(expr, list(a=1)))
expression(a + b + c)



-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list