[Rd] merging environments

Gabor Grothendieck ggrothendieck at gmail.com
Fri Mar 7 21:02:20 CET 2008


You can either use the facilities of environments or
the proto package can do this if you take advantage of the fact
that a proto object is an environment:

> library(proto)
> f <- function() {}
> # put a into the environment of f
> do.call(proto, c(list(a = 1), envir = environment(f)))
<environment: R_GlobalEnv>
attr(,"class")
[1] "proto"       "environment"
> ls(environment(f))
[1] "a" "f"

which does what you ask although you might prefer to create
a new environment/proto object with f in it to avoid explicit
environment manipulation:

# create proto object, i.e. environment, with a and f in it
p <- proto(a = 1, f = function(.) {})

# and you can add more variables later:
p$b <- 2
p[["c"]] <- 3
ls(p)
with(p, ls(environment(f))) # same

or with environments not using proto:

# create an unnamed environment and put a and f in
# adding b and c to it later
f <- local({ a <- 1; function(){} })
environment(f)$b <- 2
environment(f)[["c"]] <- 3

ls(environment(f))

2008/3/7 Ben Bolker <bolker at zoo.ufl.edu>:
>
>   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?
> 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))
>
>
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>



More information about the R-devel mailing list