[Rd] merging environments

Duncan Murdoch murdoch at stats.uwo.ca
Fri Mar 7 20:23:40 CET 2008


On 3/7/2008 2:02 PM, Ben Bolker wrote:
>    Despite the spirited arguments of various R-core folks
> who feel that mle() doesn't need a "data" argument, and
> that users would be better off learning to deal with function
> closures, I am *still* trying to make such things work
> in a reasonably smooth fashion ...
> 
>    Is there a standard idiom for "merging" environments?

One way is to set one as the parent of the other.  If they both already 
have non-empty parents, you're out of luck.

> i.e., suppose a function has an environment that I want
> to preserve, but _add_ the contents of a data list --
> would something like this do it? Is there a less ugly
> way?
> 
> x <- 0
> y <- 1
> z <- 2
> 
> f <- function() {
>      x+y+z
> }
> 
> f2 <- function(fun,data) {
>      L <- ls(pos=environment(fun))
>      mapply(assign,names(data),data,
>                       MoreArgs=list(envir=environment(fun)))
>      print(ls(pos=environment(fun)))
> }
> 
> f2(f,list(a=1))

Luckily lists and data.frames don't have parents, so you can make a new 
environment, put the elements of data into it, and set the old 
environment as its parent.  That's sort of like what you did, but 
slightly different, and with fewer bad side effects:

bothenvs <- function(fun,data) {
      newenv <- new.env(hash=TRUE, parent=environment(fun))
      mapply(assign,names(data),data,
                       MoreArgs=list(envir=newenv))
      newenv
}

It would sure be nice if as.environment() took a list as an arg and 
turned it into an environment, but no such luck.

Duncan Murdoch

> 
> 
> 
> 
> ------------------------------------------------------------------------
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list