renv
The renv
package helps you create reproducible environments for your R projects. Use renv
to make your R projects more:
Isolated: Installing a new or updated package for one project won’t break your other projects, and vice versa. That’s because renv
gives each project its own private package library.
Portable: Easily transport your projects from one computer to another, even across different platforms. renv
makes it easy to install the packages your project depends on.
Reproducible: renv
records the exact package versions you depend on, and ensures those exact versions are the ones that get installed wherever you go.
Workflow
The general workflow when working with renv
is:
Call
renv::init()
to initialize a new project-local environment with a private R library,Work in the project as normal, installing and removing new R packages as they are needed in the project,
Call
renv::snapshot()
to save the state of the project library to the lockfile (calledrenv.lock
),Continue working on your project, installing and updating R packages as needed.
Call
renv::snapshot()
again to save the state of your project library if your attempts to update R packages were successful, or callrenv::restore()
to revert to the previous state as encoded in the lockfile if your attempts to update packages introduced some new problems.
The renv::init()
function attempts to ensure the newly-created project library includes all R packages currently used by the project. It does this by crawling R files within the project for dependencies with the renv::dependencies()
function. The discovered packages are then installed into the project library with the renv::hydrate()
function, which will also attempt to save time by copying packages from your user library (rather than reinstalling from CRAN) as appropriate.
Calling renv::init()
will also write out the infrastructure necessary to automatically load and use the private library for new R sessions launched from the project root directory. This is accomplished by creating (or amending) a project-local .Rprofile
with the necessary code to load the project when the R session is started.
If you’d like to initialize a project without attempting dependency discovery and installation – that is, you’d prefer to manually install the packages your project requires on your own – you can use renv::init(bare = TRUE)
to initialize a project with an empty project library.
For full details, see the renv
package documentation.
New project, use renv with this project
The general details on creating a new Project in RStudio are covered in RStudio Projects. Users can opt in to using renv
when creating a new Project in RStudio.
Select the Use renv with this project checkbox, and the new project will automatically create and activate the necessary scaffolding for renv
within that project. Since those files now exist in the newly created project, you can skip step 1 from the above workflow.