I have recently started exploring R programming and have a very trivial doubt. I want to write a function which would try to load the required packages and install the same in case its not installed already.
I have written it using if else logic. My question is will it be more efficient if I use tryCatch()? Is there any other advantage than the ability to handle errors as it is not important to handle errors in this context.
Below is the code I am currently using:
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)
}
}
You can check at once and install missing packages.
# 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])
We can in fact use tryCatch
for this. If the program tries to load a library that is not installed, it will throw an error - an error that can be caught and resolved with a function called by tryCatch()
.
Here's how I would do it:
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))
This will install the missing packages and load the required libraries, as requested in the OP.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.