Skip to content

Instantly share code, notes, and snippets.

@sempervent
Last active February 24, 2021 13:50
Show Gist options
  • Save sempervent/4635569b9544949f4676b1fad8950956 to your computer and use it in GitHub Desktop.
Save sempervent/4635569b9544949f4676b1fad8950956 to your computer and use it in GitHub Desktop.
Load R Packages and install them if they are not already installed.
loadPackages <- function(pkgs, repo = 'https://cloud.r-project.org',
lib = .libPaths()[1]) {
not_installed <- pkgs[!pkgs %in% rownames(installed.packages())]
install.packages(not_installed, repos = repo, lib = lib)
loaded <- unlist(lapply(pkgs, require, character.only = TRUE, quietly = TRUE))
if (any(loaded == FALSE)) {
message(sprintf('The following packages failed to load: %s',
paste0(pkgs[!loaded], collapse = ', ')))
return(FALSE)
}
return(TRUE)
}
@sempervent
Copy link
Author

Retrieve the file:

wget https://gist.githubusercontent.com/sempervent/4635569b9544949f4676b1fad8950956/raw/d20ae031c1eae0e8a2bef02bc78de915bea4d516/loadPackages.R

@sempervent
Copy link
Author

sempervent commented Mar 11, 2020

Retrieve the file: wget https://gist.github.com/sempervent/4635569b9544949f4676b1fad8950956/raw/5919f0fc8150392882075e58a407990de66300f1/loadPackages.R

This is a more streamlined version of the loadPackages, with ability to customize the repo and library. The repo was updated to the 0-cloud repo, which does automatic redirection to servers worldwide, sponsored by Rstudio

I use like this:
packages <- c('igraph', 'network', 'sna', 'ggraph', 'visNetwork', 'threejs', 'networkD3', 'ndtv', 'flipPlots') stopifnot(loadPackages(packages) == TRUE)

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