Write a function that checks if a package has been installed on the R system

I want to write a function that checks if a package has been installed on the R system, the code is as follows

checkBioconductorPackage <- function(pkgs) {
    if(require(pkgs)){
        print(paste(pkgs," is loaded correctly"))
    } else {
        print(paste("trying to install" ,pkgs))

        update.packages(checkBuilt=TRUE, ask=FALSE)
        source("http://bioconductor.org/biocLite.R")
        biocLite(pkgs)

        if(require(pkgs)){
            print(paste(pkgs,"installed and loaded"))
        } else {
            stop(paste("could not install ",pkgs))
        }
    }
} 
checkBioconductorPackage("affy")

but this function did not arrive correctly? What for? can someone tell me?

+4
source share
2 answers

Use tryCatch. Here is an example:

# purpose: write a function to:
# - attempt package load
# - if not then attempt package install & load
checkInstallPackage = function(packName) {
  tryCatch(library(packName), 
           error = function(errCondOuter) {
             message(paste0("No such package: ", packName, "\n Attempting to install."))
             tryCatch({
               install.packages(packName)
               library(packName, character.only = TRUE)               
             }, 
             error = function(errCondInner) {
               message("Unable to install packages. Exiting!\n")
             },
             warning = function(warnCondInner) {
               message(warnCondInner)
             })
           },
           warning = function(warnCondOuter) {
             message(warnCondOuter)
           },
           finally = {
             paste0("Done processing package: ", packName)
           })
}

# for packages that exist on given repo
invisible(lapply(c("EnsembleBase", 
                   "fastcluster",
                   "glarma",
                   "partools"), checkInstallPackage))


# for packages that do not exist
checkInstallPackage("blabla")
+1
source
checkBioconductorPackage <- function(pkgs) {
  if(require(pkgs , character.only = TRUE)){
    print(paste(pkgs," is loaded correctly"))
  } else {
    print(paste("trying to install" ,pkgs))

    update.packages(checkBuilt=TRUE, ask=FALSE)
    source("http://bioconductor.org/biocLite.R")
    biocLite(pkgs)

    if(require(pkgs, character.only = TRUE)){
      print(paste(pkgs,"installed and loaded"))
    } else {
      stop(paste("could not install ",pkgs))
    }
  }
} 

I added character.only

+1
source

Source: https://habr.com/ru/post/1570110/


All Articles