R: copy/move one environment to another

There seem to be at least 3 different things you can do:

  1. Clone an environment (create an exact duplicate)
  2. Copy the content of one environment to another environment
  3. Share the same environment

To clone:

# Make the source env
e1 <- new.env()
e1$foo <- 1
e1$.bar <- 2   # a hidden name
ls(e1) # only shows "foo"

# This will clone e1
e2 <- as.environment(as.list(e1, all.names=TRUE))

# Check it...
identical(e1, e2) # FALSE
e2$foo
e2$.bar

To copy the content, you can do what @gsk showed. But again, the all.names flag is useful:

# e1 is source env, e2 is dest env
for(n in ls(e1, all.names=TRUE)) assign(n, get(n, e1), e2)

To share the environment is what @koshke did. This is probably often much more useful. The result is the same as if creating a local function:

f2 <- function() {
  v1 <- 1 
  v2 <- 2

  # This local function has access to v1 and v2
  flocal <- function() {
    print(v1)
    print(v2)
  }

  return(flocal)
} 

f1 <- f2()
f1() # prints 1 and 2 

Try this:

f2 <- function() {
    v1 <- 1
    v2 <- 2
    environment(f1) <<- environment()
}

You could use assign:

f1 <- function() {
  print(v1)
  print(v2)
}

f2 <- function() {
  v1 <- 1
  v2 <- 2

  for(obj in c("v1","v2")) {
    assign(obj,get(obj),envir=f1.env)
  }
}

If you don't want to list out the objects, ls() takes an environment argument.

And you'll have to figure out how to get f1.env to be an environment pointing inside f1 :-)

Tags:

R