Predictive Hacks

Hack: How to Install and Load Packages Dynamically

R packages

When we share an R script file with someone else, we assumed that they have already installed the required R packages. However, this is not always the case and for that reason, I strongly suggest adding this piece of code to every shared R script which requires a package. Let’s assume that your code requires the following three packages: “readxl“, “dplyr“, “multcomp” .

The script below checks, if the package exists, and if not, then it installs it and finally it loads it to R

mypackages<-c("readxl", "dplyr", "multcomp")

for (p in mypackages){
  if(!require(p, character.only = TRUE)){
    install.packages(p)
    library(p, character.only = TRUE)
  }
  }

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

3 thoughts on “Hack: How to Install and Load Packages Dynamically”

  1. Cool. A couple of other options too (not really that different but latter is using sapply instead of a for loop ad both use the awesome || ):

    For a single package:

    require(tidyverse) || install.packages(“tidyverse”)
    library(tidyverse)

    For multiple:

    req <- substitute(require(x, character.only = TRUE))
    libs<-c("Hmisc", "caret", "randomForest", "nnet", "acs",
    "zoo", "chron", "xgboost", "anomalize", "shiny",
    "Matrix", "stringr", "stringi", "tidyr", "tidyverse")
    sapply(libs, function(x) eval(req) || {install.packages(x); eval(req)})

    Reply
  2. Tsk, tsk. A for loop? How about a more R-like approach using sapply() and converting your for loop into a function?

    load_required_libraries <- function(p){
    if(!require(p, character.only = TRUE)){
    install.packages(p)
    library(p, character.only = TRUE)
    }
    }

    mypackages<-c("readxl", "dplyr", "multcomp")

    sapply(mypackages, load_required_libraries)

    Reply

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore