675

I'd like to unload a package without having to restart R (mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use).

?library doesn't show any options that would unload a package.

There is a suggestion that detach can unload package, but the following both fail:

detach(vegan)

Error in detach(vegan) : invalid name argument

detach("vegan")

Error in detach("vegan") : invalid name argument

So how do I unload a package?

4
  • 5
    @Iterator: A library is a location where you find packages. (They are not synonymous.) .libPaths() gives you the paths to all the libraries on your system. Commented Aug 8, 2011 at 13:08
  • 20
    @Richie: Thanks. I get that in the R context, but I feel that R usage overloads or makes ambiguous the term library in two ways: 1 - it's not the same use of library as elsewhere, and 2 - the term is used in library() to load...not a library, but a package.
    – Iterator
    Commented Aug 8, 2011 at 13:21
  • 4
    @Iterator You are right. This was the answer I needed, and when googling I used "opposite of require" or "undo library" because that is how I typically load, erm, "packages". So titling it properly makes the question more correct but also harder to find. Commented Jul 1, 2013 at 18:36
  • I usually use standard R detachcommand without any external packages. It has worked for me, but there are many things I don't know. Commented May 5, 2023 at 19:34

12 Answers 12

841

Try this (see ?detach for more details):

detach("package:vegan", unload=TRUE)

It is possible to have multiple versions of a package loaded at once (for example, if you have a development version and a stable version in different libraries). To guarantee that all copies are detached, use this function.

detach_package <- function(pkg, character.only = FALSE)
{
  if(!character.only)
  {
    pkg <- deparse(substitute(pkg))
  }
  search_item <- paste("package", pkg, sep = ":")
  while(search_item %in% search())
  {
    detach(search_item, unload = TRUE, character.only = TRUE)
  }
}

Usage is, for example

detach_package(vegan)

or

detach_package("vegan", TRUE)
7
  • 3
    @hadley Indeed. The unquoted version doesn't seem to work in the latest version of R. I've updated kohske's answer to reflect your solution. Commented Feb 9, 2013 at 16:49
  • @AriB.Friedman, is there an way to detach several packages at once? When I load say Hmisc it also loads survival and splines is there a way to unload that groups together?
    – Eric Fail
    Commented Jul 9, 2013 at 10:12
  • 3
    > detach("package:MASS", unload=TRUE) Error in detach("package:MASS", unload = TRUE) : invalid 'name' argument
    – Mona Jalal
    Commented Feb 12, 2014 at 2:39
  • 8
    If you get an invalid 'name' argument error, add character.only=TRUE. Commented Feb 13, 2014 at 0:55
  • 4
    > detach("package:kriging", unload=TRUE, character.only=T) Error in detach("package:kriging", unload = TRUE, character.only = T) : invalid 'name' argument. However @rstober solution does work!
    – Andrew
    Commented Nov 17, 2015 at 12:33
131
Answer recommended by R Language Collective

You can also use the unloadNamespace command, as in:

unloadNamespace("sqldf")

The function detaches the namespace prior to unloading it.

1
  • 2
    In case @kohske's solution also didn't work for you, this worked for me
    – Wassadamo
    Commented Aug 8, 2019 at 0:02
45

You can uncheck the checkbox button in RStudio (packages).

RStudio packages pane

2
  • 22
    It is worth adding that this results in a detach("package:packageToUnload", unload=TRUE) command being executed and is no different to already proposed solution.
    – Konrad
    Commented Jan 10, 2017 at 13:14
  • 2
    Also, the box isn't checked if the package was loaded using rstudio install & restart (bug?). But you can just check and uncheck it.
    – jiggunjer
    Commented Jul 22, 2019 at 5:16
10

I tried what kohske wrote as an answer and I got error again, so I did some search and found this which worked for me (R 3.0.2):

require(splines) # package
detach(package:splines)

or also

library(splines)
pkg <- "package:splines"
detach(pkg, character.only = TRUE)
4
  • 3
    What error do you get? Because it works for me (R 3.1). And the second solution is the same @koshke's answer, only without unload (so the package namespace is not unloaded).
    – alko989
    Commented Jun 11, 2014 at 1:32
  • I got the same error. the point is I gave the same solution as @Kohske but with different package name. it simply means that if you use the package: then it should work fine, but if you don't use that, you will get the same error as in the question. ;)
    – Mehrad
    Commented Jul 3, 2014 at 15:44
  • Wait... so you tried to unload a package that wasn't even loaded? And you're surprised you got an error? Commented Mar 11, 2015 at 16:19
  • @Gregor Would you please read again everything before pressing downvote button?!!! the function require() and library() almost does the same (atleast in this case), so the package is already loaded !! I'm not responsible for you lack of information!!
    – Mehrad
    Commented Mar 12, 2015 at 9:14
10

When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.

if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE) 

Including this at the top of a script might be helpful.

I hope that makes your day!

10

detach(package:PackageName) works and there is no need to use quotes.

8

Another option is

devtools::unload("your-package")

This apparently also deals with the issue of registered S3 methods that are not removed with unloadNamespace()

1
  • 1
    I've been trying to detach formula.tools. This is the only approach that worked for me, at least in terms of reverting the effects of said package on as.character. Thanks!!
    – jruf003
    Commented Sep 13, 2021 at 5:46
6

You can try all you want to remove a package (and all the dependencies it brought in alongside) using unloadNamespace() but the memory footprint will still persist. And no, detach("package:,packageName", unload=TRUE, force = TRUE) will not work either.

From a fresh new console or Session > Restart R check memory with the pryr package:

pryr::mem_used()

# 40.6 MB   ## This will depend on which packages are loaded obviously (can also fluctuate a bit after the decimal)

Check my sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

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

loaded via a namespace (and not attached):
[1] compiler_3.6.1   pryr_0.1.4       magrittr_1.5     tools_3.6.1      Rcpp_1.0.3       stringi_1.4.3    codetools_0.2-16 stringr_1.4.0   
[9] packrat_0.5.0   

Let's load the Seurat package and check the new memory footprint:

library(Seurat)
pryr::mem_used()

# 172 MB    ## Likely to change in the future but just to give you an idea

Let's use unloadNamespace() to remove everything:

unloadNamespace("Seurat")
unloadNamespace("ape")
unloadNamespace("cluster")
unloadNamespace("cowplot")
unloadNamespace("ROCR")
unloadNamespace("gplots")
unloadNamespace("caTools")
unloadNamespace("bitops")
unloadNamespace("fitdistrplus")
unloadNamespace("RColorBrewer")
unloadNamespace("sctransform")
unloadNamespace("future.apply")
unloadNamespace("future")
unloadNamespace("plotly")
unloadNamespace("ggrepel")
unloadNamespace("ggridges")
unloadNamespace("ggplot2")
unloadNamespace("gridExtra")
unloadNamespace("gtable")
unloadNamespace("uwot")
unloadNamespace("irlba")
unloadNamespace("leiden")
unloadNamespace("reticulate")
unloadNamespace("rsvd")
unloadNamespace("survival")
unloadNamespace("Matrix")
unloadNamespace("nlme")
unloadNamespace("lmtest")
unloadNamespace("zoo")
unloadNamespace("metap")
unloadNamespace("lattice")
unloadNamespace("grid")
unloadNamespace("httr")
unloadNamespace("ica")
unloadNamespace("igraph")
unloadNamespace("irlba")
unloadNamespace("KernSmooth")
unloadNamespace("leiden")
unloadNamespace("MASS")
unloadNamespace("pbapply")
unloadNamespace("plotly")
unloadNamespace("png")
unloadNamespace("RANN")
unloadNamespace("RcppAnnoy")
unloadNamespace("tidyr")
unloadNamespace("dplyr")
unloadNamespace("tibble")
unloadNamespace("RANN")
unloadNamespace("tidyselect")
unloadNamespace("purrr")
unloadNamespace("htmlwidgets")
unloadNamespace("htmltools")
unloadNamespace("lifecycle")
unloadNamespace("pillar")
unloadNamespace("vctrs")
unloadNamespace("rlang")
unloadNamespace("Rtsne")
unloadNamespace("SDMTools")
unloadNamespace("Rdpack")
unloadNamespace("bibtex")
unloadNamespace("tsne")
unloadNamespace("backports")
unloadNamespace("R6")
unloadNamespace("lazyeval")
unloadNamespace("scales")
unloadNamespace("munsell")
unloadNamespace("colorspace")
unloadNamespace("npsurv")
unloadNamespace("compiler")
unloadNamespace("digest")
unloadNamespace("R.utils")
unloadNamespace("pkgconfig")
unloadNamespace("gbRd")
unloadNamespace("parallel")
unloadNamespace("gdata")
unloadNamespace("listenv")
unloadNamespace("crayon")
unloadNamespace("splines")
unloadNamespace("zeallot")
unloadNamespace("reshape")
unloadNamespace("glue")
unloadNamespace("lsei")
unloadNamespace("RcppParallel")
unloadNamespace("data.table")
unloadNamespace("viridisLite")
unloadNamespace("globals")

Now check sessionInfo():

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

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

loaded via a namespace (and not attached):
 [1] tools_3.6.1       stringr_1.4.0     rstudioapi_0.10   pryr_0.1.4        jsonlite_1.6      gtools_3.8.1      R.oo_1.22.0      
 [8] magrittr_1.5      Rcpp_1.0.3        R.methodsS3_1.7.1 stringi_1.4.3     plyr_1.8.4        reshape2_1.4.3    codetools_0.2-16 
[15] packrat_0.5.0     assertthat_0.2.1 

Check the memory footprint:

pryr::mem_used()

# 173 MB

Link to screen-cast demonstration

6

Note also that you can only use unload() once. If you use it a second time without rerunning library(), y'll get the not very informative error message invalid 'name' argument:

library(vegan)
#> Loading required package: permute
#> Loading required package: lattice
#> This is vegan 2.5-6
detach("package:vegan",  unload=TRUE)
detach("package:vegan",  unload=TRUE)
#> Error in detach("package:vegan", unload = TRUE): invalid 'name' argument

Created on 2020-05-09 by the reprex package (v0.3.0)

2

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

1

Just go to OUTPUT window, then click on Packages icon (it is located between Plot and Help icons). Remove "tick / check mark" from the package you wanted be unload.

For again using the package just put a "tick or Check mark" in front of package or use :

library (lme4)
1
  • 1
    Not unless you have your own custom library path. It doesn't show up under "Packages" so you have to do the above methods
    – zazu
    Commented Jul 28, 2016 at 20:41
1

Connected with @tjebo answer.

TL;DR
Please use pkgload:::unload instead of devtools::unload as they are the same function (1 to 1) and pkgload is a much lighter package (nr of dependencies). devtools simply reexporting the pkgload:::unload function.

Unfortunately devtools is a huge dependency (as devtools has a lot of own dependencies), which is more development stage targeted. So if you want to use the unload function in your own package or you care about library size please remember to use pkgload:::unload instead of devtools::unload. devtools simply reexporting the pkgload:::unload function.

Please check the footer of the devtools::unload function to quickly confirm the reexport or go to the github repo

> devtools::unload
function (package = pkg_name(), quiet = FALSE) 
{
    if (package == "compiler") {
        oldEnable <- compiler::enableJIT(0)
        if (oldEnable != 0) {
            warning("JIT automatically disabled when unloading the compiler.")
        }
    }
    if (!package %in% loadedNamespaces()) {
        stop("Package ", package, " not found in loaded packages or namespaces")
    }
    unregister_methods(package)
    unloaded <- tryCatch({
        unloadNamespace(package)
        TRUE
    }, error = function(e) FALSE)
    if (!unloaded) {
        unload_pkg_env(package)
        unregister_namespace(package)
    }
    clear_cache()
    unload_dll(package)
}
<bytecode: 0x11a763280>
<environment: namespace:pkgload>

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