[R] Environment of a formula

Duncan Murdoch murdoch at stats.uwo.ca
Mon Feb 7 09:38:41 CET 2005


On Mon, 7 Feb 2005 04:39:40 +0000 (UTC), Gabor Grothendieck
<ggrothendieck at myway.com> wrote :

>Adrian Baddeley <adrian <at> maths.uwa.edu.au> writes:
>
>: I want to equip a data frame with an attribute 
>: which specifies how to plot some of the columns. 
>: 
>: Up to now we have been doing this by giving the data frame 
>: a `formula' attribute, that can be passed to plot.formula.
>: 
>: For example
>:       dat <- data.frame(x=1:100,y=runif(100),z=100:1)
>:       attr(dat, "plotme") <- (z ~ x)
>:       ......
>:       ......
>:       if(missing(desiredformula))
>: 	desiredformula <- attr(dat, "plotme")
>:       plot(desiredformula, data=dat)
>: 
>: We just got bitten by the fact that a formula object has a `.Environment'
>: attribute, which may be huge, depending on the environment
>: in which the formula was created. In the example above there is
>: no upper limit on the size of the object 'dat' !!!!
>: That is, environment(attr(dat, "plotme")) could be huge.
>
>Do you mean that if fo is the formula then ls(environment(fo))
>has many large components?   I don't understand why that would
>be a problem.

It can be a problem when you save a workspace.  For example, the
.Rdata file produced by this session is tiny:

> makef <- function() {
+     y ~ x
+ }
> fo <- makef()
> save.image()

while the file produced by this session is around 8 megabytes:

> makef <- function() {
+     z <- rnorm(1000000)
+     y ~ x
+ }
> fo <- makef()
> save.image()

You might assume that since z is local to the makef() call, and never
referenced by the formula, it wouldn't be saved:  but you'd be wrong.

>: It appears that we can't set the environment to NULL;
>: should we set it to the Global environment e.g. using as.formula?
>
>It works for me (R 2.1.0 Windows):
>
>R> fo <- y~x
>R> environment(fo)
><environment: R_GlobalEnv>
>R> environment(fo) <- NULL
>R> environment(fo)
>NULL

It works for me too, so I'm not sure what problem Adrian was having.  

Duncan Murdoch




More information about the R-help mailing list