Skip to content

Instantly share code, notes, and snippets.

@smithdanielle
Created April 1, 2014 13:23
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save smithdanielle/9913897 to your computer and use it in GitHub Desktop.
Save smithdanielle/9913897 to your computer and use it in GitHub Desktop.
Check if multiple R packages are installed. Install them if they are not,then load them into the R session.
# check.packages function: install and load multiple R packages.
# Check to see if packages are installed. Install them if they are not, then load them into the R session.
check.packages <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
# Usage example
packages<-c("ggplot2", "afex", "ez", "Hmisc", "pander", "plyr")
check.packages(packages)
@AldridgeCaleb
Copy link

@smithdanielle, very helpful function, thank you. I was wondering if library should be used instead of require? See Yihui Xie's post on require vs library... https://yihui.name/en/2014/07/library-vs-require/

@chrisvacc
Copy link

if you add options(repos=structure(c(CRAN="http://cloud.r-project.org/"))) they won’t have to select a mirror

@ngupta23
Copy link

Something like this will also work:
#This line of code installs the pacman page if you do not have it installed - if you do, it simply loads the package
if(!require(pacman))install.packages("pacman")
pacman::p_load("dplyr", "DT", "mosaic", "MASS", "usdm", "tidyverse", "ggplot2", "PerformanceAnalytics", "caTools", "glmnet", "caret","leaps","doParallel")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment