Skip to content

Instantly share code, notes, and snippets.

@lebriggs
Created July 2, 2024 18:04
Show Gist options
  • Save lebriggs/736ff4f9afd5e133b6aaa4b76cabd53f to your computer and use it in GitHub Desktop.
Save lebriggs/736ff4f9afd5e133b6aaa4b76cabd53f to your computer and use it in GitHub Desktop.
R Package Installation And Loading Script With Error Handling And Feedback
#Author: L. E. Briggs
#Date: 2 July 2024
# Overview:
# This script checks if the required R packages are already installed and installs them if missing, including all dependencies.
# It provides feedback on the status of each package installation and loading process.
# The code balances error handling with simplicity, making it easy to understand.
# I. Initial Set-up: Install and Load Required Packages with Basic Feedback
#this script installs and loads required packages with basic feedback
#separating the installation check from the loading step ensures a more robust process
#list of required packages
#fakepkg is a placeholder for testing error handling
pkg2 <- c("fakepkg", "here", "gt", "gtExtras")
#create a function to install and load packages with feedback
#installing all dependencies minimizes potential issues with missing packages
#adding messages provides feedback on the installation and loading status of each package
install_and_load <- function(package) {
tryCatch({
if (!package %in% rownames(installed.packages())) { #check if package is installed
install.packages(package, dependencies = TRUE) #install the package with all dependencies
Sys.sleep(2) #ensure the installation process completes properly
.libPaths(.libPaths()) #reload the library paths
if (!require(package, character.only = TRUE)) { #try to load the package again
return(paste("failed to install or load package:", package)) #return message if loading fails
} else {
return(paste(package, "was installed and loaded successfully.")) #return message if successful
}
} else {
if (!require(package, character.only = TRUE)) { #try to load the package
return(paste("failed to load package:", package)) #return message if loading fails
} else {
return(paste(package, "was already installed and loaded.")) #return message if already installed and loaded
}
}
}, error = function(e) {
return(paste("error installing or loading package:", package, "-", e$message)) #extract and return the error message
})
}
#install and load packages
install_results <- lapply(pkg2, install_and_load)
#print installation and loading results with a title
cat("Summary:\n", unlist(install_results), sep = "\n")
# II. Subsequent Session(s): Load Required Packages
#list of required packages that were previously installed
pkg2 <- c("fakepkg", "here", "gt", "gtExtras")
#load packages that were previously installed
lapply(pkg2, require, character.only = TRUE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment