2015-01-06 191 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

這真的有用,謝謝!最好的祝願! –

相關問題