Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python rpy2 module: refresh global R environment

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.

like image 846
Setjmp Avatar asked Dec 01 '25 20:12

Setjmp


1 Answers

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)   
like image 156
Josh O'Brien Avatar answered Dec 03 '25 12:12

Josh O'Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!