-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcheck_pkg.R
More file actions
52 lines (45 loc) · 1.74 KB
/
Copy pathcheck_pkg.R
File metadata and controls
52 lines (45 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#' Install and Load Multiple R Packages
#'
#'Author: Juliano Palacios Abrantes
#'Date: August, 2025
#' This function checks whether the packages listed in the pkg_list are installed.
#' If any are missing, it installs them from CRAN (including dependencies) and then
#' loads all packages in the list into the current R session.
#'
#'@param pkg_list A character vector of package names to be installed (if missing) and loaded.
#' @details
#' The function:
#' \enumerate{
#' \item Compares \code{pkg_list} against the packages currently installed (via \code{installed.packages()}).
#' \item Installs any packages not already installed, including their dependencies, from the CRAN mirror at \code{http://cran.us.r-project.org}.
#' \item Loads all packages in \code{pkg_list} using \code{require()}.
#' }
#'
#' @return
#' A logical vector (invisibly) indicating the success of loading each package, as returned by \code{sapply()} over \code{require()}.
#'
#' @examples
#' \dontrun{
#' my_load(c("dplyr", "ggplot2", "sf"))
#' }
#'
#' @seealso \code{\link[base]{installed.packages}}, \code{\link[base]{install.packages}}, \code{\link[base]{require}}
#'
#' @export
check_pkg <- function(pkg_list){
new.pkg <- pkg_list[!(pkg_list %in% installed.packages()[,"Package"])]
if(length(new.pkg) >0){
message(paste0("One moment, I am installing the following required package(s): ",new.pkg))
install.packages(new.pkg, dependencies = TRUE)
}
success <- suppressMessages(
sapply(pkg_list, require, character.only = TRUE)
)
# Warn if any still failed
if (any(!success)) {
warning("These packages could not be loaded: ",
paste(pkg_list[!success], collapse = ", "))
} else {
message("✅ All required packages loaded")
}
}