Using Nix to Create R Virtual Environments

Previously we saw how to use Nix to create virtual environments for Python. We can do the same for R. This means we can have different simultaneous R installations for different projects and keep the installed packages for each project separated. An important benefit of this is the ability to have different (incompatible) versions of the same packages for different projects.

The straightforward approach is to let Nix handle all R package management. However, sometimes it is useful to manage packages through the various R tools such as the built-in install.packages or install utilities provided by the devtools package.

R looks for installed packages in the R library directories, of which there are two types: the system library and the user library. By default these package management tools install packages in the first-specified user library directory. The user library directories can be specified through the R_LIBS_USER environment variable. We can use Nix to specify a unique library directory per project.

For example, create a nix.shell in your project root as follows:

with import <nixpkgs> {};
let
  my-r = rWrapper.override {
    packages = with rPackages; [ 
      ggplot2
      plyr
      tidyr
      devtools
    ];
  };
in  
  pkgs.mkShell {
    buildInputs = [
      bashInteractive
      my-r
    ];
    shellHook = ''
      mkdir -p "$(pwd)/_libs"
      export R_LIBS_USER="$(pwd)/_libs"
    '';
  }

Activate it in your shell by running $ nix-shell.

This makes available R with ggplot, plyr, tidyr and devtools. It creates a subdirectory in your project root, _libs, where the project’s R user library is located.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.