How to unload a package without restarting R?

2019-01-04 15:44发布

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?

标签: r packages r-faq
7条回答
时光不老,我们不散
2楼-- · 2019-01-04 15:46

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 detach 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)
查看更多
家丑人穷心不美
3楼-- · 2019-01-04 15:47

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楼-- · 2019-01-04 15:51

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!

查看更多
Rolldiameter
5楼-- · 2019-01-04 15:54

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)
查看更多
SAY GOODBYE
6楼-- · 2019-01-04 15:58

You can also use the unloadNamespace command, as in:

unloadNamespace("sqldf")

The function detaches the namespace prior to unloading it.

查看更多
爷、活的狠高调
7楼-- · 2019-01-04 15:58

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

查看更多
登录 后发表回答