I need to clean up an R instance to return it to its on-launch virginal state. So far, what I'm doing is:
On launch, record the loaded packages and namespaces
original_packages <- grep('^package:', search(), value = TRUE)
original_namespaces <- loadedNamespaces()
When I need to flush the instance, detach each loaded package that was not there at launch:
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 have loaded a package with a bunch of imported namespaces, such as ggplot2, those namespaces stay loaded, and I have to unload them in order of import, from high-level down. Just unloading them blindly doesn't work, as I get "namespace ‘x’ is imported by ‘y’, ‘z’ so cannot be unloaded" errors.
Here is reproducible example:
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 some way to figure out the namespace import hierarchy? If so, then I should just be able to order the last loop correctly...