Skip to content

Instantly share code, notes, and snippets.

@jankuc
Last active January 24, 2019 10:09
Show Gist options
  • Save jankuc/8ea8704b21e7b46da719a49ba318f710 to your computer and use it in GitHub Desktop.
Save jankuc/8ea8704b21e7b46da719a49ba318f710 to your computer and use it in GitHub Desktop.
R Function which tries to load packages and installs those packages that are not installed already.
#' Load or install packages
#'
#' It tries to install the specified packages multiple (deafault is 10) times.
#'
#' @param packages character vector of packages which should be loaded or installed if they are not already.
#' @param recursive_depth Argument that is used for selecting how many times the installation should be tried.
#' Defaults to 10. Not intended to be changed.
#'
#' @return
#' @export
#'
#' @examples
#' load_or_install(c('XML', 'jsonlite', 'data.table', 'glue'))
#'
load_or_install <- function(packages, recursive_depth = 10, lib_path = .libPaths()[length(.libPaths())]) {
# try to load libraries, install those missing
# packages_are_installed contains TRUE/FALSE for loaded/not installed packages
packages_are_installed <- sapply(packages, function(package){
if(!require(package, character.only = TRUE)) {
install.packages(package, repos = 'https://cloud.r-project.org', lib = lib_path)
# require returns TRUE for loaded packages, FALSE for those not.
require(package, character.only = TRUE)
} else {
# return TRUE because the package is loaded (the first require())
TRUE
}
})
# We recursively install packages that did not install the previous time
if (!all(packages_are_installed)) {
packages_to_install <- packages[!packages_are_installed]
if (recursive_depth > 0) {
load_or_install(packages_to_install, recursive_depth - 1)
} else {
stop(paste0('ERROR: Even after many (10) tries could not install packages: ', paste(packages_to_install, collapse = ", "), '.'))
}
}
}
load_or_install(packages = c('XML', 'jsonlite', 'data.table', 'glue'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment