Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jmfernandez/500a6b332fbb4345c5daef2568184858 to your computer and use it in GitHub Desktop.
Save jmfernandez/500a6b332fbb4345c5daef2568184858 to your computer and use it in GitHub Desktop.
Reproducible R scripts with packrat

The way to be able to record all the exact versions of the R packages being used (even BioConductor ones), and install them later, is using packrat.

This gist shows an example where CRAN and Bioconductor packages are installed and recorded.

Later, the minimum information is put in a different directory (and machine), and all the installed packages and their dependencies are installed, using the same, exact version used when it was previously installed.

#!/usr/bin/Rscript
# First, install packrat (if it is needed!)
if (!require(packrat)) {
install.packages('packrat')
library(packrat)
}
# We are declaring the directory where to install
# all of these packages. For instance, ~/RATAMAN2
packrat::init("~/RATAMAN2")
# This is needed to activate the new environment
packrat::on("~/RATAMAN2")
# A CRAN package is installed
install.packages("reshape2")
# Bioconductor itself must be recorded
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
# This line adding the Bioconductor repositories is needed,
# in order to have the URLs to their repos in the
# reproducible snapshot
options(repos=structure(BiocManager::repositories()))
# Now, installing several packages from Bioconductor
BiocManager::install()
BiocManager::install(c("GenomicFeatures", "AnnotationDbi"))
# At last, the snapshot is generated
packrat::snapshot()
#!/usr/bin/Rscript
# This is needed, in case packrat is not already installed
if(!require(packrat)) {
install.packages('packrat')
library(packrat)
}
# Now, time to populate the current environment
packrat::restore("~/newRATA")
# From this point, the environment has all the dependencies,
# and it is ready to be used
#!/bin/bash
# At this point, you should have an environment at `~/RATAMAN2`.
# You should copy from inside that directory only a few files.
# .Rprofile , packrat/init.R , packrat.lock and packrat.opts
# Let's create the new directory for the reproduced environment.
# For instance, `~/newRATA`
mkdir -p ~/newRATA ~/newRATA/packrat
# Now, let's copy the minimum information needed to regenerate
# the environment
cp -p ~/RATAMAN2/.Rprofile ~/newRATA
cp -p ~/RATAMAN2/packrat/{init.R,packrat.*} ~/newRATA/packrat
# Last, you have to run next code from an R console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment