1

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.

Setjmp
  • 27,279
  • 27
  • 74
  • 92
  • Can you clarify what you'd like to reset? A lot can change in a workspace, such as the objects, the loaded packages, the directory, the random seed, various environment and configuration values. – Iterator Nov 16 '11 at 00:46
  • Iterator - I edited the question in response. Thanks! – Setjmp Nov 16 '11 at 21:29

2 Answers2

2

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)   
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • This is very helpful. However, I notice that loaded packages remain loaded. Is there any mechanism to "unload" them? – Setjmp Nov 17 '11 at 20:20
  • Sure. If, for example, you've loaded the `lattice` package, you can "unload" it (a.k.a. "detach from the search path") with `detach("package:lattice")`. You can do the same with any of the packages that are attached (try `search()` to see them), except for `package(base)`. You probably don't want to detach any of the packages that are loaded by default (including `"package:graphics:"` and `"package:grDevices"`)... – Josh O'Brien Nov 17 '11 at 21:46
0

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.

lgautier
  • 11,363
  • 29
  • 42