Last Updated: November 03, 2016
·
487
· unsignedzero

Making library calls in R easier

In R, if you have a library(<package>) call, it assumes that the package is already install. If it is not, then R will load up an interactive menu asking for the repo you want to install from.

If you don't want to deal with the hassle of making sure its installed, use this. This should make grabbing repos, on say Github, and running them much easier. Edit the repos line as needed, if you aren't from the US.

#' Installs the package, if it exists, and bypasses the interactive
#' prompt.
#'
#' The default location, if not specified, is at .libPaths()[1] which is
#; usually /usr/lib/R/site-library
#'
#' @param pack the package that will be installed
#' @param ... any other arguments passed for install.packages
#' @return NULL this is a statement. Use other functions to check if
#'  install works
#' @examples
#' install('e1071')
#' @seealso \code{\link{lib}}
install = function (pack, ...) {

  install.packages(pack,
    dependencies=TRUE, repos='http://cran.us.r-project.org',
    ...
  )
}
inst = install # Function alias

#' Checks if a package is installed
#'
#' @param pack the package we will check
#' @param ... any other arguments for library
#' @return a boolean value if it is installed correctly
#' @seealso \code{\link{lib}}
libCheck = function (pack, ...){

  # Load a lib from .libPaths()[1]

  return (suppressWarnings(
    library(pack,
      logical.return = TRUE, character.only = TRUE,
    ...)
    )
  )
}

#' Checks if a package is installed and loads it. If not, it will install and then
#' try to load it
#'
#' @param pack the package that will be checked
#' @param ... other arguments passed into libCheck
#' @return a boolean stating if it is loaded
lib = function (pack, ...){

  if (libCheck(pack, ...)){
    # Loaded successfully
    return (TRUE)
  }
  else{
    # Try to install and load
    install(pack)
    return (libCheck(pack, ...))
  }
}