Monday, August 19, 2013

A way to simplify package use on a R project

Introduction

Introduction

One of the steps that I always do when I begin an R script is to check if all the needed packages are installed, and if not install them.

That way I know that the script won't crash on another computer because of a missing package (one less reason to crash :D).

Lately I've been thinking about the subject of code reuse and decided to transform my block of code in to an R function.

The Code

#«««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««
#  script : loadlib.R
#  author : Vitor Chagas(VC)                last updated : 2013.08.19
#«««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««

# install & load necessary packages ----
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

loadlibs <- function(...) {

  necessary <- as.vector(as.character(match.call()[-1]))

  installed <- necessary %in% .packages(all.available = TRUE)

  # install
  if (length(necessary[!installed]) >=1)
    install.packages(necessary[!installed])

  # update
  update.packages()

  # load
  for(pkg in necessary)
    library(pkg, character.only=TRUE)  

  rm(necessary, installed, pkg)
}

Final comments

Now I just save this code into a lib folder, and then use the following code to source every code file in there

sapply(list.files(pattern="*.R", path="lib", full.names=TRUE),
       source,.GlobalEnv)