12
votes

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

2 Answers

7
votes

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

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