Skip to content

Instantly share code, notes, and snippets.

@sempervent
sempervent / loadPackages.R
Last active February 24, 2021 13:50
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)
}