Detach several packages at once

2020-02-22 04:14发布

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)

标签: r packages
4条回答
forever°为你锁心
2楼-- · 2020-02-22 04:29

To delete all currently attached packages:

lapply(names(sessionInfo()$otherPkgs), function(pkgs) detach(paste0('package:',pkgs),character.only = T,unload = T,force=T))
查看更多
萌系小妹纸
3楼-- · 2020-02-22 04:31

?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.)

查看更多
Root(大扎)
4楼-- · 2020-02-22 04:34

Another option:

Vectorize(detach)(name=paste0("package:", c("Hmisc","survival","splines")), unload=TRUE, character.only=TRUE)
查看更多
够拽才男人
5楼-- · 2020-02-22 04:34

To answer my own question to Hong's answer:

detlist<-c('Hmisc','survival','splines')

lapply(detlist, function(k) detach( paste('package:', k, sep='', collapse=''), unload=TRUE, char=TRUE))

Works just fine. The sorting function at the top of base::detach is a bit wonky, but using character.only=TRUE got me thru just fine.

查看更多
登录 后发表回答