tryCatch()如果是其他的

时间:2015-10-26 07:59:47

标签: r

我最近开始探索R编程并且有一个非常微不足道的疑问。我想写一个函数,它会尝试加载所需的软件包,并在未安装它的情况下安装它。

我用if else逻辑编写了它。我的问题是,如果我使用tryCatch()会更有效吗?除了处理错误的能力之外还有其他任何优势,因为在这种情况下处理错误并不重要。

以下是我目前使用的代码:

Inst.Pkgs=function(){

  if (!require(tm)) 
    {install.packages("tm")
    require(tm)}

   if (!require(SnowballC)) 
    {install.packages("SnowballC")
     require(SnowballC)}

  if (!require(wordcloud)) 
    {install.packages("wordcloud")
    require(wordcloud)}

  if (!require(RWeka)) 
    {install.packages("RWeka")
    require(RWeka)}

  if (!require(qdap)) 
    {install.packages("qdap") 
    require(qdap)}

  if (!require(timeDate)) 
    {install.packages("timeDate") 
    require(timeDate)}

  if (!require(googleVis)) 
  {install.packages("googleVis") 
    require(googleVis)}

  if (!require(rCharts)) 
  { 
    if (!require(downloader)) 
    {install.packages("downloader") 
      require(downloader)}

    download("https://github.com/ramnathv/rCharts/archive/master.tar.gz", "rCharts.tar.gz")
    install.packages("rCharts.tar.gz", repos = NULL, type = "source")
    require(rCharts)
  }

}

2 个答案:

答案 0 :(得分:5)

您可以立即查看并安装缺少的软件包。

# Definition of function out, the opposite of in
"%out%" <- function(x, table) match(x, table, nomatch = 0) == 0

# Storing target packages
pkgs <- c("tm", "SnowballC", "wordcloud", "RWeka", "qdap",
          "timeDate", "googleVis")

# Finding which target packages are already installed using
# function installed.packages(). Names of packages are stored
# in the first column
idx <- pkgs %out% as.vector(installed.packages()[,1])

# Installing missing target packages
install.packages(pkgs[idx])

答案 1 :(得分:0)

事实上,我们可以使用tryCatch。如果程序尝试加载未安装的库,则会抛出错误 - 可以通过tryCatch()调用的函数捕获并解决该错误。

我将如何做到这一点:

needed_libs <- c("tm", "SnowballC", "wordcloud", "RWeka", "qdap", "timeDate", "googleVis")
install_missing <- function(lib){install.packages(lib,repos="https://cran.r-project.org/", dependencies = TRUE); library(lib, character.only = TRUE)}
for (lib in needed_libs) tryCatch(library(lib, character.only=TRUE), error = function(e) install_missing(lib))

这将按照OP中的要求安装缺少的包并加载所需的库。