Suppose that the function
foo
foo <- function () {
a <- 42
b <- "a string"
x <- FALSE
environment()
}
bar
foo
bar <- function () {
a <- 0
z <- pi
cat("before\n")
print(ls.str())
INSTANTIATE(foo())
cat("after\n")
print(ls.str())
}
INSTANTIATE
INSTANTIATE(foo())
instantiate the environment returned byin the current enviroment.foo()
foo()
foo()
bar()
> bar()
before
a : num 0
z : num 3.14
after
a : num 42
b : chr "a string"
x : logi FALSE
z : num 3.14
INSTANTIATE(foo())
bar()
foo
INSTANTIATE(foo())
bar <- function () {
a <- 0
z <- pi
cat("before\n")
print(ls.str())
list2env(as.list(foo()))
cat("after\n")
print(ls.str())
}
> bar()
before
a : num 0
z : num 3.14
after
a : num 0
z : num 3.14
How about something like this
import_env <- function(env, to=parent.frame()) {
vars <- ls(envir=env)
for(v in vars) {
assign(v, get(v, env),to)
}
}
Tested with
foo <- function () {
a <- 42
b <- "a string"
x <- FALSE
environment()
}
bar <- function () {
a <- 0
z <- pi
cat("before\n")
print(ls.str())
import_env(foo())
cat("after\n")
print(ls.str())
}
bar()
# before
# a : num 0
# z : num 3.14
# after
# a : num 42
# b : chr "a string"
# x : logi FALSE
# z : num 3.14
Basically we just iterate the environment and assign all the variables over. This should work for atomic types. Things get a bit trickier if you ever tried to copy over functions or formulas which hold on to the environment where they were created.