2015-01-06 247 views
4

我想写一个检查一个软件包是否已经安装在R系统功能的功能,代码如下写检查包装是否已经安装在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") 

但是,这个功能没有做正确的事情?为什么?有人可以告诉我吗?

+1

您的标题和问题内容不匹配。代码似乎是“尝试加载一个包;如果它失败了,然后下载它并再试一次”,这与“检查包是否已安装”不同(你想要'installed.packages' )。 –

+0

另外,你需要解释什么是正确的事情,或者不可能回答这个问题。 checkBioconductorPackage(“affy”)的输出是什么,你期望什么? –

回答

1

使用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") 
+0

It Worked!谢谢!最好的祝福! –

1
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

+0

这真的有用,谢谢!最好的祝愿! –

相关问题