Skip to content

Instantly share code, notes, and snippets.

@ritchieking
Created June 15, 2018 18:31
Show Gist options
  • Save ritchieking/e675b47d9713a02782885d2010f14fc4 to your computer and use it in GitHub Desktop.
Save ritchieking/e675b47d9713a02782885d2010f14fc4 to your computer and use it in GitHub Desktop.
Require R packages from a vector of package names; install a package automatically if it's not installed

This might be a terrible idea, but I like loading packages without a bunch of a require statements — or needing to explicitly install a package if I haven't already done so. I have this function in my .Rprofile, so the top of my R files look like this:

pkgs <- c(
  "tidyverse",
  "Hmisc",
  ... etc.
)

smartRequire(pkgs)
smartRequire <- function(pkgs) {
req <- function(pkg) {
if (!require(pkg, character.only = T)) {
install.packages(pkg, repos='http://cran.us.r-project.org', quiet=T)
}
require(pkg, character.only = T)
}
out <- lapply(pkgs, req)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment