Skip to main content

Preface

Who this book is for

This book is for physicists who already work with data: researchers, postdocs and graduate students, in the lab, at the telescope or on the cluster, and the many astrophysicists who learned some Fortran long ago. It is the third of three related works. My orbitr package (https://orbit-r.com) is software for N-body simulation, with its own book, Orbital Mechanics with R. R for Physics (https://rforphysics.daverosenman.com) is my introduction to R for undergraduates. This book picks up where R for Physics stops.

It is written for professionals, and it tries to respect your time. It assumes you know your statistics, your numerical methods and your instruments, and that you have met R at the level of R for Physics: vectors, data frames, functions, a first filter() and a first ggplot(). It does not teach those again. When a chapter leans on something basic, it names it and points to where it is taught.

What this book teaches

This book teaches three things. The first is a way of working with physics data in R, the tidyverse way, in which a table holds one observation per row and a short chain of verbs turns raw measurements into a result. The second is how data compression works, from Shannon’s entropy through Huffman coding to the codecs inside every modern file format, because you cannot handle big data sensibly without knowing what makes a file small. The third is how to store and analyse data too large for your computer’s memory with the same verbs you use on a small table, through the arrow and duckdb packages. All three end in the same place: a correct result and a figure worth publishing.

What you will learn

Every analysis in this book follows the same path.

flowchart LR
  A[Import] --> B[Tidy]
  B --> C[Transform]
  C <--> D[Visualize]
  C --> E[Store]
  E --> F[Scale]
  F --> C
  D --> G[Communicate]

flowchart LR
  A[Import] --> B[Tidy]
  B --> C[Transform]
  C <--> D[Visualize]
  C --> E[Store]
  E --> F[Scale]
  F --> C
  D --> G[Communicate]

You import data from a file, often a compressed one. You tidy it, so each row is one observation and each column one variable. You transform it: select the events you want, compute new quantities like an invariant mass, and summarise. You visualize it, and the figure sends you back to transform something else; most analyses loop between these two many times. When the data is worth keeping, you store it in a format that is compact, fast and readable for decades. When it is too big for memory, you scale the same transformations out to files on disk. Finally you communicate: a figure, a table, a paper.

How this book is organized

Part I, the whole game, runs through that entire path in one chapter (1  The whole game), then covers the two ideas the rest of the book stands on: tidy data (2  Tidy data) and the move from writing loops to describing results, told for readers who know some Fortran (3  From Fortran to the tidyverse).

Part II, information and compression, starts from entropy (4  Entropy and the limits of compression) and works through the algorithms that have lasted: Huffman coding (5  Huffman coding), the Lempel–Ziv family (6  Dictionaries: LZ77, LZ78 and LZW), DEFLATE and gzip (7  DEFLATE: gzip and zlib), bzip2 and the Burrows–Wheeler transform (8  bzip2 and the Burrows–Wheeler transform), LZMA and xz (9  LZMA and xz), and the modern codecs Zstandard, LZ4, Snappy and Brotli (10  Zstandard, LZ4, Snappy and Brotli). Each chapter explains the idea, builds a small version in R so you can see it work, and then uses the real thing.

Part III, big data the tidyverse way, starts with what data costs in memory (11  What data costs in memory), then moves outward: R’s own file formats (12  R’s own formats: CSV and RDS), Parquet (13  Parquet: columns that compress), Arrow datasets bigger than memory (14  Arrow datasets: dplyr on data bigger than memory), and DuckDB (15  DuckDB: a database without the database).

Part IV, physics that lasts, is the payoff: figures worth publishing (16  Figures worth publishing), a complete analysis from a compressed file to a measured resonance (17  A complete analysis), and the habits that let someone rerun your analysis in ten years (18  Work that lasts).

What you won’t learn

This is not a statistics book, a numerical-methods book or a machine-learning book. Fitting appears only where an analysis needs it. It does not teach C++, although Advanced R has a good chapter on speeding up R with it (Wickham 2019). It covers the physics-specific formats ROOT and HDF5 only in passing; Parquet and Arrow are the bridge between R, Python and the rest, and a file you write in this book opens in pandas, polars or pyarrow without conversion.

It is also not a first book on R. If you have not used R before, R for Physics (https://rforphysics.daverosenman.com) will get you to the starting line in an afternoon or two, and the first chapters of R for Data Science (Wickham et al. 2023) go further.

Prerequisites

You need R 4.5 or later. Version 4.1 introduced the native pipe |> used throughout, and version 4.5 added Zstandard compression to base R, which Part II uses. You also need an editor that runs R; RStudio and Positron are both free.

The book uses few packages, on purpose. Every dependency is a promise someone else has to keep, so each one below earns its place.

Package What it does in this book Why it earns its place
tidyverse dplyr, tidyr, readr, purrr, ggplot2, tibble and friends: the verbs of every chapter The most widely used set of data tools in R, with explicit lifecycle stages for every function
arrow Parquet and Arrow files, and datasets bigger than memory The R interface to Apache Arrow, an open standard implemented in about a dozen languages
duckdb An analytical database that runs inside R, with no server dplyr code becomes SQL automatically, so you never have to write it
orbitr N-body simulation, as a source of simulation output in 13  Parquet: columns that compress and 16  Figures worth publishing My own package; a tidy simulation engine whose output is an ordinary table
lobstr Measuring memory, in 11  What data costs in memory only Small, and the tool Advanced R uses for the same job
renv Recording the exact package versions an analysis used, in 18  Work that lasts The standard way to make an R project reproducible

The broom and dbplyr packages also appear; both are installed with the tidyverse. Install everything with:

install.packages(c("tidyverse", "arrow", "duckdb", "orbitr", "lobstr", "renv"))

The data

Three data sets appear throughout. All three are simulated from simple physical models with realistic noise, so they behave like real data while being small enough to download in seconds and free to share. They are not real measurements, and the detector, the magnetometer station and the star cluster they describe do not exist. The script that makes them, data-raw/make_data.R in the book’s repository, is short and worth reading once you have finished Part I.

  • dimuon.csv.gz: 119,528 pairs of muons recorded by a collider detector, one row per pair, with each muon’s transverse momentum, direction and charge. Somewhere inside are the J/ψ, the ψ(2S), the three Υ states and the Z boson.
  • magnetometer.csv.gz: one day of readings from a three-axis fluxgate magnetometer, once a second, in nanotesla. A sudden impulse from the solar wind arrives in the afternoon.
  • stars.csv.gz: a catalog of about 85,000 stars within 300 parsecs, in the style of the Gaia mission’s catalogs, with positions, parallaxes, magnitudes and colours. An open cluster is hiding in it.

The files are compressed with gzip, which is one of the subjects of the book. Download them from the book’s data folder into a folder called data inside your project, or in R:

dir.create("data", showWarnings = FALSE)
base <- "https://raw.githubusercontent.com/DRosenman/advanced-r-for-physics/main/data/"
for (f in c("dimuon.csv.gz", "magnetometer.csv.gz", "stars.csv.gz")) {
  download.file(paste0(base, f), file.path("data", f), mode = "wb")
}

A fourth source of data is made on the spot: a simulation of the solar system with orbitr, the kind of output every computational physicist has to store, in 13  Parquet: columns that compress and again in 16  Figures worth publishing.

Several chapters also write files of their own. They put them in a folder called scratch, which you can delete at any time.

Running the code

Code appears in shaded blocks with its output directly below, prefixed by #>. Every number and every figure in this book was produced by the code beside it when the book was built, so if you run the same code you will get the same result, except for timings, which depend on your computer. Each chapter begins with a short Prerequisites section that loads the packages it uses.

When it matters which package a function comes from, the book writes it as package::function(), for example arrow::read_parquet(). The code follows the tidyverse style guide (Wickham, n.d.): names in snake_case that end in their units (mass_gev, field_nt, energy_kev), one verb per line in a pipeline, and spaces around operators. Code written that way is easier for the next person to read, and the next person is usually you.

Acknowledgements

This book stands on the work of many people: the R Core Team, who have kept R stable and growing for a quarter of a century; Hadley Wickham and the tidyverse team, whose books gave this one its shape; the Apache Arrow and DuckDB communities; and the people who invented the algorithms in Part II, most of whom gave them away.

Colophon

This book was built with Quarto and R, using these versions of the packages it depends on:

#> R version 4.6.1 (2026-06-24 ucrt)
#> dplyr   1.2.1
#> tidyr   1.3.2
#> readr   2.2.0
#> purrr   1.2.2
#> ggplot2 4.0.3
#> tibble  3.3.1
#> arrow   26.0.1.1
#> duckdb  2.0.1
#> dbplyr  2.6.0
#> orbitr  1.0.0
#> lobstr  1.2.2
#> broom   1.0.13