[R] Wrong environment when evaluating and expression?

Gabor Grothendieck ggrothendieck at gmail.com
Mon Jul 4 13:26:22 CEST 2011


On Mon, Jul 4, 2011 at 4:11 AM, Joshua Wiley <jwiley.psych at gmail.com> wrote:
> Hi All,
>
> I have constructed two expressions (e1 & e2).  I can see that they are
> not identical, but I cannot figure out how they differ.
>
> ###############
> dat <- mtcars
> e1 <- expression(with(data = dat, lm(mpg ~ hp)))
> e2 <- as.expression(substitute(with(data = dat, lm(f)), list(f = mpg ~ hp)))
>
> str(e1)
> str(e2)
> all.equal(e1, e2)
> identical(e1, e2) # false
>
> eval(e1)
> eval(e2)
> ################
>
> The context is trying to use a list of formulae to generate several
> models from a multiply imputed dataset.  The package I am using (mice)
> has methods for with() and that is how I can (easily) get the pooled
> results.  Passing the formula directly does not work, so I was trying
> to generate the entire call and evaluate it as if I had typed it at
> the console, but I am missing something (probably rather silly).
>

In e1, mpg ~ hp is a call object but in e2 its a formula with an environment:

> e1[[1]][[3]][[2]]
mpg ~ hp
> e2[[1]][[3]][[2]]
mpg ~ hp
>
> class(e1[[1]][[3]][[2]])
[1] "call"
> class(e2[[1]][[3]][[2]])
[1] "formula"
>
> environment(e2[[1]][[3]][[2]])
<environment: R_GlobalEnv>

-- 
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