Skip to content

Instantly share code, notes, and snippets.

@jefferys
Last active February 18, 2021 23:46
Show Gist options
  • Save jefferys/772418e7c5634a99b86edd4b5b3ea5ae to your computer and use it in GitHub Desktop.
Save jefferys/772418e7c5634a99b86edd4b5b3ea5ae to your computer and use it in GitHub Desktop.
Check for needed R packages, optionally installing them.
hasPackage <- function( package ) {
suppressWarnings( suppressMessages(
require( package, quietly= TRUE, warn.conflicts= FALSE, character.only= TRUE )
))
}
# Set progress=FALSE to hide progress messages. Install messages always
# displayed as they are changing the system.
ensurePackages <- function( packages, installOk= FALSE, progress= TRUE,
exitOnError= installOk ) {
# First package must be "BiocManager" as that is used.
# Second package will be "remotes" if any package name includes "/",
# e.g. is installed from github
packages <- packages[ packages != "BiocManager" ]
if (any( grepl( pattern = "/", packages, fixed= TRUE ))) {
packages <- packages[ packages != "remotes" ]
packages <- c( "remotes", packages )
}
packages <- c( "BiocManager", packages )
if ( progress ) {
message( "Verifying required R packages..." )
}
for (package in packages) {
if ( progress ) {
message( paste0( "\t", package, "..." ))
}
if ( ! hasPackage( package )) {
if ( ! installOk ) {
errMsg <- paste0(
"Required package '", package, "' not found.",
" Auto-install is not enabled;",
" you'll have to install it yourself."
)
if (exitOnError) {
stop( errMsg )
}
else {
warning( errMsg )
}
} else {
message( "Installing '", package, "' and dependencies...")
if (package == "BiocManager") {
install.packages( "BiocManager", character.only= TRUE,
quiet= TRUE, verbose= FALSE )
}
else {
BiocManager::install( package, update=FALSE, ask=FALSE )
}
if ( ! hasPackage( package )) {
errMsg <- paste0(
"Installing ", package, " seems to have failed.",
" Please try installing manually."
)
if (exitOnError) {
stop( errMsg )
}
else {
warning( errMsg )
}
}
}
}
}
}
checkBioconductor <- function( biocVersion ) {
# No need to validate the version, it
# will fail in the comparison if not formatted correctly.
version <- BiocManager::version()
if ( version != numeric_version( biocVersion )) {
warning( paste0(
"This is intended to work with BioConductor ", biocVersion,
". May not work with the currently installed BioConductor (",
version, ")."
))
}
}
# Use like
# myPackages <- c("someCranPackage", "someBioconductorPackage", "author/githubRepoPackage", "author/repo@tag_or_branch")
# ensurePackages( myPackages, installOk= TRUE )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment