Skip to content

Instantly share code, notes, and snippets.

@pmur002
Last active August 29, 2015 14:02
Show Gist options
  • Save pmur002/922c97dd9245c9a0cf4c to your computer and use it in GitHub Desktop.
Save pmur002/922c97dd9245c9a0cf4c to your computer and use it in GitHub Desktop.
Define a function that installs an R package if it is not available
ensurePkg <- function(x, lib.loc=NULL) {
if (is.null(lib.loc)) {
home <- Sys.getenv("HOME")
if (nchar(home)) {
lib.loc <- file.path(home, ".OA.Rlibs")
} else {
lib.loc <- "./.OA.Rlibs"
}
if (!file.exists(lib.loc))
dir.create(lib.loc)
}
if (!require(x, character.only=TRUE, lib.loc=lib.loc)) {
install.packages(x, lib=lib.loc,
repo="http://cran.stat.auckland.ac.nz")
require(x, character.only=TRUE, lib.loc=lib.loc)
}
lib.loc
}
ensurePkgGitHub <- function(x, ..., lib.loc=NULL) {
ensurePkg("devtools", lib.loc)
if (is.null(lib.loc)) {
home <- Sys.getenv("HOME")
if (nchar(home)) {
lib.loc <- file.path(home, ".OA.Rlibs")
} else {
lib.loc <- "./.OA.Rlibs"
}
if (!file.exists(lib.loc))
dir.create(lib.loc)
}
if (!require(x, character.only=TRUE, lib.loc=lib.loc)) {
.libPaths(lib.loc)
local({
r <- getOption("repos")
r["CRAN"] <- "http://cran.stat.auckland.ac.nz"
options(repos = r)
})
install_github(x, ...)
require(x, character.only=TRUE, lib.loc=lib.loc)
}
lib.loc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment