Skip to content
Prev 45633 / 63421 Next

how to control the environment of a formula

On 13-04-19 2:57 PM, Thomas Alexander Gerds wrote:
Yes, this is tricky.  The problem is that "out" is in the environment of 
out$f, so you get two copies when you save it.  (I think you won't have 
two copies in memory, because R only makes a copy when it needs to, but 
I haven't traced this.)

Here are two solutions, both have some problems.

1.  Don't put out in the environment:

test <- function(x) {
   x <- rnorm(1000000)
   out$x <- list(x=x)
   out$f <- a ~ b    # the as.formula() was never needed
   # temporarily create a new environment
   local({
     # get a copy of what you want to keep
     out <- out
     # remove everything that you don't need from the formula
     rm(list=c("x", "out"), envir=environment(out$f))
     # return the local copy
     out
   })
}

I don't like this because it is too tricky, but you could probably wrap 
the tricky bits into a little function (a variant on return() that 
cleans out the environment first), so it's probably what I would use if 
I was desperate to save space in saved copies.

2. Never evaluate the formula in the first place, so it doesn't pick up 
the environment:

test <- function(x) {
   x <- rnorm(1000000)
   out$x <- list(x=x)
   out$f <- quote(a ~ b)
   out
}

This is a lot simpler, but it might not work with some modelling 
functions, which would be confused by receiving the model formula 
unevaluated.  It also has the problems that you get with using 
.GlobalEnv as the environment of the formula, but maybe to a slightly 
lesser extent:  rather than having what is possibly the wrong 
environment, it doesn't have one at all.

Duncan Murdoch