Search code examples
rinstall.packages

Loading Local Library in R with Prerequisites Together


For example, I have a local broom package, which has several prerequisite libraries such as backports.

install.packages("broom",lib=file.path(Sys.getenv("userprofile"),"desktop","project"))

I found that the following library does not load the necessary prerequisites together.

library(broom,lib.loc=file.path(Sys.getenv("userprofile"),"desktop","project"))
Error: package or namespace load failed for ‘broom’:
 .onLoad failed in loadNamespace() for 'pillar', details:
  call: loadNamespace(name)
  error: there is no package called ‘crayon’

I already have those prerequisites since install.packages downloads them together. Should one load all the prerequisite libraries (such as backports) before loading the package I want to use (i.e., broom)?


Solution

  • I made this function that basically loads the dependencies of the passed packages now all you need to do is run it before loading broom then it'll load the dependencies.

    # loads dependencies of passed packages
    # can be used in two forms :
    #     load.dep(broom, tidyr)
    #.    load.dep("broom", "tidyr")
    load.dep <- function(...){
        x <- as.list(substitute(...()))
        stopifnot(length(x)>0)
        x <- sapply(x, as.character)
        avp <- available.packages()
        pkgs <- unlist(strsplit(avp[x, c("Imports","Depends")], split=" ?(\\([^)]+?\\))?, ?"), use.names=F)
        invisible(lapply(pkgs[!grepl('^(\\n|R )', pkgs)], library, character.only=T))
    }