python rpy2 module: refresh global R environment

与世无争的帅哥 提交于 2019-12-11 10:29:40

问题


The documentation for rpy2 states that the robjects.r object gives access to an R global environment. Is there a way to "refresh" this global environment to its initial state?

I would like to be able to restore the global environment to the state it was in when the rpy2.robjects module was imported but not yet used. In this manner, I don't have to worry about memory leaks on long running jobs or other unexpected side effects. Yes, refreshing the environment could introduce a different category of bug, but I believe in my case it will be a win.


回答1:


Taking your question to mean literally what it says, if you just want to clear out .GlobalEnv, you can do that with a single line:

rm(list = ls(all.names=TRUE))

The all.names=TRUE bit is necessary because some object names are not returned by vanilla ls(). For example:

x <- rnorm(5)
ls()
# [1] "x"

# Doesn't remove objects with names starting with "."
rm(list=ls())
ls(all.names = TRUE)
# [1] ".Random.seed"

# Removes all objects
rm(list = ls(all.names=TRUE))
ls(all.names = TRUE)
# character(0)   



回答2:


There is only /one/ "global environment" in R; it is initialized when R starts. You can clear out its members, as Josh points it out, but if you happen to need to it this might mean that you'd better instanciate new environments and either switch between them or delete them when no longer needed.



来源:https://stackoverflow.com/questions/8144956/python-rpy2-module-refresh-global-r-environment

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