a function to unload all loaded libraries in r

To unload all loaded libraries in R, we can use the detach() function to detach the libraries from the search path. We can also check the current search path using the search() function.

Here's an example function to unload all loaded libraries:

main.r
unload_all_libs <- function() {
  # get a list of all loaded packages
  loaded_packages <- search()[grepl("package:", search())]
  
  # detach each loaded package
  for (package in loaded_packages) {
    detach(package, unload = TRUE)
  }
}
241 chars
10 lines

To use this function, simply call unload_all_libs():

main.r
# load some packages for example
library(dplyr)
library(ggplot2)

# check that they're loaded
search()
#>  [1] ".GlobalEnv"           "package:ggplot2"      "package:dplyr"       
#>  [4] "package:stats"        "package:graphics"     "package:grDevices"   
#>  [7] "package:utils"        "package:datasets"     "package:methods"     
#> [10] "Autoloads"            "package:base"

# unload all loaded packages
unload_all_libs()

# check if they're unloaded
search()
#> [1] ".GlobalEnv"      "package:stats"   "package:graphics" "package:grDevices"
#> [5] "package:utils"   "package:datasets" "package:methods"  "Autoloads"       
#> [9] "package:base"
652 chars
20 lines

gistlibby LogSnag