Skip to content
Prev 20068 / 63424 Next

Return function from function with minimal environment

On Tue, 4 Apr 2006, Roger D. Peng wrote:

            
You can, but you really don't want to and you will get the same error. A 
'minimal environment' is baseenv(), since you are not going to be able to 
do very much without the primitives such as * (and even "{"), and 
(relevant here) you will never save anything from it so it will cost you 
nothing.  In this example, 'scale' is supposed to being picked up from the 
environment.  So (removing all the empty statements to save memory)

foo <- function(huge) {
   scale <- mean(huge)
   env <- new.env(parent=baseenv())
   assign("scale", scale, envir=env)
   bar <- function(x) { scale * x }
   environment(bar) <- env
   bar
}

is I think minimal baggage (and fcn saves in 153 bytes).