This post describes how to properly install multiple versions of R alongside on Ubuntu OS and to set up a properly controlled renv environment.

Preparation

It is better to start with a fresh installation of R. However, if R is already installed, especially if it is installed from the Ubuntu repository, it is better to get rid of the old version first:

sudo apt autoremove --purge r-base r-base-dev r-recommended

In addition, removing the packages is not enough to remove R most of the times. A safe approach is to simply change the binary name in /usr/bin with:

sudo mv /usr/bin/R /usr/bin/R2

(which is an ugly way to solve this issue, indeed).

Installing R from scratch

Inspired by this tutorial, we can now install any R version obtained from the RStudio repository (under the form of a .deb package). The following lines of codes are given for R version 4.0.3:

export R_VERSION=4.0.3
curl -O https://cdn.rstudio.com/r/ubuntu-2004/pkgs/r-${R_VERSION}_1_amd64.deb
sudo dpkg -i r-${R_VERSION}_1_amd64.deb
sudo apt install -f

At this stage, R should be properly installed and work with:

/opt/R/${R_VERSION}/bin/R

The last stage of the installation would ensure that the R binary is properly linked into a bin folder:

sudo ln -s /opt/R/${R_VERSION}/bin/R /usr/local/bin/R
sudo ln -s /opt/R/${R_VERSION}/bin/Rscript /usr/local/bin/Rscript

If you are using RStudio with multiple R versions installed as described here, you can choose between them as described here.

renv environment

Within our project directory, if the renv.lock file is already present and has never been used, the virtual R environment is installed with the following R command lines:

install.packages("renv")
renv::init()

In our case, some packages have shown additional issues:

  • nloptr required the installation of an additional Ubuntu library:
    sudo apt install libnlopt-dev
    
  • some packages depended on curl and required the installation of:
    sudo apt install libcurl4-openssl-dev
    
  • ps had a problem with a wrong installation directory for sed that can be resolved creating a symbolic link:
    ln -s /bin/sed /usr/bin/sed
    

When the renv initialization process is interrupted, it can be resumed with:

renv::restore()