Install and Load Multiple R Packages

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.

Install multiple R Packages

The function below performs the following operations -
  1. First it finds all the already installed R packages
  2. Check packages which we want to install are already installed or not.
  3. If package is already installed, it does not install it again.
  4. If package is missing (not installed), it installs the package.
  5. Loop through steps 2, 3 and 4 for multiple packages we want to install
  6. Load all the packages (both already available and new ones).

Install_And_Load <- function(packages) {
  k <- packages[!(packages %in% installed.packages()[,"Package"])];
  {install.packages(k, repos='');}

  for(package_name in packages)
  {library(package_name,character.only=TRUE, quietly = TRUE);}
Install_And_Load(c("fuzzyjoin", "quanteda", "stringdist", "stringr", "stringi"))


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
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.
3. quietly = TRUE tells R not to print errors/warnings if package attaching (loading) fails.

How to check version of R while installation

In the program below, the package RDCOMClient refers repository - if R version is greater than or equal to 3.5. Else refers the repository
if (length("RDCOMClient"[!("RDCOMClient" %in% installed.packages()[,"Package"])])) {
  if (as.numeric(R.Version()$minor)>= 5)
    install.packages("RDCOMClient", repos = "")
    install.packages("RDCOMClient", repos = "")
Love this Post? Spread the Word!
Comment and share to motivate us to write more!
About Author:

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 8 years of experience in data science. During his tenure, he has worked with global clients in various domains like Banking, Insurance, Telecom and Human Resource.

Get Free Email Updates :
*Please confirm your email address by clicking on the link sent to your Email*
Related Posts:
1 Response to "Install and Load Multiple R Packages"
  1. 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.

    ---------- start code ----------
    if (!require("pacman")) install.packages("pacman")
    ---------- end code ----------


We have Zero Tolerance to Spam. Comments with links will be deleted immediately upon our review.

Next → ← Prev
Scroll to Top