Skip to main content

Advanced R for Physics

Tidy Data, Compression, and Tools That Last

Author

Dave Rosenman

Welcome

Advanced R for Physics hex logo: an electron-positron pair spiralling out of one point, as in a bubble chamber, behind a teal R

Physicists have always had to program. FORTRAN, the first widely used high-level programming language, was built at IBM in the 1950s so that scientists and engineers could write down their formulas instead of hand-coding machine instructions (Backus et al. 1957). Its name comes from the formula translating system it was designed to be. Physicists have been programming ever since, in Fortran and then in C, C++, IDL, MATLAB, Python and R: simulations, detector readout, telescope pipelines, fits, and the figures that end up in papers.

Most of those physicists never set out to become computer scientists. They wanted the number at the end, its uncertainty, and a figure that shows both honestly. Many astrophysicists can still write a working Fortran DO loop and would rather not learn a new way of thinking just to read a big file.

This book is for them: serious physicists, researchers, postdocs and graduate students, experimentalists and theorists, who want to do physics with data in R without first becoming software engineers.

Where this book sits

This is one of three related works of mine.

  • orbitr is my software: a tidy N-body simulation engine for R, documented at https://orbit-r.com, with its own book, Orbital Mechanics with R (https://book.orbit-r.com).
  • R for Physics (https://rforphysics.daverosenman.com) is my introduction to R for undergraduates: vectors, data frames, functions, first steps with dplyr and ggplot2, and fitting lab data.
  • Advanced R for Physics, this book, is for working physicists. It assumes physics maturity (statistics, numerical methods, real instruments and real pipelines) and the R of R for Physics, and it does not teach either again. If you are new to R, read R for Physics first; this book picks up where it stops.

Say what you want, not how to loop over it

The tidyverse is a family of R packages that share one design philosophy (Wickham et al. 2019), and for a physicist two ideas in it matter most. The first is simplicity: a small number of pieces that fit together, each doing one job well. Its verbs are plain English. filter() keeps rows, mutate() adds columns, group_by() and summarise() collapse groups of rows into one row each. The second is abstraction: you describe the result you want, and the software works out the loop.

Here is a complete analysis step. Keep the muon pairs heavier than 60 GeV, group them by run, and find the mean mass in each run:

events |>
  filter(mass_gev > 60) |>
  group_by(run) |>
  summarise(mean_mass_gev = mean(mass_gev))

There are no index variables, no array bounds, no counters to reset and no temporary arrays, and each line reads as a sentence. In Fortran the same step takes nested loops and a page of bookkeeping. 3  From Fortran to the tidyverse puts the two side by side.

The same four lines run unchanged on a table in memory, on a folder of compressed Parquet files far bigger than your computer’s memory (14  Arrow datasets: dplyr on data bigger than memory), and on a DuckDB database (15  DuckDB: a database without the database). You learn one language for data, and it scales.

Tools that last

Physicists keep code and data for a whole career, and archives keep them longer. A spectrum recorded this year may be reanalysed by someone who has not been born yet. Your tools should outlive the next trend.

R is conservative in the best sense. It descends from S, the language John Chambers and his colleagues began designing at Bell Labs in 1976 (Chambers 2020). Ross Ihaka and Robert Gentleman started R at the University of Auckland in the early 1990s (Ihaka and Gentleman 1996), version 1.0.0 was released on 29 February 2000, and CRAN, the network of servers that distributes R packages, has been running since 1997. Base R code written decades ago still runs today.

This book leans into that. It teaches base R and a short list of long-established, actively maintained packages, and from those packages it uses only functions their authors mark as stable (Posit Software, n.d.). When a function you will meet in older code has been superseded, the book says so and shows its replacement. It stores data in formats that have stayed readable for decades, like gzip-compressed CSV, or in open, documented standards that many languages read, like Parquet and Arrow. Astronomers have a motto for this, from the history of their FITS file format: once FITS, always FITS (NASA FITS Support Office, n.d.). The format may grow, but no change may ever make an existing file invalid; even a feature the standard retires must, in its own words, “remain valid indefinitely” (IAU FITS Working Group 2018).

Conservative does not mean dull. The payoff of every chapter is physics: a resonance peak, a Hertzsprung–Russell diagram, a geomagnetic disturbance, drawn with ggplot2 and good enough for a paper.

Why compression?

Big physics data is compressed data. Every detector, telescope and simulation that produces more numbers than will fit on one disk relies on algorithms that are, by the standards of computing, old: Huffman’s code from 1952 (Huffman 1952), Ziv and Lempel’s methods from 1977 and 1978 (Ziv and Lempel 1977, 1978), DEFLATE from the early 1990s (Deutsch 1996). They have lasted because they rest on physics you already know. Shannon’s measure of information has the same form as the Gibbs entropy of statistical mechanics, and it sets a hard limit on how small a file can get (Shannon 1948). Part II explains the algorithms from that physical side. Part III then puts them to work through Parquet, Arrow and DuckDB, always with the same dplyr verbs.

How this book relates to others

The form of this book comes from R for Data Science (Wickham et al. 2023): short chapters grouped into parts, a “whole game” first, every piece of code shown with its output, and exercises at the end of each chapter. Where the book depends on how R works underneath (memory, copying, vectors, functions) it cites Hadley Wickham’s Advanced R (Wickham 2019), which tells the full story. Both are free to read online, and both are worth reading in full.

NoteAn independent book

Advanced R for Physics is an independent book by Dave Rosenman. Its title nods to Hadley Wickham’s Advanced R, and it cites his books throughout, but it is not affiliated with, sponsored by or endorsed by Hadley Wickham, his co-authors, or Posit.

NoteFree to read, free to reuse

This book is free. The text is licensed under CC BY-NC-ND 4.0. The code and the data files are MIT-licensed, so use them in your own work however you like. The source is at https://github.com/DRosenman/advanced-r-for-physics.