我想编写一个函数来检查是否已经在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")
但是,这个功能没有做正确的事情?为什么?任何人都可以告诉我吗?
最佳答案 使用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")