Simple management of per-project R versions with direnv

Taha Ahmed

2025-06-14

Motivation

For the sake of repeatability over time (even on the same machine and for same user) it is desirable to pin the R version used by a project.

Repeatability of R packages is mostly already solved thanks to renv, but it does nothing for the R version itself.

direnv has been around for over a decade, is simple to install and use, and appears to work reliably.

Install and setup

Assuming Debian-based OS and bash:

apt install direnv
printf 'if hash direnv >/dev/null 2>&1; then\n   eval \
\"$(direnv hook bash)\"\nfi' >> ~/.bashrc

Can also easily be installed from binary releases for more up-to-date versions, for example my own Ansible role
http://codeberg.org/ansible/direnv.

Using direnv to set a specific R version

  • In the project, create a symlink named R to the desired R binary, e.g., ln -s /opt/R/4.4.3/bin/R bin/R
  • Add the PATH to the .envrc file
$ cat .envrc
PATH_add bin

Finally, allow direnv and it will start doing its magic!

Example config with VSCodium IDE

VSCodium with the following extensions:

With the direnv extension, the IDE “just works” and always reflects the environment of the current working directory.
Also, do set a relative path to R: { "settings": { "r.rpath.linux": "R" } } in your user or workspace settings.

Summary

Thank you for listening!

http://solarchemist.se/contact