Detach All Packages While Working in R

How do I detach all objects and methods from a specific package in R?

To try to unload the namespace that was loaded when loading a package, you have to set the argument unload = TRUE in detach().

In your example:

detach('package:pomp', unload = TRUE, character.only = TRUE)

However, if you read the details in the docs (?detach), there are some things to watch out for:

If a package has a namespace, detaching it does not by default unload
the namespace (and may not even with unload = TRUE), and detaching
will not in general unload any dynamically loaded compiled code
(DLLs). Further, registered S3 methods from the namespace will not be
removed. If you use library on a package whose namespace is loaded, it
attaches the exports of the already loaded namespace. So detaching and
re-attaching a package may not refresh some or all components of the
package, and is inadvisable.

Emphasis mine. Be wary that it may not always work.

How to unload a package without restarting R

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)

Detach several packages at once

Another option:

Vectorize(detach)(name=paste0("package:", c("Hmisc","survival","splines")), unload=TRUE, character.only=TRUE)

Conflict of Packages in RStudio, detach() fails to work

You shouldn't choose unload = TRUE. The default is unload = FALSE, and that's what you need.

Here's the explanation:

In R, packages can be "loaded", which makes them available to other packages that import functions from them. They can also be "attached", which puts them on the search list, so that they are available to the user in the console. If a package is attached, it needs to be loaded, but the reverse is not true.

So if you run detach("package:MASS"), you will remove it from the search list, and in the console, running select() will no longer find the function in MASS. It will still be loaded, so will be available to the other packages that need it.

By the way, using the prefix form MASS::select() or dplyr::select() will work regardless of whether either or both packages are in your search list.



Related Topics



Leave a reply



Submit