Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detach all packages while working in R

Tags:

r

workspace

People also ask

How do you detach a package in R?

To detach a package in R, we can simply use the detach function. But we need to remember that once the package will be detached there is no way to use any of the functions of that particular package.


So, someone should have simply answered the following.

lapply(paste('package:',names(sessionInfo()$otherPkgs),sep=""),detach,character.only=TRUE,unload=TRUE)

(edit: 6-28-19) In the latest version of R 3.6.0 please use instead.

invisible(lapply(paste0('package:', names(sessionInfo()$otherPkgs)), detach, character.only=TRUE, unload=TRUE))

Note the use of invisible(*) is not necessary but can be useful to prevent the NULL reply from vertically spamming the R window.

(edit: 9/20/2019) In version 3.6.1

It may be helpful to convert loaded only names(sessionInfo()$loadedOnly) to explicitly attached packages first, and then detach the packages, as so.

lapply(names(sessionInfo()$loadedOnly), require, character.only = TRUE)
invisible(lapply(paste0('package:', names(sessionInfo()$otherPkgs)), detach, character.only=TRUE, unload=TRUE, force=TRUE))

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. Currently timeDate can break irreversibly, for example.

(edit: 9/24/20) for version 4.0.2 The following first loads packages to test and then gives a sequence to fully detach all packages except for package "base" and "utils". It is highly recommended that one does not detach those packages.

    invisible(suppressMessages(suppressWarnings(lapply(c("gsl","fBasics","stringr","stringi","Rmpfr"), require, character.only = TRUE))))
    invisible(suppressMessages(suppressWarnings(lapply(names(sessionInfo()$loadedOnly), require, character.only = TRUE))))
    sessionInfo()

    #the above is a test

    invisible(lapply(paste0('package:', c("stringr","fBasics")), detach, character.only=TRUE,unload=TRUE))
    #In the line above, I have inserted by hand what I know the package dependencies to be. A user must know this a priori or have their own automated
    #method to discover it. Without removing dependencies first, the user will have to cycle through loading namespaces and then detaching otherPkgs a
    #second time through.
    invisible(lapply(paste0('package:', names(sessionInfo()$otherPkgs)), detach, character.only=TRUE,unload=TRUE))

    bspkgs.nb<-sessionInfo()$basePkgs[sessionInfo()$basePkgs!="base"]
    bspkgs.nbu<-bspkgs.nb[bspkgs.nb!="utils"]
    names(bspkgs.nbu)<-bspkgs.nbu
    suppressMessages(invisible(lapply(paste0('package:', names(bspkgs.nbu)), detach, character.only=TRUE,unload=TRUE)))

    #again this thoroughly removes all packages and loaded namespaces except for base packages "base" and "utils" (which is highly not recommended).

Please try this:

detachAllPackages <- function() {

  basic.packages <- c("package:stats","package:graphics","package:grDevices","package:utils","package:datasets","package:methods","package:base")

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

You were close. Note what ?detach has to say about the first argument name of detach():

Arguments:

name: The object to detach.  Defaults to ‘search()[pos]’.  This can
      be an unquoted name or a character string but _not_ a
      character vector.  If a number is supplied this is taken as
      ‘pos’.

So we need to repeatedly call detach() once per element of pkg. There are a couple of other arguments we need to specify to get this to work. The first is character.only = TRUE, which allows the function to assume that name is a character string - it won't work without it. Second, we also probably want to unload any associated namespace. This can be achieved by setting unload = TRUE. So the solution is, for example:

pkg <- c("package:vegan","package:permute")
lapply(pkg, detach, character.only = TRUE, unload = TRUE)

Here is a full example:

> require(vegan)
Loading required package: vegan
Loading required package: permute
This is vegan 2.0-0
> sessionInfo()
R version 2.13.1 Patched (2011-09-13 r57007)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.utf8       LC_NUMERIC=C             
 [3] LC_TIME=en_GB.utf8        LC_COLLATE=en_GB.utf8    
 [5] LC_MONETARY=C             LC_MESSAGES=en_GB.utf8   
 [7] LC_PAPER=en_GB.utf8       LC_NAME=C                
 [9] LC_ADDRESS=C              LC_TELEPHONE=C           
[11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C      

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods  
[7] base     

other attached packages:
[1] vegan_2.0-0   permute_0.7-0

loaded via a namespace (and not attached):
[1] grid_2.13.1     lattice_0.19-33 tools_2.13.1   
> pkg <- c("package:vegan","package:permute")
> lapply(pkg, detach, character.only = TRUE, unload = TRUE)
[[1]]
NULL

[[2]]
NULL

> sessionInfo()
R version 2.13.1 Patched (2011-09-13 r57007)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.utf8       LC_NUMERIC=C             
 [3] LC_TIME=en_GB.utf8        LC_COLLATE=en_GB.utf8    
 [5] LC_MONETARY=C             LC_MESSAGES=en_GB.utf8   
 [7] LC_PAPER=en_GB.utf8       LC_NAME=C                
 [9] LC_ADDRESS=C              LC_TELEPHONE=C           
[11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C      

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods  
[7] base     

loaded via a namespace (and not attached):
[1] grid_2.13.1     lattice_0.19-33 tools_2.13.1

If you want to turn this into a function, study the code in sessionInfo() to see how it identifies what it labels as "other attached packages:". Combine that bit of code with the idea above in a single function and you are home and dry. I'll leave that bit up to you though.


nothing

It may be worth to add solution made available by Romain François. When loaded the package nothing, which is currently available on GitHub, will unload all of the loaded packages; as in the example that Romain provides:

loadedNamespaces()
[1] "base"      "datasets"  "grDevices" "graphics"  "methods"   "stats"
[7] "utils"

require(nothing, quietly = TRUE)

loadedNamespaces()
[1] "base"

Installation

With use of the devtools package:

devtools::install_github("romainfrancois/nothing")

pacman

An alternative approach uses pacman package available through CRAN:

pacman::p_unload(pacman::p_loaded(), character.only = TRUE)