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

Søren Højsgaard Soren.Hojsgaard at agrsci.dk
Fri Nov 26 14:48:02 CET 2010


Thanks, but I think there is a small mistake in your code:

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

I think it should be:
> as.expression(do.call("substitute", list(expr[[1]], list(a=1))))
expression(1 + b + c)
- or maybe it can be done in a simpler way?

Regards
Søren


-----Oprindelig meddelelse-----
Fra: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Sendt: 26. november 2010 14:39
Til: Søren Højsgaard
Cc: r-help at stat.math.ethz.ch
Emne: Re: [R] Calling substitute(expr, list(a=1)) when expr <- expression(a+b+c)

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