Created
April 1, 2014 13:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
if you add options(repos=structure(c(CRAN="http://cloud.r-project.org/")))
they won’t have to select a mirror
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
@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/