16

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)?

2 Answers 2

12

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
  ))
2
  • FYI - it worked but it threw a bunch of warnings saying packages could not be unloaded. However, when I ran (.packages()) afterwards, only the base R packages remained.
    – L Tyrone
    Nov 22 at 0:21
  • 1
    I assume that there were packages that could not be unloaded without a warning because other packages still loaded did need them.
    – petzi
    Nov 23 at 15:22
8

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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.