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()
There seem to be at least 3 different things you can do:
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With