Inspired by this answer I am looking for a way to detach several packages at once.
When I load say Hmisc,
# install.packages("Hmisc", dependencies = TRUE)
require(Hmisc)
R
also loads survival
and splines
. My question is if there is a way to unload that group together?
I currently do something like this,
detach(package:Hmisc, unload = T)
detach(package:survival, unload = T)
detach(package:splines, unload = T)
I tried,
detach(package:c('Hmisc', 'survival', 'splines'), unload = T)
…
Another option:
Vectorize(detach)(name=paste0("package:", c("Hmisc","survival","splines")), unload=TRUE, character.only=TRUE)
?detach
explicitly rules out supplying a character vector (as opposed to scalar, ie more than one library to be detached) as its first argument, but you can always make a helper function. This will accept multiple inputs that can be character strings, names, or numbers. Numbers are matched to entries in the initial search list, so the fact that the search list dynamically updates after each detach won't cause it to break.
mdetach <- function(..., unload = FALSE, character.only = FALSE, force = FALSE)
{
path <- search()
locs <- lapply(match.call(expand=FALSE)$..., function(l) {
if(is.numeric(l))
path[l]
else l
})
lapply(locs, function(l)
eval(substitute(detach(.l, unload=.u, character.only=.c, force=.f),
list(.l=l, .u=unload, .c=character.only, .f=force))))
invisible(NULL)
}
library(xts) # also loads zoo
# any combination of these work
mdetach(package:xts, package:zoo, unload=TRUE)
mdetach("package:xts", "package:zoo", unload=TRUE)
mdetach(2, 3, unload=TRUE)
The messing with eval(substitute(...
is necessary because, unless character.only=TRUE
, detach
handles its first argument in a nonstandard way. It checks if it's a name, and if so, uses substitute
and deparse
to turn it into character. (The character.only
argument is misnamed really, as detach(2, character.only=TRUE)
still works. It should really be called "accept.names" or something.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With