Download, build and install R from source

A new version of the R source was released today and so, as is customary, I download and install it on my personal Linux servers. My main server runs Ubuntu and the other run CentOS.

To download, build and install R I use the below script. It relies on you having ‘sudo’ enabled for your account as well as already having the build dependencies installed (see this post from RStudio for more info).

Once you have the script copied to your server - I call it ‘buildR’ - make sure it’s executable and then run:

$ ./buildR 3.6.0

This will download the specified version’s source code from CRAN. Unpack the source, configure the build, run the build and finally, install R.

The script is as follows:

#!/usr/bin/env bash
set -euo pipefail

function usage () {
  echo "Usage: $(basename $0) <R version number>"
  echo "   eg. $(basename $0) 3.4.4"
  exit 1
  }


R_VERSION=${1:-"missing"}

if [[ ${R_VERSION} == "missing" ]]; then
    echo "Error - No R version specified"
    usage
fi

R_MAJOR_VERSION=${R_VERSION:0:1}

wget -q https://cran.r-project.org/src/base/R-${R_MAJOR_VERSION}/R-${R_VERSION}.tar.gz

if [[ ${?} -ne 0 ]]; then
  echo "Error - Problem downloading R-${R_VERSION} - check output and try again"
  exit 1
fi

tar -zxvf R-${R_VERSION}.tar.gz

cd R-${R_VERSION}

./configure --prefix=/opt/R/${R_VERSION} --enable-R-shlib --with-blas --with-lapack

make

sudo make install

cd ..

I’ve used this to build many versions of R that I’ve used for my projects or testing things over the last few years, so I figured it was time to share it, in case anyone else finds it useful.