Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: copy/move one environment to another

Tags:

I would like to ask if it is possible to copy/move all the objects of one environment to another, at once. For example:

f1 <- function() {     print(v1)     print(v2) }  f2 <- function() {     v1 <- 1     v2 <- 2      # environment(f1)$v1 <- v1         # It works     # environment(f1)$v2 <- v2         # It works          environment(f1) <- environment(f2) # It does not work }  f2() f1() 
like image 635
Apostolos Polymeros Avatar asked Apr 01 '12 15:04

Apostolos Polymeros


2 Answers

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  
like image 59
Tommy Avatar answered Sep 19 '22 18:09

Tommy


Try this:

f2 <- function() {     v1 <- 1     v2 <- 2     environment(f1) <<- environment() } 
like image 45
kohske Avatar answered Sep 17 '22 18:09

kohske