Robert's Data Science Blog

Choosing a CRAN with renv

The renv package is a great way to isolate projects. The documentation for renv is good, so I am not writing an introduction to renv here. Instead I want to focus on how I set a CRAN mirror for projects.

MRAN

As noted in multiple posts I use a suitable MRAN for R packages to ensure that the packages are compatible with the R version I am using.

When using renv::snapshot() to save the state of a project we get a file renv.lock. For a project using R 3.6.1 and whose only dependency is the glue package the renv.lock file looks like this:

{
  "R": {
    "Version": "3.6.1",
    "Repositories": [
      {
        "Name": "CRAN",
        "URL": "https://mran.microsoft.com/snapshot/2019-12-12"
      }
    ]
  },
  "Packages": {
    "glue": {
      "Package": "glue",
      "Version": "1.3.1",
      "Source": "Repository",
      "Repository": "CRAN",
      "Hash": "d4e25697c450c01b202c79ef35694a83"
    },
    "renv": {
      "Package": "renv",
      "Version": "0.9.2",
      "Source": "Repository",
      "Repository": "CRAN",
      "Hash": "5181d5f316c7a6589219866d640e004c"
    }
  }
}

A key thing about renv is that it tracks the version of each package. When using renv::restore() to restore a project it downloads the specific version. If the version in renv.lock is not the latest version available in the repository it simply downloads the requested version from the archive that every package has on a CRAN.

Since MRAN contains copies of the entire official CRAN it also contains the archives of each package.

CRAN

MRAN fulfills it purpose of compatabilty. The only downside is that it is much slower to download packages from MRAN than from the 0-Cloud mirror.

However, due to the nature of MRAN and renv::restore, we can simply replace the Repositories field:

"Repositories": [
  {
    "Name": "CRAN",
    "URL": "https://cran.rstudio.com"
  }
]

This of course only works when restoring, not when snapshot’ing.