I've had problems with the global scope being polluted by attached packages (sessionInfo()$otherPkgs
) and namespaces (loadedNamespaces()
). So I want to clear them at the beginning of my scripts.
Half the problem was solved in this thread. The key difference with this question is that I want to unload namespaces, not just detach packages. pacman is interesting as well, but doesn't seem to work either.
library(dbplyr)
names(sessionInfo()$otherPkgs)
lapply(paste("package:", names(sessionInfo()$otherPkgs), sep=""),
detach, character.only = TRUE, unload = TRUE)
# `dbplyr` is detached
names(sessionInfo()$otherPkgs)
But similar approaches for unloading the loaded namespaces seem much more challenging because the packages which depend on others must be unloaded first.
Here's my attempt:
# Recursive unload which checks for reverse dependencies (children) along the way
# and unloads them first
myunload <- function(pkg) {
# Get child (reverse-dependent) packages that have loaded namespaces
child_pkgs <- unlist(tools::dependsOnPkgs(pkg, which = c("Depends", "Imports"), reverse = T))
child_pkgs <- child_pkgs[which(child_pkgs %in% loadedNamespaces())]
# Recursively unload child packages
lapply(child_pkgs, myunload)
unloadNamespace(pkg)
}
# Apply over all our loaded namespaces
lapply(loadedNamespaces(), myunload)
Testing it:
lapply(loadedNamespaces(), myunload)
Error in unloadNamespace(pkg) : namespace ‘grDevices’ is imported by ‘grid’, ‘graphics’, ‘stats’ so cannot be unloaded
It looks like it's trying to unload base packages, which is not my intent. I'm not sure how to specify no base packages.
I would like to use detach(..., unload=T, character.only=T, force=T)
but this fails, as explained in the documentation:
...if the namespace is imported by another namespace or unload is FALSE, no unloading will occur.
Is there a simpler method, or one which works, for unloading all namespaces, including those that might be imported by others? if the namespace is imported by another namespace or unload is FALSE, no unloading will occur.
.rs.restartR()
. But for me it worked only one time, afterwards, every time I try to restart RStudio it simply hangs – Buddy