Detach several packages at once

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)


另外一个选择:

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


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.

链接地址: http://www.djcxy.com/p/25010.html

上一篇: 如何删除使用Python easy安装的软件包

下一篇: 一次分离几个软件包