efficiently move environment from inside function to global environment

流过昼夜 提交于 2019-12-07 04:56:20

问题


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:

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.

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.


回答1:


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:


Usually when I want to assign something to a global environment I just do

varname <<- value


来源:https://stackoverflow.com/questions/21177499/efficiently-move-environment-from-inside-function-to-global-environment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!