Skip to content

Instantly share code, notes, and snippets.

@jonsedar
Last active December 15, 2015 12:18
Show Gist options
  • Save jonsedar/5259236 to your computer and use it in GitHub Desktop.
Save jonsedar/5259236 to your computer and use it in GitHub Desktop.
[R] Convenience function to load R libraries or install then load if they're not found. Handy when deploying/executing new code on several servers. Uses the active boolean response from require() rather than the passive library() load function. Replace the repo with your favorite. This will install libraries to your system's default location.
lib_getter <- function(y){
# Accepts a char array of package / library names, and loads or installs then loads them
# Returns a char array of load status messages
r <- ''
for (x in y) {
if (!require(x,character.only=TRUE,quietly=TRUE,warn.conflicts=FALSE)) {
install.packages(x, repos="http://cran.ma.imperial.ac.uk/")
if(require(x,character.only=TRUE,quietly=TRUE,warn.conflicts=FALSE)) {
r <- c(r,paste(x,'installed and loaded'))
} else {
r <- c(r,paste('could not install',x))
}
} else {
r <- c(r,paste(x,'loaded correctly'))
}
}
return(r[-1])
}
# Example usage for loading / installing then loading some libraries
l <- lib_getter(c('ggplot2','plyr','data.table','futile.logger'))
print(l)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment