编写一个检查包是否已安装在 R 系统中的函数

write a function that check whether a package has been install in R system

我想写一个函数来检查R系统是否安装了一个包,代码如下

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

但是,这个函数没有做正确的事情?为什么?谁能告诉我吗?

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

我加了character.only

使用tryCatch。这是一个例子:

# 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")