Skip to content

Instantly share code, notes, and snippets.

@noahhl
Created April 4, 2011 01:29
Show Gist options
  • Select an option

  • Save noahhl/901019 to your computer and use it in GitHub Desktop.

Select an option

Save noahhl/901019 to your computer and use it in GitHub Desktop.
Find package dependencies in R source files and optionally try to install them
# This function finds all "require" and "library" statements within a
# directory tree of R code and optionally attempts to install them as
# quietly as possible.
# Usage: setwd("yourcodedirectory"); FindDependencies()
# To install required packages if not currently available, run
# FindDependencies(install=T).
FindDependencies <- function(install=F) {
files <- dir(pattern="\\.R$|\\.S$|\\.r$|\\.s$", recursive=T)
dependencies <- c()
for (i in files) {
f <- suppressWarnings(readLines(i))
dep <- f[grep("require|library", tolower(f))]
dep <- gsub("require|library|\\(|\\)| |\\\t", "", dep)
dependencies <- c(dependencies, dep)
}
dependencies <- unique(dependencies)
cat("Required packages:\n",paste(dependencies, collapse="\n"), "\n")
if(install) {
for(i in dependencies) {
if(!suppressWarnings(require(i, character.only=T))) {
suppressWarnings(install.packages(i))
if(!suppressWarnings(require(i, character.only=T)))
cat("Could not install package", i, "\n")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment