Detach several packages at once

后端 未结 4 2030
不思量自难忘°
不思量自难忘° 2020-12-28 21:11

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          


        
相关标签:
4条回答
  • 2020-12-28 21:52

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

    0 讨论(0)
  • 2020-12-28 21:56

    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.

    0 讨论(0)
  • 2020-12-28 21:59

    To delete all currently attached packages:

    lapply(names(sessionInfo()$otherPkgs), function(pkgs) detach(paste0('package:',pkgs),character.only = T,unload = T,force=T))
    
    0 讨论(0)
  • 2020-12-28 22:06

    Another option:

    Vectorize(detach)(name=paste0("package:", c("Hmisc","survival","splines")), unload=TRUE, character.only=TRUE)
    
    0 讨论(0)
提交回复
热议问题