In enterprise environment, we generally need to automate the process of installing multiple R packages so that user does not have to install them separately before submitting your program.
The function below performs the following operations -
- First it finds all the already installed R packages
- Check packages which we want to install are already installed or not.
- If package is already installed, it does not install it again.
- If package is missing (not installed), it installs the package.
- Loop through steps 2, 3 and 4 for multiple packages we want to install
- Load all the packages (both already available and new ones).
Install_And_Load <- function(packages) {
k <- packages[!(packages %in% installed.packages()[,"Package"])];
if(length(k))
{install.packages(k, repos='https://cran.rstudio.com/');}
for(package_name in packages)
{library(package_name,character.only=TRUE, quietly = TRUE);}
}
Install_And_Load(c("fuzzyjoin", "quanteda", "stringdist", "stringr", "stringi"))
Explanation
1. installed.packages() returns details of all the already installed packages. installed.packages()[,"Package"] returns names of these packages.
To see version of the packages, submit the following command
installed.packages()[,c("Package","Version")]2. You can use any of the following repositories (URL of a CRAN mirror). You can experiment with these 3 repositories if one of them is blocked in your company due to firewall restriction.
https://cloud.r-project.org3. quietly = TRUE tells R not to print errors/warnings if package attaching (loading) fails.
https://cran.rstudio.com
http://www.stats.ox.ac.uk/pub/RWin
How to check version of R while installation
In the program below, the package RDCOMClient refers repository - http://www.omegahat.net/R if R version is greater than or equal to 3.5. Else refers the repository http://www.stats.ox.ac.uk/pub/RWin
if (length("RDCOMClient"[!("RDCOMClient" %in% installed.packages()[,"Package"])])) {
if (as.numeric(R.Version()$minor)>= 5)
install.packages("RDCOMClient", repos = "http://www.omegahat.net/R")
else
install.packages("RDCOMClient", repos = "http://www.stats.ox.ac.uk/pub/RWin")
}
library("RDCOMClient")
Thanks for the post! I use an alternative strategy/function using the function "p_load" which can be found in the "pacman" package. See the code below.
ReplyDelete---------- start code ----------
if (!require("pacman")) install.packages("pacman")
pacman::p_load(packages)
---------- end code ----------