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) } }
4 thoughts on “Hack: How to Install and Load Packages Dynamically”
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)})
TY!
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)
Often you may also want to make sure that the “someone else” not only installs the required packages but also the same package version. There is an R package that can do all this for you: check out https://cran.r-project.org/web/packages/renv/index.html