Created
April 4, 2011 01:29
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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