I have a function that creates an environment within it and i wish to assign that environment to the global environment. At present i do this by assigning the environment to globalenv()
as the final step -- as follows:
我有一个在其中创建环境的功能,我希望将该环境分配给全局环境。目前我通过将环境分配给globalenv()作为最后一步来做到这一点 - 如下:
funfun <- function(inc = 1){
dataEnv <- new.env()
dataEnv$d1 <- 1 + inc
dataEnv$d2 <- 2 + inc
dataEnv$d3 <- 2 + inc
assign('dataEnv', dataEnv, envir = globalenv())
}
It feels like i should be able to do something to make dataEnv
persisit when the function funfun
ends (to save copying the environment at the end) however my attempts, such as dataEnv <- new.env(parent = globalenv())
, have not worked.
当函数funfun结束时(为了节省最后复制环境),我觉得应该能够做一些事情来使dataEnv persisit,但是我的尝试,例如dataEnv < - new.env(parent = globalenv()),没工作。
Why does it fail? Is this possible?
为什么会失败?这可能吗?
Also, what is the most efficient way of doing this?
另外,最有效的方法是什么?
My tables are very large at times, and the copying will become an issue as the project grows.
我的表有时非常大,随着项目的增长,复制将成为一个问题。
2 个解决方案
#1
5
Your environment is not being destroyed when you exit the function. You just need to return a reference to it.
退出函数时,您的环境不会被破坏。您只需要返回对它的引用。
funfun <- function(inc = 1){
dataEnv <- new.env(parent=globalenv())
dataEnv$d1 <- 1 + inc
dataEnv$d2 <- 2 + inc
dataEnv$d3 <- rnorm(10000)
return(dataEnv)
}
myEnv <- funfun()
object.size(myEnv)
Get some stuff out
得到一些东西
head(myEnv$d3)
#2
-1
Usually when I want to assign something to a global environment I just do
通常,当我想将某些东西分配给全球环境时,我就是这样做的
varname <<- value
#1
5
Your environment is not being destroyed when you exit the function. You just need to return a reference to it.
退出函数时,您的环境不会被破坏。您只需要返回对它的引用。
funfun <- function(inc = 1){
dataEnv <- new.env(parent=globalenv())
dataEnv$d1 <- 1 + inc
dataEnv$d2 <- 2 + inc
dataEnv$d3 <- rnorm(10000)
return(dataEnv)
}
myEnv <- funfun()
object.size(myEnv)
Get some stuff out
得到一些东西
head(myEnv$d3)
#2
-1
Usually when I want to assign something to a global environment I just do
通常,当我想将某些东西分配给全球环境时,我就是这样做的
varname <<- value