romainfrancois / nothing

A package about nothing
40 stars 11 forks source link

Unload all packages except base #2

Closed wch closed 10 years ago

wch commented 10 years ago

All packages should be unloaded except base, with unloadNamespace.

Normally you have to do this in the correct order to avoid errors. (You can't unload a package imported by another loaded package.) But a horrible, ugly way of doing it is to loop over all the loaded packages until only base is left, and ignore errors:

pkgs <- setdiff(loadedNamespaces(), "base")

while (length(pkgs) > 0) {
  for (pkg in pkgs) {
    tryCatch(unloadNamespace(pkg), error = function (e) invisible())
  }

  pkgs <- setdiff(loadedNamespaces(), "base")
}

This needs a check to avoid infinite loops, because some packages just won't unload properly.