[英]tryCatch() Vs if else
我最近开始探索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)
}
}
您可以立即检查并安装缺少的软件包。
# 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])
实际上,我们可以使用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的要求,这将安装缺少的软件包并加载所需的库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.