I've looked at this but couldn't readily find how to do it. I tried to write up some function that fails with the error:
Error in unloadNamespace(x) : namespace ‘graphics’ is imported by ‘stats and other packages here'
However, many of these packages are not even on the search
list.
[1] ".GlobalEnv" "tools:rstudio" "package:grDevices" "package:utils" "package:datasets"
[6] "package:methods" "Autoloads" "package:base"
This is the function I was playing with:
lapply(gsub("package:","",search()[grep(".*(?<=package:)",search(),perl = T)]),
function(x) unloadNamespace(x))
A variant that doesn't work:
lapply(gsub("package:","",search()[grep(".*(?<=package:)",search(),perl = T)]),
function(x) detach(x))
Question: How can I best unload several packages(better if I could unload them all)?
One can attempt to unload base packages via $basePkgs and also attempt using unloadNamespace (loadedNamespaces ()). However these typically are fraught with errors and could break basic functionality such as causing sessionInfo () to return only errors. This typically occurs because of a lack of reversibility in the original package's design.
After a package has been installed, it needs to be loaded before you can use it. To load a package you can simply check the checkbox beside the package name in the Packages tab – as shown by the yellow box highlight below. This will automatically enter and execute the command shown with the yellow arrow.
If the package is not loaded already, it does nothing. It's not always possible to cleanly unload a package: see the caveats in unload () for some of the potential failure points. If in doubt, restart R and reload the package with library () .
Let’s check the list of currently loaded packages again: As you can see, the updated list contains only the base packages that were loaded at the beginning of the session.
I typically run something like this to unload all non-base packages:
detachAllPackages <- function() {
basic.packages.blank <- c(
"stats",
"graphics",
"grDevices",
"utils",
"datasets",
"methods",
"base"
)
basic.packages <- paste("package:", basic.packages.blank, sep = "")
package.list <- search()[ifelse(unlist(gregexpr("package:", search())) == 1, TRUE, FALSE)]
package.list <- setdiff(package.list, basic.packages)
if (length(package.list) > 0) {
for (package in package.list) {
detach(package, character.only = TRUE)
}
}
}
detachAllPackages()
A simpler solution to unload all non-base packages:
lapply(names(sessionInfo()$otherPkgs), function(pkgs)
detach(
paste0('package:', pkgs),
character.only = T,
unload = T,
force = T
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With