library(tidyverse)
library(arrow)18 Work that lasts
18.1 Introduction
Physics data outlives the people who take it. Astronomers still measure photographic plates exposed more than a century ago, particle physicists return to the data of experiments that shut down decades ago, and every new theory sends someone back to an old measurement to check it. The question for every analysis is not only “is it right?” but “could someone, perhaps you, rerun it in ten years and get the same answer?”
Most of the answer has nothing to do with clever software. It is a handful of habits, and this book has been practising them all along. This last chapter collects them in one place: keep raw data untouched, write the analysis as code from raw data to final figure, record the software versions, store data in formats that will still open, and build on tools that are designed to last.
Prerequisites
18.2 A layout for an analysis
Give every analysis its own folder, laid out so that anyone can see where things are and what depends on what:
upsilon-resolution/
README.md what this is, and how to run it
data-raw/ the data exactly as received; never edited
data/ data made from data-raw by code; can be deleted and rebuilt
R/ functions used by the analysis
analysis.qmd the analysis: narrative, code and results in one document
renv.lock the exact package versions the analysis used
The rule that matters is the direction of the arrows. Code reads data-raw/ and writes data/, figures and reports; nothing ever writes to data-raw/. Anything outside data-raw/ can be deleted and regenerated by running the code. This book follows the same layout: data-raw/make_data.R makes the files in data/, and every number in every chapter is regenerated when the book is built.
18.3 Raw data is sacred
Never edit raw data by hand, not even to fix an obvious typo. Fix it in code, where the correction is visible, explained and reversible. It helps to make the raw files read-only, which Sys.chmod() can do from R.
A checksum proves that a file has not changed. A cryptographic hash such as SHA-256 summarises a file in 64 hexadecimal digits; change a single bit of the file and the hash changes completely. Base R has computed MD5 checksums with tools::md5sum() for many years, and since R 4.5 it computes SHA-256 with tools::sha256sum(). Record them in a manifest when the data arrive:
manifest <- tibble(
file = list.files("data", full.names = TRUE),
bytes = file.size(file),
sha256 = unname(tools::sha256sum(file))
)
manifest
#> # A tibble: 3 × 3
#> file bytes sha256
#> <chr> <dbl> <chr>
#> 1 data/dimuon.csv.gz 2530077 2cb1988b28f3d03c7b2425565c34b8a06b655c22…
#> 2 data/magnetometer.csv.gz 603494 aa81b7d6d7bd15aff0a03de9799c4bcd4eeb7433…
#> 3 data/stars.csv.gz 1960814 d918534df7a4b07e179315c13f224812b3d01a4a…dir.create("scratch", showWarnings = FALSE)
write_csv(manifest, "scratch/MANIFEST.csv")Years later, recompute the hashes and compare. If every one matches, you are analysing exactly the data you think you are:
recorded <- read_csv("scratch/MANIFEST.csv", col_types = "cdc")
all(tools::sha256sum(recorded$file) == recorded$sha256)
#> [1] TRUE18.4 Analyses as documents
An analysis that lives in a document mixing prose, code and results cannot drift out of step with itself. Quarto (https://quarto.org) is such a system: you write text and code chunks in a .qmd file, and rendering it runs every chunk and weaves the results, numbers, tables and figures, into a finished report. This book is a Quarto book, and every number in it came from the code beside it. A minimal analysis looks like this:
---
title: "Mass resolution from the Upsilon states"
author: "A. Physicist"
format: html
---
```{r}
library(tidyverse)
library(arrow)
events <- open_dataset("data/events")
barrel_res <- 0.0079 # in a real analysis, the result of a fit
```
The barrel resolution is `{r} 100 * barrel_res`%.The inline expression in the last line means the number in the sentence is computed, not typed. When the data or the method change, re-rendering updates every number and figure at once, and a referee’s request becomes an edit and a re-render rather than an afternoon of copying values by hand.
18.5 Pinning package versions
Packages change. A function gains an argument, a default changes, a bug is fixed and an old result moves in its last digit. To rerun an analysis exactly, you need the versions it used. The renv package records them. In a project folder:
renv::init() # once: give the project its own package library and a lockfile
renv::snapshot() # after installing or updating packages: record the versions
renv::restore() # on another computer, or years later: install those versionsThe lockfile, renv.lock, is a small text file that lists the R version and every package with its exact version and where it came from. Commit it alongside the code. renv cannot promise that a package version from today will compile on a computer from 2040, so for the longest horizons record the R version and the operating system too, and consider a container image as well. But for the years that matter most, a lockfile and the packages’ own stability go a long way.
At minimum, end every report with a record of the session that produced it. sessionInfo() lists the R version, the platform and the version of every loaded package, and costs one line.
18.6 Formats that last
Everything in Part III comes down to a few rules.
- Archive tables as gzip-compressed CSV, Parquet, or both. CSV is readable by anything, forever, and exact for numbers written at their measured precision (Chapter 12). Parquet is typed, compact, fast and an open standard with many independent implementations (Chapter 13).
- Write down what the numbers mean. A column name with a unit helps (
field_nt), but a short README describing every column, its unit and its precision helps more. Parquet files can carry that description inside them as key-value metadata, which arrow writes and reads:
magnetometer <- read_csv("data/magnetometer.csv.gz", show_col_types = FALSE)
described <- arrow_table(magnetometer)
described$metadata$instrument <- "three-axis fluxgate magnetometer (simulated)"
described$metadata$units <- "time: UTC; bx_nt, by_nt, bz_nt: nanotesla"
described$metadata$resolution <- "0.01 nT"
write_parquet(described, "scratch/magnetometer.parquet")
read_parquet("scratch/magnetometer.parquet", as_data_frame = FALSE)$metadata[
c("instrument", "units", "resolution")
]
#> $instrument
#> [1] "three-axis fluxgate magnetometer (simulated)"
#>
#> $units
#> [1] "time: UTC; bx_nt, by_nt, bz_nt: nanotesla"
#>
#> $resolution
#> [1] "0.01 nT"- Keep R’s own formats for R’s own objects. RDS files are the right home for fitted models and intermediate results, but not for data you mean to keep, since only R reads them (Chapter 12).
- In astronomy, use FITS for images. FITS was defined in 1981 (Wells et al. 1981) and files from that year still open today. Its rule, “once FITS, always FITS”, is the archival attitude this whole chapter is about: the standard may grow, but no change may ever break an existing file (NASA FITS Support Office, n.d.; IAU FITS Working Group 2018).
- Avoid formats that need one company’s software to open. A file is only as durable as the least durable thing needed to read it.
18.7 Tools that last
The tools you build on are part of the archive too. A few principles have guided every choice in this book.
- Prefer base R and stable functions. The tidyverse marks every function with a lifecycle stage: stable, experimental, superseded or deprecated (Posit Software, n.d.). The help page for a function shows its stage when it is anything other than stable. Build on stable functions. Superseded functions, like
gather()andspread(), keep working but get no new features; deprecated ones warn you before they go away. - Read the warnings. When arrow tells you that
write_feather()has been superseded bywrite_ipc_file(), or ggplot2 tells you to uselinewidthinstead ofsizefor lines, that is a tool that cares about stability telling you how to keep your code working. - Keep dependencies few, and know why each one is there. The Preface’s table of packages is that reasoning for this book. Every package you depend on is a promise someone else has to keep.
- Use what is built into R. The native pipe
|>needs no package. Base R’smemCompress(),gzfile(),saveRDS()andtools::sha256sum()will be there as long as R is.
R itself is the best argument for this approach. Its core has been maintained conservatively for a quarter of a century, it descends from a language designed at Bell Labs in the 1970s (Chambers 2020), and code written for it long ago still runs. Physicists who build on it are building on something meant to last.
18.8 A checklist
Before you call an analysis finished, check that:
- the raw data are untouched, read-only and listed in a manifest with checksums;
- one command, or one render, goes from raw data to every number and figure;
- the package versions are recorded in a lockfile, and the report ends with
sessionInfo(); - the data you keep are in CSV, Parquet or FITS, with a description of every column, its unit and its precision;
- the code uses stable functions and runs without deprecation warnings;
- a README says what the project is and how to run it.
None of these takes long. Together they are the difference between a result and a result someone can trust in ten years.
18.9 Summary
Work lasts when its raw data are untouched and verified with checksums, its analysis runs from raw data to figures as code, ideally in a Quarto document, its package versions are pinned with renv, its data are stored in open formats with their meaning written down, and its tools are chosen for stability. Each habit is small, and the book has practised all of them. The physics is the point, and these habits are what let the physics be checked, extended and believed long after the analysis is done.
18.10 Exercises
- Change one byte of a copy of
data/stars.csv.gz(read it withreadBin(), modify one element, write it back withwriteBin()) and compare its SHA-256 hash with the original’s. How many of the 64 hex digits changed? - Turn the analysis of Chapter 17 into a Quarto document that reports the fitted resolutions with inline code. Render it, change the bin width, and render again.
- Write a README for the magnetometer data: one line per column with its unit and precision, plus how the data were made. What would someone need to know in ten years that the file itself does not say?
- Run
renv::init()in a new project that uses only the tidyverse and arrow, then openrenv.lockin a text editor. What does it record for each package? - Look up the lifecycle stage of five functions you have used in this book with
?(for examplepivot_longer(),summarise(),map_dfr(),write_feather()andcoord_flip()). Which are stable, and what replaces the ones that are not?