3

I need to load and detach a lot of packages in one R session (I'm looking at which functions are methods across different packages). detach() doesn't work for what I want, because it doesn't remove everything from the environment; for example, if you run:

require(pomp)
detach('package:pomp', character.only = TRUE)
print(methods('show'))

the show,pomp.fun-method is still listed, which is not a method that exists in base R. How do I remove all methods and objects associated with a package? Alternately, is there a way to create a temporary environment in R to load the package, which I can then destroy to remove all objects in methods in a package?

Eli Sander
  • 1,228
  • 1
  • 13
  • 29
  • use packrat http://stackoverflow.com/questions/24283171/virtual-environment-in-r – Bg1850 Dec 10 '15 at 23:55
  • 1
    Try `detach('package:pomp', unload = TRUE, character.only = TRUE)` – ialm Dec 10 '15 at 23:55
  • Or `devtools::unload(pkg = "pomp")`. The help for `unload` has a little bit of info on why things can be difficult for S4 classes. – Gregor Thomas Dec 11 '15 at 00:30
  • I want to only use base R functions if at all possible, so I'd rather not use `devtools::unload`, but the `unload` option for `detach` seems to be working. @ialm if you submit that as an answer, I can accept it. – Eli Sander Dec 11 '15 at 00:36

1 Answers1

3

To try to unload the namespace that was loaded when loading a package, you have to set the argument unload = TRUE in detach().

In your example:

detach('package:pomp', unload = TRUE, character.only = TRUE)

However, if you read the details in the docs (?detach), there are some things to watch out for:

If a package has a namespace, detaching it does not by default unload the namespace (and may not even with unload = TRUE), and detaching will not in general unload any dynamically loaded compiled code (DLLs). Further, registered S3 methods from the namespace will not be removed. If you use library on a package whose namespace is loaded, it attaches the exports of the already loaded namespace. So detaching and re-attaching a package may not refresh some or all components of the package, and is inadvisable.

Emphasis mine. Be wary that it may not always work.

ialm
  • 8,510
  • 4
  • 36
  • 48