R: copy/move one environment to another

前端 未结 7 2002
-上瘾入骨i
-上瘾入骨i 2020-12-14 02:01

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)
          


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 03:01

    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 
    

提交回复
热议问题