I need to clear an instance of R in order to return it to its virgin state. So far I am doing:
At startup, record downloaded packages and namespaces
original_packages <- grep('^package:', search(), value = TRUE) original_namespaces <- loadedNamespaces()
When I need to clear an instance, disconnect every downloaded package that was not there at startup:
for (pkg in grep('^package:', search(), value = TRUE)) { if (! pkg %in% original_packages){ detach(pkg, unload=TRUE, force=TRUE, character.only=TRUE) } }
The problem is that if I downloaded a package with a bunch of imported namespaces like ggplot2, these namespaces remain loaded, and I have to unload them in import order, starting from the top level. Just unloading them blindly does not work, since I get a "namespace" x imported by the errors "y, z, so it cannot be unloaded."
Here is an example of reproducibility:
original_packages <- grep('^package:', search(), value = TRUE) original_namespaces <- loadedNamespaces() library(ggplot2) library(plyr) loadedNamespaces() for (pkg in grep('^package:', search(), value = TRUE)) { if (! pkg %in% original_packages){ detach(pkg, unload=TRUE, force=TRUE, character.only=TRUE) } } for (ns in loadedNamespaces()) { if (! ns %in% original_namespaces){ unloadNamespace(ns) } }
Is there a way to define a namespace import hierarchy? If so, then I should just be able to arrange the last loop correctly ...