Skip to content

Instantly share code, notes, and snippets.

@bonifazi
Last active April 26, 2023 17:18
Show Gist options
  • Save bonifazi/1b90d73a0515752a81a65eecb481cc76 to your computer and use it in GitHub Desktop.
Save bonifazi/1b90d73a0515752a81a65eecb481cc76 to your computer and use it in GitHub Desktop.
Check and load R packages
# different (similar) ways to check and load pkgs in R
# method 1
check_pkgs <- function(pkg_list){
for(pkg in pkg_list) {
if(!require(pkg, character.only = T)){
stop('Please install the ', pkg, ' package, using "install.packages(', pkg, ')"', call. = F)
}
}
}
check_pkgs(pkg_list = c("asserththat", "ggplot2"))
# method 1 + install missing packages
check_pkgs <- function(pkg_list){
for(pkg in pkg_list) {
if(!require(pkg, character.only = T)){
cat('Installing the ', pkg, ' package, using "install.packages(', pkg, ')')
install.packages(pkg, repos = "http://cran.us.r-project.org")
}
}
}
check_pkgs(pkg_list = c("asserththat", "ggplot2"))
# method 2
check_pkgs <- function(...){
for (pkg in c(...)) {
if(!require(pkg, character.only = T)){
stop('Please install the ', pkg, ' package, using "install.packages(', pkg, ')"', call. = F)
}
}
}
check_pkgs("assertthat", "ggplot2")
# method 3
check_pkgs <- function(...){
for (pkg in c(...)) {
if(pkg %in% rownames(installed.packages())) {
cat("- Loading required package: ", pkg, "\n")
do.call('library', list(pkg))
} else {
stop('Please install the ', pkg, ' package, using "install.packages(', pkg, ')"', call. = F)
}
}
}
check_pkgs("assertthat", "ggplot2")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment