# load_packages_mentioned_in_description ---------------------------------------
#
#' @title Load the Project/Package Packages
#'
#' @description Loads the project's R packages defined in the DESCRIPTION file.
#'
#' @details GIVEN a \code{path} pointing at a directory containing a valid
#' DESCRIPTION file, AND that file contains dependencies, THEN the function
#' loads the defined packages.
#'
#' @param path (`character`) A path to the project's root folder.
#'
#' @return NULL. Prints information about how many packages were loaded and if
#' applicable, which packages failed to load.
#'
#' @examples
#' \dontrun{
#' load_packages_mentioned_in_description(path = rprojroot::find_rstudio_root_file())
#' }
#'
#' @export
#' @keywords internal
#'
load_packages_mentioned_in_description <- function(path) {
###########################
## Defensive Programming ##
###########################
stopifnot(dir.exists(path))
target <- file.path(path, "DESCRIPTION")
if(isFALSE(file.exists(target))) stop("There is no DESCRIPTION file in ", path)
###################################
## Get Packages from DESCRIPTION ##
###################################
description_obj <- desc::description$new(file = path)
description_obj$del_dep(package = "R")
dependencies_table <- description_obj$get_deps()
if(nrow(dependencies_table) == 0) return(invisible())
dependencies_table$flag <- FALSE
for(k in seq_len(nrow(dependencies_table)))
suppressWarnings(
suppressPackageStartupMessages(
dependencies_table[k, "flag"] <-
require(
dependencies_table[k, "package"], quietly = TRUE,
warn.conflicts = FALSE, character.only = TRUE)
)
)
######################
## Show Information ##
######################
n_failure <- sum(dependencies_table[, "flag"] == FALSE)
n_success <- sum(dependencies_table[, "flag"] == TRUE)
message("Preloaded ", n_success, " out of ", n_success + n_failure, " packages declared in DESCRIPTION.")
if (n_failure >= 1){
packages_names <- unlist(subset(dependencies_table, flag == FALSE, select = "package"))
message(paste0(c("Couldn't load the following packages:", packages_names), collapse = "\n-> "))
}
############
## Return ##
############
return(invisible())
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.