In order to exactly reproduce a given result, it may be necessary to use programs in the exact versions used originally.
Sandve, Nekrutenko, Taylor, and Hovig, Ten Simple Rules for Reproducible Computational Research, Rule 3 (2013)
By the end of this chapter you will be able to pin the exact version of every package an analysis uses. A colleague who restores the lockfile a year from now will then run the same code against the same packages as the original run, rather than whatever happens to be current on their machine. You will also be able to say precisely which layer of the determinant stack that pin does and does not reach.
NoteBefore you start
Reading time. About 45 minutes.
Prerequisites.Chapter 3, for the L0-L3 ladder, the determinant stack, and the capture-versus-validation vocabulary this chapter relies on throughout. Chapter 5, for the DESCRIPTION file and the R-package archetype the dependency triad draws its middle term from. Statistically, nothing beyond reading a package version number is required. R knowledge assumed: calling library(), installing a package, and reading a JSON file as a nested list; no prior exposure to renv itself is assumed.
Objectives. By the end of this chapter, can you:
Explain the package-churn failure mode, and say why pinning package versions is the step that lifts an analysis from locatable (L0) to package-pinned (L1)?
Describe what an renv.lock file records, and carry out the init, snapshot, and restore workflow that produces and consumes it?
State the dependency-triad invariant relating the code, the DESCRIPTION, and the lockfile, and run the automated check that keeps the three in agreement?
Configure a dated snapshot of a package repository so that a restore draws fixed versions, as pre-compiled binaries where the platform is served?
Delimit what renv does and does not pin, and thus explain why a lockfile alone cannot reach the pinned-environment level?
Outline. The package-churn failure mode and the L0-to-L1 transition it motivates; the three judgments that stay with the analyst; packrat to renv and what a lockfile records; the init, snapshot, restore workflow; the dependency-triad invariant and the automated check that enforces it; dated snapshots of a package repository; the limits of renv; lighter alternatives; the cohort’s own dependencies, scanned for real; collaborating with an LLM; exercises, a cheat sheet, and further reading.
NoteCheck your understanding: from earlier chapters
A colleague clones your cohort repository at its submission tag and runs analysis/scripts/01-clean.R on the unchanged raw extract. The cleaned table has fewer rows than the committed analysis/data/derived_data/cohort_clean.csv. The history shows that the outlier threshold in the script was tightened after that file was last committed. On the same machine, the script as it stood when the file was committed reproduces the file’s row count. Drawing on Chapter 3, Chapter 4, and Chapter 5, name the failure and the rule it breaks.
NoteAnswer
The cleaned cohort table with fewer rows exposes a stale derived file, not a package or environment change. On one machine the old script reproduces the old count and the current script does not, so only the analysis code differs. The committed file breaks the promise of Chapter 5 that a file in derived_data/ can always be regenerated from the raw inputs and the code. The history of Chapter 4 locates the change: git log on the script lists the commit, and git show displays its diff. The tag secures L0 on the ladder of Chapter 3. It fixes which code a reader finds, not that a stored output still matches that code. The remedy is to regenerate the file from the raw extract and the current script.
6.1 Where this sits on the stack
This chapter’s whole business is the lockfile, so it is the clearest capture in the book so far. It pins, for the first time, the package-versions layer of the determinant stack that Chapter 3 laid out. That is exactly the step from L0 to L1. Figure 6.1 marks that single layer against the ambient nine, with every other layer left faded as secured, or left unpinned, elsewhere.
plot_determinant_stack( captures =c('Package versions'), title ='Pinning packages captures one layer, and one layer only')
Figure 6.1: The determinant stack of Chapter 3, with package versions marked as captured here. Pinning this one layer with a committed renv.lock is the L0-to-L1 transition this chapter teaches; the R runtime, the operating system, and the system libraries beneath it remain unpinned until Chapter 7 adds the container.
6.2 Orientation
To illustrate, consider a familiar situation. A doctoral student completes the analysis for a registry study of hospital readmissions, renders a clean report, and deposits the code alongside the manuscript. The work is under version control, so a reader can locate every script; on the ladder of Chapter 3 the analysis has reached L0, locatable. Eighteen months later a reviewer asks for a minor revision. The student pulls the repository onto a new laptop, installs the packages afresh, and reruns the analysis. The model now reports a different coefficient. Nothing in the code changed. What changed is that dplyr had moved from version 1.1.0 to 1.2.1, a grouping default had been refined, and one intermediate summary was computed over a slightly different partition. The number in the published table can no longer be regenerated, and the student cannot say with certainty which number was correct.
This is the package-churn failure mode. It is the specifically computational failure that the empirical studies of Chapter 2 isolate. The R package ecosystem is healthy precisely because it changes: maintainers fix bugs, sharpen defaults, and deprecate awkward interfaces. Every such improvement is, however, a potential threat to the exact reproduction of an analysis written against the older behavior. A script names the packages it loads but almost never the versions it loaded them at. It therefore inherits whatever versions the next machine happens to provide.
The remedy for this one layer is a lockfile, a file that records the exact version of every package the analysis used so that the same set can be reinstalled later. Recording that file is the transition from L0 to L1, from locatable to package-pinned, and it is the whole business of this chapter. We shall be equally careful about the transition’s limit. A lockfile pins the packages and nothing beneath them. An analysis at L1 is therefore pinned at the package layer and exposed at every layer below, a boundary that motivates the container of Chapter 7.
The chapter proceeds as follows. We begin with the three judgments that stay with the analyst, then trace the line from packrat to renv and examine what a lockfile records. We next work through the init, snapshot, and restore workflow, the dependency-triad invariant and the automated check that enforces it, and dated snapshots of a package repository. We then set out the limits of renv and some lighter alternatives. Lastly, we scan the cohort’s own dependencies for real and consider how to collaborate with an LLM on this material.
NoteCheck your understanding: naming the failure
The student’s code did not change, and the published table can no longer be regenerated. What single determinant changed, and what artifact would have prevented the drift?
NoteAnswer
The package-versions layer changed. dplyr moved from 1.1.0 to 1.2.1 between the original run and the revision, and a refined grouping default altered an intermediate summary. A committed renv.lock, restored rather than freshly installed, would have reinstalled the exact version the student originally ran against. That would have closed the gap the bare script left open.
6.3 The analyst’s contribution
The tooling in this chapter automates a great deal. However, three judgments remain irreducibly the analyst’s.
Deciding when to snapshot, and what a snapshot claims. A lockfile is a dated assertion that these versions produced this result. The analyst chooses the moment to make that assertion, typically once an analysis is stable, and must understand that a snapshot taken mid-exploration pins whatever half-installed state the library happens to be in.
Distinguishing a result dependency from a development tool. No scanner can know that languageserver powers the editor while dplyr powers the analysis. The analyst must keep the lockfile an honest, minimal record of what determines the result, and keep mere tooling out of it, a distinction we develop below and that the accompanying whitepaper treats at length.
Matching the reproducibility claim to the layer actually pinned. A lockfile secures the package layer and no other. Presenting a lockfile-equipped analysis as fully reproducible, when the R version, the operating system, and the system libraries remain unpinned, overstates what has been achieved, and only the analyst can prevent that.
NoteThe vocabulary of this chapter
Lockfile. A machine-generated file, renv.lock, recording the R version, the package repositories, and the exact version and source of every package the project uses, together with metadata copied from each package’s DESCRIPTION.
Package library. The directory into which R installs packages. A project-local library belongs to one project rather than being shared across all of a user’s work.
Snapshot. The act of scanning a project, resolving the versions currently installed, and writing them into the lockfile.
Restore. The reverse act of reading the lockfile and reinstalling exactly the packages it records.
DESCRIPTION. The human-authored file that declares a project’s direct dependencies by role (Imports, Suggests, Depends), with optional version floors.
Package record. The lockfile entry for one package: its name, version, and source, plus fields such as Imports and License copied from its DESCRIPTION. It contains no checksum of the package’s files.
Package repository. A server, such as CRAN or the Posit Package Manager, from which packages are installed.
Dated snapshot. A view of a repository frozen as it stood on a particular calendar day, so that an install run today and one run next year fetch the same versions.
NoteCheck your understanding: tool versus judgment
renv::snapshot() can scan a project’s code for packages and write them to the lockfile automatically. Name one of the three judgments above that this automation does not make for the analyst.
NoteAnswer
Any one of the three. The first is the moment at which a snapshot is taken, and therefore what state of the library it asserts as correct. The second is the distinction between a package the result depends on and a package that merely serves the analyst’s editor or workflow. The third is the honest match between the reproducibility claim made and the layer the lockfile actually pins. The scan makes none of these three decisions.
6.4 From packrat to renv
We begin with some history. The idea of a project-local library governed by a lockfile is not new to R. The packrat package, begun in 2013 and on CRAN from 2014, was the first widely adopted attempt to give each project its own isolated set of packages recorded in a manifest. Its mechanics were sound but its ergonomics were not, and it acquired a reputation for surprising behavior that discouraged routine use. The renv package, introduced by Ushey & Wickham (2026) and now the community standard, superseded it in 2019. It kept the essential idea, a project-local library plus a lockfile. However, it rebuilt the surface around a small, predictable set of verbs, a human-readable JSON lockfile, and a shared package cache. The cache lets many projects share one physical copy of a given package version.
The design separates two things. The library is where packages physically live; the lockfile is the written record of what should live there. The two are kept in agreement by two complementary operations. A snapshot reads the library and updates the lockfile to match it; a restore reads the lockfile and updates the library to match it. Everything renv does is a variation on keeping these two representations in step.
NoteCheck your understanding: library or lockfile
A teammate deletes their project’s library folder by accident, but the lockfile is untouched and committed. Which operation restores their ability to work, and which of the two representations was lost?
NoteAnswer
renv::restore() restores it, by reading the lockfile and reinstalling the packages it records into a fresh library. What was lost was the library, where packages physically live. The lockfile, the written record of what should live there, was never at risk, because it is a small committed text file rather than a directory of installed code.
6.4.1 What the lockfile records
The lockfile is the artifact that does the pinning, so it repays close reading. The top of the file records the R version and the repositories in force. Below that, each package has a record giving its exact version and the source it came from. Fields copied from the package’s own DESCRIPTION follow: its title, license, declared dependencies, whether it contains compiled code, and more. The excerpt below comes from a lockfile that renv 1.2.3 wrote on 2026-10-11, under R 4.6.1, for a one-line script that calls library(dplyr). It is shown as a static block because renv does not run while this book renders. It is abbreviated only by deleting fields and records; nothing has been added or reordered. The record for dplyr omits, among others, its Type, Authors@R, Description, URL, and Suggests fields.
Four features deserve comment. First, the version is recorded exactly, 1.2.1 and not >= 1.2, so there is no latitude for a later install to drift upward. The version floors inside Imports, such as rlang (>= 1.1.7), are a different thing. They are dplyr’s own statement of what it tolerates, copied from its DESCRIPTION. The pin for rlang is the exact version in rlang’s own record.
Second, the source is named. A package that came from CRAN, from a Posit Package Manager mirror, from Bioconductor, or from a specific GitHub commit is recorded as such. By default renv::restore() looks for it in the same place, since the same version number can denote different code on different repositories. The Repository value is the registered name of the repository the package was drawn from, matching one of the names in the Repositories block above. This is why the excerpt records CRAN even though that entry points at a Posit mirror.
Third, the closure is complete. Every contributed package that dplyr needs, directly or through another package, has a record of its own: the full file also holds records for rlang, vctrs, tibble, and the rest, and one for renv itself. Base packages such as methods and utils come with R and have none.
Fourth, and easily misread, the record contains no checksum of the package’s files. Lockfiles written by renv before version 1.1.0 carried a Hash field and a Requirements list, and older tutorials still show them. The change is recorded in the NEWS file that ships with renv. That Hash was a fingerprint of selected DESCRIPTION fields, which renv uses to key its package cache. It was never a hash of the installed files, so it could not confirm that a restored package was byte-identical to the one recorded. A lockfile in either format therefore cannot detect a repository that serves altered contents under an unchanged version string. That protection, such as it is, rests with the repository.
WarningPitfall
A reader who has worked with renv before 1.1.0 may look for the old Hash field and, finding it absent in a current lockfile, worry that integrity checking has been removed. Nothing has been lost, because the old Hash never checked file integrity in the first place. It only fingerprinted DESCRIPTION fields for the package cache. The actual pitfall is believing either format’s record proves the installed bytes match what was recorded. Neither does, and a lockfile’s protection against a repository silently serving different code under the same version string is exactly nil.
6.4.2 The init, snapshot, restore workflow
Three commands drive the ordinary lifecycle. None of them can execute while this book renders, so we show them as static R blocks. The reader runs them at an interactive prompt inside the project.
Initialization creates the project-local library and a first lockfile.
From this point, packages installed into the project go into its private library rather than the shared system-wide one. One project’s dplyr upgrade therefore cannot disturb another’s. As the analysis develops and new packages are installed, a snapshot writes the current state into the lockfile.
The snapshot does not blindly record every installed package. It first scans the project’s source for the packages the code actually references, through library(), require(), and pkg::fun() calls, and records those together with their transitive dependencies. A package sitting in the library but called nowhere in the code is, by default, left out.
On another machine, or the same machine a year later, a restore reads the lockfile and rebuilds the library to match.
A collaborator who clones the repository and calls renv::restore() obtains the exact package set the analysis was written against, irrespective of what versions are current.
In the framework this book uses, this lifecycle is partly automated so that an analyst does not forget the snapshot. The project’s generated .Rprofile installs an exit hook that snapshots the library when an interactive session ends, and restores missing packages when a session begins. A package installed during analysis is thus captured. The automation removes the two most common ways the library and the lockfile drift apart.
TipVerification
To see the pin actually hold: note the installed version of one package (packageVersion('dplyr')), delete the project library, run renv::restore(), and confirm the same version comes back. To make it fail on purpose, open renv.lock in a text editor, change one package’s Version field to a release that does not exist, and rerun renv::restore(). It reports that the requested version cannot be found, rather than silently installing something else.
NoteCheck your understanding: snapshot versus restore
A colleague clones your project, opens R, and is puzzled that the packages are not yet installed. They ask whether they should run renv::snapshot() to get them. What do you advise, and why?
NoteAnswer
They should run renv::restore(), not renv::snapshot(). Restore reads the existing lockfile and installs the recorded versions into the local library, which is exactly what a fresh clone needs. Snapshot runs in the opposite direction. It would overwrite the lockfile with whatever is currently installed, which on a fresh clone is nothing relevant. It would thereby destroy the very record the colleague needs. The mnemonic is that snapshot writes the lockfile and restore reads it.
6.5 The dependency-triad invariant
A lockfile solves the pinning problem. However, it introduces a bookkeeping problem in its place: the lockfile can fall out of step with the code it is supposed to describe. A contributor installs a package for an exploratory notebook and forgets to snapshot, so the code now uses a package the lockfile does not record. Or a package is dropped from the analysis but left in the project’s DESCRIPTION, so the declared dependencies name something the code no longer touches. Either drift silently degrades the pin.
But how are we to know that the lockfile still describes the code? The framework this book uses formalizes the correct relationship as the dependency triad. Three sources of information describe the packages an analysis uses, and in a healthy compendium they satisfy a nesting relation.
The code references some set of packages, through its library(), require(), and pkg::fun() calls.
The DESCRIPTION declares a set of direct dependencies.
The renv.lock records a set of pinned packages.
The invariant is the composition of two atomic inclusions, each set contained in the next:
Read left to right, it says that every package the code calls must be declared in DESCRIPTION, and every declared dependency must be pinned in the lockfile. The lockfile is the largest set because it also records the transitive dependencies that the analyst never named directly. Base packages, which every R installation provides at the R version’s own version, are excluded from the code set. Recommended packages such as survival also ship with R, but they are versioned independently of it and renv records them in the lockfile, so they stay in. The first inclusion therefore concerns every package that is not base.
The invariant needs one qualification. Its strict form, with DESCRIPTION as the binding middle term, holds cleanly for the R-package archetype. There DESCRIPTION is the package’s declared dependency interface, and every package the code calls belongs there by definition. For a research or analysis compendium the middle term is looser. In that case DESCRIPTION declares only the API of the reusable code in R/, while packages used solely by analysis scripts or reports legitimately live in renv.lock without appearing in DESCRIPTION. The operative invariant for a compendium is therefore the weaker \(\mathrm{Code} \subseteq \mathrm{renv.lock}\). That is, the strict DESCRIPTION inclusion is exact for the package archetype but archetype-conditional in general. As a matter of placement an analysis-script dependency may still be listed in DESCRIPTION under Suggests. However, the framework does not enforce the strict DESCRIPTION inclusion as a gate on a compendium, precisely because that inclusion does not hold for one. The gate it enforces on a compendium is the single inclusion \(\mathrm{Code}
\subseteq \mathrm{renv.lock}\), that nothing the code uses goes unpinned. The strict double inclusion is applied only in the package archetype, where DESCRIPTION is the authoritative dependency interface.
Figure 6.2 draws the nesting, with the archetype qualification marked. A package may sit legitimately in any of the three bands; the only broken position is outside the lockfile altogether.
library(ggplot2)library(tibble)bands<-tibble( label =c('renv.lock: everything pinned','DESCRIPTION: declared','Code: actually called'), xmin =c(0.4, 1.5, 2.5), xmax =c(9.6, 8.5, 7.5), ymin =c(0.5, 1.3, 2.1), ymax =c(6.2, 5.4, 4.6), fill =c('#eef4f4', '#dcebea', '#c3ddda'))items<-tibble( x =c(5.0, 5.0, 2.6, 7.4), y =c(3.3, 1.75, 0.92, 0.92), lab =c('dplyr\n(called, declared, pinned)','an unused declaration','rlang, vctrs\n(transitive)','ggplot2, used only by\nanalysis scripts'))ggplot()+geom_rect(data =bands,aes(xmin =xmin, xmax =xmax, ymin =ymin, ymax =ymax, fill =fill), color ='grey40', linewidth =0.4)+scale_fill_identity()+geom_text(data =bands, aes(x =xmin+0.15, y =ymax-0.25, label =label), hjust =0, fontface ='bold', size =3.1)+geom_text(data =items, aes(x =x, y =y, label =lab), size =2.9, lineheight =0.95, color ='grey20')+annotate('point', x =3.55, y =0.02, shape =4, size =2.6, stroke =1.1, color ='#a33')+annotate('text', x =3.75, y =0.02, hjust =0, label ='survival: used but unpinned', size =3.1, fontface ='bold', color ='#a33')+coord_cartesian(xlim =c(0.2, 9.8), ylim =c(-0.35, 6.4))+theme_void()
Figure 6.2: The dependency triad as nested sets, with example packages placed in each region. Everything the code calls must be pinned, so a package outside the lockfile is the one broken position and is marked with a cross. The band between DESCRIPTION and the lockfile holds the transitive dependencies no analyst names directly, together with, in a compendium, the packages used only by analysis scripts. That second case is the archetype qualification discussed above: it is a violation in an R package and legitimate in a compendium.
The invariant can be checked by machine. The framework’s check-renv gate, backed by the zzrenvcheck package, scans all three sources and tests the two inclusions. It reports any violation: a package used in code but undeclared, or declared but unpinned. It can also repair a violation on request. It writes a missing declaration into DESCRIPTION through the desc package. For a package absent from the lockfile, it writes a record of the version installed in the analyst’s library, the version the code was actually run against. Only when the package is not installed at all does it fall back to the current CRAN version. It then prints a warning saying so, since that version may not be the one that produced any result. The repair does not call renv::snapshot() or install.packages(); it edits the two manifests as text. Two limits follow. First, the record it writes is minimal, a name, version, and source without the copied DESCRIPTION metadata. Second, it covers the missing package alone, not that package’s own dependencies. The repair is therefore a prompt to review, and a later renv::snapshot() remains the authoritative record of the library.
$ make check-renv
In the framework this book uses, this target runs the check with repair enabled before a commit. Outside the framework the same call is zzrenvcheck::check_packages(auto_fix = TRUE). Under continuous integration the check must run with repair disabled and must be able to fail the build:
When error_on_fail is true, a failed check stops with an error and Rscript exits with a nonzero status. That is what turns the job red. Current zzrenvcheck already defaults to error_on_fail = !interactive(), so a script or CI job fails while an interactive console only reports. Nevertheless, the CI call above passes the argument explicitly so that the gate does not depend on how R was started. We confirmed the failure on a scratch project whose code called dplyr without declaring it: the command above printed ‘Validation failed’ and exited with status 1. zzrenvcheck is not on CRAN, so the CI job installs it first. The gate tool is itself a dependency of the evidence it produces, so the job pins it to one commit rather than to whatever the default branch holds on the day of the run:
That commit is zzrenvcheck 0.10.0, the version whose behavior this section describes. A drift that escaped the developer’s machine therefore fails the build rather than being silently repaired. This forces the contributor to commit the fix instead of letting the clean build paper over it. The gate is a presence check. That is, it guarantees that the three sets nest, that nothing used is unpinned. It does not verify that the version floors in DESCRIPTION agree with the exact pins in the lockfile, which is a separate concern.
The gate is also archetype-aware. When it finds an analysis/ directory at the project root it enters compendium mode automatically (compendium = "auto" is the default). In that mode only packages used in R/ are required in DESCRIPTION, while packages used only in analysis/ or scripts/ need only appear in renv.lock. On an R-package project, which has no analysis/ directory, the strict double inclusion applies. Passing compendium = TRUE or compendium = FALSE overrides the auto-detection when the directory layout does not reflect the archetype.
6.5.1 Scanning the documentation, not only the code
The most common way for a dependency check to fail is subtle. It scans the analysis code, pronounces the project consistent, and overlooks a package that is used only in a vignette or in the rendered manuscript. That is exactly where a documentation build breaks on a fresh machine. zzrenvcheck deliberately scans more widely than a plain code scan on this point.
The scan does not look at .R scripts alone. It parses the literate and dynamic documents as well, R Markdown (.Rmd), Quarto (.qmd), and Sweave (.Rnw). A package loaded inside a report chunk or a vignette is thus seen just as one loaded in R/ is. Within every such file it recognizes each of the forms by which R code reaches for a package. These are the explicit library(pkg) and require(pkg), the namespaced pkg::function(), and the roxygen2 directives @import and @importFrom from which a package’s .Rd help files are generated. In its strict mode it widens the search beyond the analysis directories, into the tests/, vignettes/, and inst/ directories. It is correspondingly careful about what it ignores. README files and the example directories (man/examples, inst/examples) are skipped, since the install-and-demonstrate code they usually carry would otherwise raise false alarms. A separate pass reads the reproducibility files themselves, the Dockerfile, the Makefile, install.sh, and .Rprofile, for version-pinned installs such as pak('survival@3.5-8'). This pass catches a version fixed in the container recipe that has drifted from the lockfile.
Consider a manuscript compendium whose analysis in R/ restores cleanly from the lockfile. Its report, however, draws a forest plot with a plotting package that appears nowhere except the .qmd itself. A scanner that read only the code would certify the project as consistent. The report would then fail to render on the reviewer’s machine for want of an unpinned package. Because zzrenvcheck reads the document, the missing dependency is caught and pinned before it can break the build. The wider reach helps most with the scholarly manuscript and the blog, whose rendered outputs are the deliverable. Their package needs sit in documents, where a naive check does not look.
NoteCheck your understanding: what a code-only scan misses
A manuscript’s R/ directory restores cleanly from the lockfile, but its .qmd report loads a plotting package nowhere referenced in R/. Would a dependency check that scans only .R files catch the missing pin, and why does zzrenvcheck catch it where that scan would not?
NoteAnswer
No. A code-only scan sees only R/, finds every package it references already pinned, and certifies the project consistent while the report’s own dependency goes unseen. zzrenvcheck catches it because it also parses literate documents, .Rmd and .qmd among them, for library(), require(), and pkg::fun() calls. A package loaded only inside a report chunk is therefore scanned exactly as one loaded in R/ would be.
ImportantThe honest level
This chapter’s own practice, the check-renv gate and the lockfile it enforces, reaches L1 package-pinned and nothing further. It leaves the R version, the operating system, and the system libraries beneath the package layer entirely exposed.
6.5.2 The triad across archetypes
The lockfile discipline is identical across the archetypes of Chapter 5, because every archetype records its packages in the same renv.lock by the same snapshot and restore. What varies slightly is how natural the declared-dependency middle term feels. In the R-package archetype, DESCRIPTION is the package’s defining interface: R CMD check reads it, an installer reads it, and CRAN reads it. The triad is therefore especially natural there, since the declared set already exists for reasons independent of reproducibility. A data-analysis project, a manuscript compendium, a simulation study, and a blog also carry a DESCRIPTION. There, however, it declares only the API of the reusable code in R/. Their binding invariant is instead the single \(\mathrm{Code} \subseteq \mathrm{renv.lock}\). The check-renv gate applies that weaker rule automatically when it detects an analysis/ directory. A subtlety follows for the R-package archetype. A package used only by an analysis script or report belongs in Suggests rather than Imports. In that way R CMD check does not hard-require a package the package’s own exported functions never call.
NoteCheck your understanding: locating a drift
Continuous integration on an R-package archetype fails with the message that survival is used in R/model.R but is not declared in DESCRIPTION. Which inclusion of the triad has been violated, and what single command would most likely repair it?
NoteAnswer
The invariant is the composition of two atomic inclusions. The one violated here is the first, \(\mathrm{Code} \subseteq \mathrm{DESCRIPTION}\): the code references survival while DESCRIPTION does not declare it. This in turn leaves it unpinned in the lockfile. The transitive composition \(\mathrm{Code} \subseteq \mathrm{renv.lock}\) therefore fails as a consequence, but the atomic breach is at the code-to-DESCRIPTION step. The likely cause is that survival was installed interactively but never declared. Running make check-renv, which invokes zzrenvcheck::check_packages() with automatic repair, would write survival into DESCRIPTION through the desc package. It would also add a record of the installed survival version to renv.lock, restoring both inclusions. This edits the two manifests as text and is distinct from an renv::snapshot(), which would instead re-derive the lockfile from the installed library. The fix must then be committed so the clean CI build sees it.
6.6 Dated snapshots of a package repository
A lockfile records which versions to install. But a plain CRAN mirror will happily serve only whatever is current. Moreover, older source packages must often be recompiled, which is slow and can fail when a system library has since moved on. The Posit Package Manager resolves both problems by offering dated snapshots of CRAN. A snapshot URL freezes the repository as it stood on one calendar day. A request for a package then returns the version that was current on that date, and, on a platform the manager serves, returns it as a pre-compiled binary rather than as source to be built. On Linux that requires the URL form described below.
With repositories pointed at a dated snapshot, an install run today and the same install run next year draw from an identical, frozen catalog. The lockfile above records exactly this URL in its Repositories block, so that a restore reproduces both the versions and the source they came from. The gain is twofold. The first gain is fixity, because the catalog cannot drift, and the second is speed, because binaries install in seconds where source builds take minutes. On Linux the binary path is more specific. Pre-compiled binaries are served from a distribution-specific form of the URL, such as https://packagemanager.posit.co/cran/__linux__/noble/2026-06-29, and R may need to send its version in the HTTP user agent. The plain dated path shown above should be expected to deliver source to be built. In the framework this book uses, the project’s generated configuration points R at a dated snapshot automatically. The two benefits thus accrue without the analyst assembling the URL by hand. The date of the snapshot becomes, in effect, part of the environment’s identity. We take up this topic again when the container fixes a snapshot date at image-build time in Chapter 7.
NoteCheck your understanding: fixity versus speed
A colleague points their repos option at https://packagemanager.posit.co/cran/2026-06-29 and reports that installs are both faster and identical a year later. Are these the same benefit or two different ones, and what does each depend on?
NoteAnswer
Two different benefits. The speed comes from the snapshot serving a pre-compiled binary rather than source to be built. It depends on the platform-specific binary path being used (the distribution-codename form on Linux) and on a binary existing for that platform. The identical-a-year-later fixity comes from the date embedded in the URL freezing the catalog. It holds regardless of whether a binary or a source install is served. A snapshot with no binaries for a given platform still delivers the fixity without the speed.
6.7 The limits of renv
A lockfile is easy to overclaim, and the gap it leaves is the subject of the next chapter. But what, exactly, does a lockfile leave unpinned? renv pins the R packages. It does not pin the R interpreter itself, so a lockfile produced under R 4.6.0 may restore under R 4.2.1 with different results. It may also fail to restore at all when a recorded version requires a newer R. It does not pin the operating system, so a lockfile assembled on macOS carries no guarantee on Linux. And it does not pin the system libraries that many packages link against, the GDAL behind a spatial package or the libxml2 behind an XML parser. A restore on a machine lacking a required system library may therefore fail to compile a package or, more insidiously, may install a differently behaving one.
renv does its one job well, but the package layer is one layer of a taller stack. Pinning it leaves every layer beneath it as the next machine happens to provide. Ushey & Wickham (2026) designed renv to solve the package problem and no more; the environment problem is out of its scope by design. An analysis equipped with a faithful lockfile has reached L1, pinned packages, and every layer beneath the packages remains exposed. Closing that remaining gap is the work of the container, and it is where Chapter 7 begins.
NoteCheck your understanding: what a lockfile cannot promise
A lockfile produced under R 4.6.0 is restored on a colleague’s machine running R 4.2.1, and the restore succeeds without error. Does this mean the analysis will produce the same result on both machines?
NoteAnswer
Not necessarily. renv pins the package versions, not the R interpreter itself. A successful restore under a different R version means the packages installed, not that they behave identically under that R. The lockfile’s R block records which R version wrote it, but it neither installs nor enforces that version. When the project loads under a different minor release of R, renv prints a one-line notice naming both versions, and then proceeds under the R it was given. Closing this exposure is the work of the container in Chapter 7, which pins the R runtime along with the packages.
6.8 Lighter and alternative approaches
The lockfile-and-restore idiom is not the only way to pin the package layer. The reader should know the principal alternatives, because some suit particular settings better and because the tradeoffs illuminate what renv is doing.
The most important shift of idiom is from preserving a lockfile to reconstructing an environment from a date. The rang package of Chan & Schoch (2023) takes a set of packages and a target date, and resolves the versions that were current then. It reaches back through CRAN’s archive to reconstruct a historical environment, even for a project that never recorded a lockfile at all. Where renv requires foresight, a committed lockfile written while the analysis was live, rang offers hindsight, recovering an approximate environment after the fact. It is the natural instrument for a legacy analysis that one wishes to resurrect.
The groundhog package of Simonsohn (2026) pursues the same date-based idea but at a different point in the workflow. Rather than restoring a library before the script runs, it loads version-specific packages at run time. A groundhog.library() call carries a date, and the packages current on that date are loaded for that session. It needs no project library and no snapshot step. In effect, it trades renv’s explicit committed lockfile for a date-stamped call evaluated against the repository’s history. The cost of that convenience is that the pin now lives inside the script’s control flow rather than in a separate, inspectable manifest. A reviewer must read the code to discover it.
Finally, capsule(McBain, 2023) is best understood as a lazier discipline layered over renv itself. It defers building the project library until it is actually needed. The analyst develops against their ordinary user library and materializes the pinned library only when reproducing or checking the work. For analysts who find renv’s always-on project library intrusive during exploratory work, it lowers the friction of adoption while preserving the lockfile as the eventual source of truth.
Each of these approaches pins the package layer and only the package layer. Whether the pin is a committed lockfile, a reconstructed date, or a run-time call, none reaches down to the R version, the operating system, or the system libraries. The choice among them is a choice of ergonomics and of foresight versus hindsight, not a choice of how far down the determinant stack one has pinned.
NoteCheck your understanding: foresight or hindsight
A legacy analysis from four years ago never recorded a lockfile. Which of the three alternatives is suited to recovering an approximate environment for it now, and which two require the discipline to have been in place from the start?
NoteAnswer
rang is suited to the legacy case, because it reconstructs a past environment from a target date through CRAN’s archive, needing no prior lockfile at all. groundhog and capsule both require the discipline in place beforehand. groundhog needs the date-stamped groundhog.library() call written into the script at the time. capsule still layers over renv’s own snapshot, so without one there is nothing for it to materialize later.
6.9 Worked example
To make the package-churn failure mode concrete, and to generate a computed artifact at build time, we construct a small synthetic lockfile diff. That is, we compare two snapshots of the same project taken some months apart. This is the kind of table a version-control diff of renv.lock would summarize. Reading it is the routine skill of noticing which pins moved. The data are synthetic and no packages are installed; the computation uses only tibble, dplyr, and knitr.
Table 6.1: A synthetic lockfile diff between two snapshots of one project. The changed column flags every package whose pinned version moved between the earlier and later snapshot.
package
version_a
version_b
changed
dplyr
1.1.0
1.2.1
changed
ggplot2
3.4.4
3.4.4
tidyr
1.3.0
1.3.1
changed
survival
3.5-7
3.5-8
changed
lubridate
1.9.3
1.9.3
rlang
1.1.2
1.1.4
changed
Between the two snapshots, 4 of the 6 pins moved. Three of the moves are patch-level (tidyr, survival, and rlang), the kind that ordinarily preserve behavior but occasionally do not. One is a minor version bump (dplyr, from 1.1.0 to 1.2.1) of the sort that can refine a default. The rlang move, from 1.1.2 to 1.1.4, deserves attention despite its size because of its transitive position. Almost nothing calls rlang directly, yet almost everything depends on it, so the move happened beneath the whole stack. A diff of the lockfile is a reviewable record of this churn. Without a committed lockfile, none of these movements would be visible, and the analyst confronted with a changed result would have no way to see which package had shifted. The lockfile cannot stop packages from changing, but it makes the change legible and lets the analyst restore the earlier column deliberately.
NoteCheck your understanding: reading the diff
In Table 6.1, ggplot2’s version is identical in both snapshots and rlang’s moved by only a patch release, yet the chapter singles out rlang’s move as the more consequential one to notice. Why?
NoteAnswer
Because consequence tracks transitive position, not the size of the version jump. rlang sits beneath almost every other package in the tidyverse closure. A change to its behavior therefore propagates upward into everything that depends on it, even though almost nothing in the project’s own code calls rlang directly. A patch-level move in a package most analysts have never heard of can matter more than a minor-version move in a package they call by name every day.
6.10 The cohort’s own dependencies
In this section we apply the chapter’s method to the running cohort compendium. renv::dependencies() scans a file for the packages its code actually references and returns one row per package found. That is exactly the scan renv::snapshot() runs before writing a lockfile.
Table 6.2: Packages renv::dependencies() finds referenced in the two files that produce the running cohort, scanned directly rather than asserted. simulate_cohort.R contributes no rows because it calls base R functions (rnorm, sample, as.Date) without library() or a :: prefix, so the scan finds no package name to report.
Source
Package
cohort.R
parallel
cohort.R
stats
cohort.R
survival
cohort.R
tibble
cohort.R
utils
cohort.R
withr
R/cohort.R references parallel, stats, survival, tibble, utils, and withr. Of these, parallel, stats, and utils are base packages: they ship with every R installation, their version is the R version’s, and a lockfile records no entry for them. The counting rule for the rest is whether renv records the package in the lockfile. A recommended package such as survival also ships with the standard R binaries, but it is versioned and updated independently of R, so renv pins it like any other, and we count it as contributed. Under that rule the scan finds 3 contributed packages, survival, tibble, and withr. The code is locatable and its dependencies are known, from a real scan rather than from memory. Whether they are also pinned is a question for the lockfile. file.exists('renv.lock') at the project root is TRUE, and of the contributed packages the scan finds, the lockfile leaves 0 unrecorded. The package-versions layer is therefore pinned, and the cohort compendium has reached at least L1. For a compendium without a lockfile, renv::init(), which scans the code and writes the first lockfile, and a commit of that lockfile, is the single step that lifts it from L0 to L1, exactly as the orientation above describes for the hypothetical registry study.
NoteCheck your understanding: why no rows for the simulator
renv::dependencies() returns no row for analysis/scripts/simulate_cohort.R, even though that script is essential to the cohort and uses functions such as rnorm() and sample(). Is this a bug in the scan?
NoteAnswer
No. rnorm() lives in the stats package and sample() in the base package. Both, like utils, are base packages bundled with every R installation rather than contributed packages a lockfile needs to pin. The scan is working as intended. It reports the packages a file names, through library(), require(), or pkg::, and this script names none. A base package named that way would appear, as stats and utils do for R/cohort.R, but the lockfile would still record no entry for it.
6.11 Collaborating with an LLM
A language model is a capable assistant for the mechanics of renv. However, a fluent, plausible-looking lockfile instruction can pin the wrong thing or nothing at all. Each of the following triples pairs a useful prompt with what the analyst must watch for and verify.
ImportantRestricted data
One rule comes first (habit 3). Never paste or upload protected health information, identifiable records, or data held under a data use agreement, nor outputs derived from them, into a model or a coding agent unless three conditions all hold. The institution has approved that endpoint for that class of data. The IRB protocol and the consent permit the processing. The data use agreement, or the provider’s terms, permits it. If any of the three is unclear, the answer is no.
The third condition is the one most often missed. Institutional approval of a tool does not override the terms under which a data provider released the data. NIH, for example, treats sharing controlled-access data through prompts with public generative AI tools, which it glosses as third-party tools, as a breach of the data use certification. It treats a model trained on such data as a data derivative, to be shared only with other approved users and not kept after the project closes (National Institutes of Health, 2025).
Describe the structure instead: the column names and types, or a small synthetic example generated from the data dictionary, never edited from real rows. A coding agent sees whatever files are in its working tree, so run it in a checkout or container where the real data is not mounted.
An agent also acts, so confine it to a branch and keep merges, pushes, and deposits for yourself (Section 2.10.1).
Dependency questions rarely need data at all.
Prompt. ‘My collaborator cloned our project and the packages are missing. Write the R command they should run.’
Verification. Confirm that the suggested command reads the lockfile rather than writing it, and that after running it the installed versions match the lockfile. Run the check gate and confirm the triad holds.
With a coding agent the suggestion becomes an action. An agent that runs renv::snapshot() in a fresh clone can overwrite the lockfile with the state of whatever library it finds there. Treat renv.lock as a protected path: read its diff line by line before any commit that touches it, and keep the decision to change it with the analyst (Section 2.10.1).
Prompt. ‘Explain why my renv.lock includes roxygen2 and tinytest when my analysis never calls them, and whether I should remove them.’
Watch for. Check for a flat assertion that any unused package should be purged, which misses the deliberate convention by which test infrastructure is pinned while pure development tooling is not. The distinction is a judgment, not a rule the model can read off the file.
Verification. Decide the placement yourself against the two-test procedure: does the package’s version affect the result, and does the code reference it? Confirm that development-only tools such as languageserver are in the Dockerfile and absent from the lockfile, and that test packages are handled by your stated convention.
Prompt. ‘Set my repository to a dated Posit Package Manager snapshot for 2026-06-29.’
Watch for. Check the URL for the wrong path structure, an implausible date, or a mirror that does not offer binaries for the analyst’s platform. Check also for a Linux distribution codename assumed without comment that does not match the analyst’s system.
Verification. Check the constructed URL against the Posit Package Manager documentation, confirm the date is the one you intend, and confirm that an install actually draws binaries rather than falling back to source. The recorded URL should then appear in the lockfile’s Repositories block.
A better prompt. ‘My analysis runs on Ubuntu 24.04 (codename noble) with the R version recorded in the attached renv.lock. Write the options(repos = ...) call that points at the Posit Package Manager CRAN snapshot dated 2026-06-29, in the form that serves Linux binaries for that codename. Change no package version. Tell me how to confirm that an install draws a binary rather than building from source.’
6.12 Exercises
Initialize renv in a throwaway project, install two packages, and snapshot. Open renv.lock in a text editor and locate, for one package, its Version, its Source and Repository, and its Imports. Explain in a sentence what each tells a later restore, and name one thing the record does not let a restore check. Report the renv version you used, since the lockfile format changed in renv 1.1.0.
With the project of Exercise 1, upgrade one package to a newer version, snapshot again, and inspect the diff of renv.lock under version control. Which fields changed, and which stayed fixed? Relate the diff to the synthetic table of Table 6.1.
Deliberately break the dependency triad: add a library() call for a package you have not declared or pinned. Run the project’s dependency check and record which inclusion it reports as violated and how it repairs the violation. Then remove the call and confirm the check passes.
Point your repository at a dated Posit Package Manager snapshot and reinstall one package. Time the install, then compare it with an install of the same package from source. Report the difference and explain, in terms of binaries versus source, why it arises.
Take a small analysis that has no lockfile and use rang to reconstruct the package environment as it stood on a chosen past date. Compare the resulting version set with what a current install.packages() would provide. Which packages differ, and by how much?
Argue, in a short paragraph, why an analysis that passes its dependency check has reached L1 and not L2. Name one concrete determinant that a lockfile leaves unpinned and describe a plausible way it could change a result across two machines.
Run renv::dependencies() on R/cohort.R and analysis/scripts/simulate_cohort.R from the running cohort compendium, as Table 6.2 does. Report the number of distinct contributed (non-base) packages the scan finds and name them, counting a recommended package such as survival as contributed because renv pins it, and treating a package as base when installed.packages(priority = 'base') lists it. Then explain, from the scan alone and without reading simulate_cohort.R, why that file is permitted to contribute zero rows.
This exercise returns to the version-control chapter’s discipline of distinguishing what must be committed from what must never be. renv::init() writes an renv/ directory containing activate.R, a settings.json, and (once packages are installed) a library/ subdirectory holding the actual installed package files. State which of these renv itself places in a generated .gitignore, and explain why committing the library/ subdirectory would defeat the purpose of the lockfile rather than merely waste space.
6.13 Solutions
Attempt an exercise before expanding its solution. Two of the eight have no single correct answer, because what they report depends on the machine and the date. For those the box says what a good answer establishes rather than supplying a number. Exercise 7 does have a checkable numeric answer, run against the extract as committed.
NoteExercise 1
The answer below assumes renv 1.1.0 or later. With renv 1.2.3, the version used for this chapter, a snapshot writes records in the format excerpted in the chapter. The fields answer different questions a later restore has to settle.
The version is recorded exactly, 1.2.1 and not >= 1.2, so a restore installs the release the analysis actually used and has no latitude to drift upward. This is the field that defends against the ordinary failure, in which a package acquires a new default between the original run and the rerun.
The source names where the package came from: CRAN, a Posit Package Manager mirror, Bioconductor, or a specific GitHub commit. It matters because the same version number can denote different code on different repositories, so the version alone does not identify the package. Note that the Repository value is the registered name of the repository rather than its URL. That is why a lockfile can record CRAN while the corresponding entry in the Repositories block points at a Posit mirror.
The Imports list is copied from the package’s own DESCRIPTION. It tells a reader which other packages this one needs, with the version floors its authors declared, such as rlang (>= 1.1.7). It is not itself a pin: each of those dependencies is pinned by the exact Version in its own record elsewhere in the file.
What the record does not let a restore check is whether the files it installs are the files that were installed before. There is no checksum of the package contents. A reader working from an older tutorial may expect a Hash field. renv before 1.1.0 wrote one, but it was a fingerprint of DESCRIPTION fields used to key the package cache, never a hash of the installed files. Current renv does not write it.
A useful way to hold the fields together: the version says which release, the source says whose copy of it, and the copied metadata says what that release declared about itself. None of them says whether the bytes match.
NoteExercise 2
For the upgraded package, Version changes, and so does any field copied from DESCRIPTION that the new release altered: commonly Imports and its version floors, the RoxygenNote, and the author or maintainer fields. A diff of one upgrade can therefore show many changed lines for a single moved pin. The line to look for first is Version. Package, Source, and Repository stay fixed, since the package is the same package drawn from the same place. A reader whose lockfile shows a Hash field moving alongside the version is running renv older than 1.1.0, which wrote the older format.
Two further effects in the diff are easy to miss on a first reading. If the upgraded package gained a dependency, new package entries appear in the lockfile that the reader never installed by name. This is because the lockfile captures the full transitive closure rather than the packages the reader asked for. And the R block at the top of the file is untouched. It records the R version under which the snapshot ran, but it does not install or enforce that version (Exercise 6), and upgrading a package does not change it.
The relation to Table 6.1 is that the table shows the same structure in synthetic form. Each row is a package, the earlier and later columns hold the pinned versions, and the flag marks where they differ. A real git diff renv.lock is that table expressed as JSON, with the additional detail that the copied DESCRIPTION metadata moves with the version.
NoteExercise 3
The violated inclusion is the first atomic one, \(\mathrm{Code} \subseteq \mathrm{DESCRIPTION}\). The code now references a package that DESCRIPTION does not declare. This in turn leaves it unpinned in the lockfile, so the transitive composition \(\mathrm{Code} \subseteq \mathrm{renv.lock}\) fails as a consequence. The breach to report is the atomic one, not the consequence.
Running make check-renv invokes zzrenvcheck::check_packages() with automatic repair. It writes the package into DESCRIPTION through the desc package and adds a record of its installed version to renv.lock, restoring both inclusions. If the package is not installed, the repair records the current CRAN version instead and warns that it has done so. The honest response to that warning is to install the package, rerun the analysis, and repair again. This edits the two manifests as text and is deliberately distinct from an renv::snapshot(), which would instead re-derive the whole lockfile from whatever is currently installed.
Removing the library() call and re-running the check does make the check pass. However, it does not return the manifests to their prior state: the repair already wrote the package into DESCRIPTION and the lockfile, and nothing removes it. A passing check means the inclusions hold, not that the project is unchanged. Restoring the prior state requires deleting the entries by hand or discarding the changes under version control, which is itself a small argument for making the repair on a branch.
NoteExercise 4
This exercise has no single correct answer, because the times depend on the package, the machine, and the network. What a good answer establishes is the mechanism, and it should report both timings and name the package.
The expected result is that the snapshot install is substantially faster. The explanation is that Posit Package Manager serves a prebuilt binary for the declared platform. Installing a binary is unpacking an archive; installing from source is compiling it. For a package carrying compiled code, typically anything depending on Rcpp, the difference is commonly an order of magnitude or more.
The instructive case is the one that does not show a large difference. A pure-R package has little to compile, so the two paths do similar work and the timings converge. A reader who happens to pick such a package and reports a small difference has the right finding, provided they identify why. Two other conditions can flatten the difference and are worth checking before concluding anything. First, the renv cache may already hold the package, in which case neither install does real work. Second, PPM does not serve binaries for every platform, so a machine whose platform is unserved falls back to source in both arms.
NoteExercise 5
This exercise also has no single correct answer, since what differs depends on the date chosen and on the size of the dependency tree. A good answer reports the count of differing packages, gives one or two concrete version pairs, and draws the general conclusion.
The general conclusion is that rang reconstructs what was current on a date, which is not the same thing as what an analysis actually used. The two coincide only if the original analyst installed everything on that date and never updated anything afterward. That is not how most projects proceed. Reconstruction by date is therefore an approximation, and a lockfile is a record; the approximation is what one falls back on when the record does not exist.
The number of differing packages will generally grow with the age of the date and with the depth of the dependency tree, since a difference anywhere in the transitive closure counts. A package whose version happens to be unchanged is not evidence that the reconstruction succeeded, only that that particular package was quiet over the interval.
NoteExercise 6
A passing dependency check establishes that the triad holds: every package the code uses is declared, and every declared package is pinned in the lockfile. That is exactly the L1 property, pinned packages, and the check is the evidence for it.
It is not L2, because the lockfile pins packages and nothing beneath them. The R version is recorded in the lockfile but not supplied by it. The operating system, the system libraries, the locale, the time zone, and the numerical libraries are all outside its scope. L2 requires an artifact that fixes the operating system, the R runtime, and the system libraries, which is what Chapter 7 is about. Even L2 does not guarantee the numerical libraries: an image determines which BLAS is installed, but the thread count and the CPU still vary.
For a concrete unpinned determinant, the numerical-library layer is the cleanest example of what a lockfile misses, though no rung of the ladder fixes it completely. Two machines can hold identical pinned package sets and still link against different BLAS implementations, reference BLAS on one and Apple’s Accelerate or Intel MKL on the other. Because these reorder the floating-point summations inside a matrix decomposition, a principal-components analysis or a mixed-model fit can return results that agree to several decimal places and differ in the last. A sign flip on a component can make the difference visible in a plot. The lockfile is silent on all of it, and setting a seed does not help, because the difference is not stochastic.
A second acceptable answer names the locale. Two machines under different collation orders sort character vectors differently. This changes which row is taken first in a tie and can therefore change a reported result through a slice() or a first(), with no error raised anywhere.
NoteExercise 7
The solution for this exercise is in the instructor guide, which is distributed separately to course instructors. Self-study readers who want to check their answer can compare the autogradable values against those reported in the chapter’s own ‘The cohort’s own dependencies’ section.
NoteExercise 8
renv::init() writes a generated .gitignore inside renv/. Under renv 1.2.3’s default settings it excludes library/, local/ (local package sources), cellar/, lock/, python/, sandbox/, and staging/. It leaves renv/activate.R and renv/settings.json to be committed, along with the lockfile renv.lock at the project root. The rule follows the same line the version-control chapter draws between what must be committed and what must never be. Here it is applied to a different kind of large, regenerable, and machine-specific content rather than to restricted data.
Committing library/ would not merely waste space; it would defeat the lockfile’s purpose outright. renv.lock exists to be a small, portable, human-readable description from which the library can be rebuilt on any machine. If the library itself were committed, a collaborator on a different operating system or architecture would receive compiled binaries built for someone else’s platform. Because their versions match the lockfile, renv::restore() would likely treat them as already installed, and a package with compiled code would then fail when it loads. Moreover, the repository would grow by orders of magnitude for content that renv::restore() already knows how to regenerate from the one file that actually matters.
The CI form: checks only, and fails the build on a violation.
options(repos = c(CRAN = '.../cran/YYYY-MM-DD'))
Points installs at a dated, fixed snapshot of the repository.
Rule of thumb
A lockfile pins the package layer and nothing beneath it; L1, not L2.
Rule of thumb
An oracle, a declared dependency, or a pinned version must come from outside the thing it checks; a lockfile is no exception for file integrity.
Habit 3
Never let restricted data reach an unapproved model endpoint, even to ask a dependency question.
6.15 Further reading
The authoritative reference for the tool is Ushey & Wickham (2026), the package documentation for renv. Its introductory and collaboration vignettes are the fastest route to fluent daily use, and its treatment of the cache and of custom repositories repays study once the basics are in hand. The glossary entry renv and packrat summarizes the relationship of renv to its predecessor.
For the date-based alternatives, Chan & Schoch (2023) presents rang and its strategy of reconstructing a historical environment from CRAN’s archive. It gives a clear account of the cases where hindsight succeeds and where it cannot. Simonsohn (2026) documents groundhog and its run-time, date-stamped loading model, and McBain (2023) describes the lazy discipline that capsule layers over renv. Reading the three together clarifies that pinning the package layer admits several idioms with different demands on foresight.
On the discipline of where a package belongs, the placement whitepaper accompanying the framework develops the two-test decision procedure and the two-layer model that this chapter summarizes. It is the place to turn when a package sits awkwardly between the lockfile and the Dockerfile. Finally, the boundary this chapter insists on, that the lockfile pins the packages and nothing beneath them, is taken up directly in Chapter 7. There the container fixes the R version, the operating system, and the system libraries that renv by design does not.