library(tidyverse)2 Tidy data
2.1 Introduction
Physicists record data in whatever shape the instrument or the moment suggests: one column per detector channel, one file per run, one row per spectrum with a thousand columns of counts. Every one of those shapes is fine for recording. Most of them are awkward for analysis, because each needs its own code.
The tidyverse asks for one shape, and in return every tool works on it. Hadley Wickham set out the idea in a paper called “Tidy Data” (Wickham 2014), and R for Data Science teaches it in its chapter on data tidying (Wickham et al. 2023). A table is tidy when:
- each variable is a column, and each column is a variable;
- each observation is a row, and each row is an observation;
- each value sits in its own cell.
Physicists already know this shape as a lab notebook done right: one line per measurement, one column per quantity, units in the heading. The hard part, in practice, is deciding what counts as an observation. This chapter works through three examples where the answer is not obvious, and learns the two functions that convert between shapes, pivot_longer() and pivot_wider().
Prerequisites
2.2 A magnetometer, two ways
A fluxgate magnetometer measures the three components of the magnetic field. The book’s magnetometer file holds one day of readings, one per second:
magnetometer <- read_csv("data/magnetometer.csv.gz")
magnetometer
#> # A tibble: 86,400 × 4
#> time bx_nt by_nt bz_nt
#> <dttm> <dbl> <dbl> <dbl>
#> 1 2026-03-20 00:00:00 20459. -4389. 47118.
#> 2 2026-03-20 00:00:01 20459. -4389. 47118.
#> 3 2026-03-20 00:00:02 20459. -4389. 47118.
#> 4 2026-03-20 00:00:03 20459. -4389. 47118.
#> 5 2026-03-20 00:00:04 20459. -4389. 47118.
#> 6 2026-03-20 00:00:05 20459. -4389. 47118.
#> 7 2026-03-20 00:00:06 20459. -4389. 47118
#> 8 2026-03-20 00:00:07 20459. -4389. 47118.
#> 9 2026-03-20 00:00:08 20459. -4389. 47118.
#> 10 2026-03-20 00:00:09 20459. -4389. 47118.
#> # ℹ 86,390 more rowsIs this tidy? It depends on the question, and that is the first lesson. If an observation is “the field vector at one instant”, then each row is one observation and the three components are three variables. In that shape, a calculation that uses all three components at once is a single mutate(). The magnitude of the field is one line:
magnetometer |>
mutate(b_total_nt = sqrt(bx_nt^2 + by_nt^2 + bz_nt^2))
#> # A tibble: 86,400 × 5
#> time bx_nt by_nt bz_nt b_total_nt
#> <dttm> <dbl> <dbl> <dbl> <dbl>
#> 1 2026-03-20 00:00:00 20459. -4389. 47118. 51555.
#> 2 2026-03-20 00:00:01 20459. -4389. 47118. 51555.
#> 3 2026-03-20 00:00:02 20459. -4389. 47118. 51555.
#> 4 2026-03-20 00:00:03 20459. -4389. 47118. 51555.
#> 5 2026-03-20 00:00:04 20459. -4389. 47118. 51555.
#> 6 2026-03-20 00:00:05 20459. -4389. 47118. 51555.
#> 7 2026-03-20 00:00:06 20459. -4389. 47118 51555.
#> 8 2026-03-20 00:00:07 20459. -4389. 47118. 51555.
#> 9 2026-03-20 00:00:08 20459. -4389. 47118. 51555.
#> 10 2026-03-20 00:00:09 20459. -4389. 47118. 51555.
#> # ℹ 86,390 more rowsNow suppose you want to plot all three components against time, one panel each. ggplot2 wants a single column of values, and a second column saying which component each value belongs to, so it can map that column to a facet. In that view an observation is “one component at one instant”, and the table is too wide. pivot_longer() lengthens it:
field_long <- magnetometer |>
pivot_longer(
cols = c(bx_nt, by_nt, bz_nt),
names_to = "component",
names_pattern = "b(.)_nt",
values_to = "field_nt"
)
field_long
#> # A tibble: 259,200 × 3
#> time component field_nt
#> <dttm> <chr> <dbl>
#> 1 2026-03-20 00:00:00 x 20459.
#> 2 2026-03-20 00:00:00 y -4389.
#> 3 2026-03-20 00:00:00 z 47118.
#> 4 2026-03-20 00:00:01 x 20459.
#> 5 2026-03-20 00:00:01 y -4389.
#> 6 2026-03-20 00:00:01 z 47118.
#> 7 2026-03-20 00:00:02 x 20459.
#> 8 2026-03-20 00:00:02 y -4389.
#> 9 2026-03-20 00:00:02 z 47118.
#> 10 2026-03-20 00:00:03 x 20459.
#> # ℹ 259,190 more rowscols says which columns to stack. names_to names the new column that will hold the old column names, and names_pattern is a regular expression whose bracketed part keeps just the x, y or z. values_to names the column that holds the numbers. The table went from 86,400 rows of four columns to 259,200 rows of three.
Plotting 86,400 points per panel is slow and shows nothing a one-minute average would not. floor_date(), from the lubridate package that comes with the tidyverse, rounds each time down to its minute, and a grouped summary averages within each minute:
field_minutes <- field_long |>
mutate(minute = floor_date(time, "minute")) |>
group_by(component, minute) |>
summarise(field_nt = mean(field_nt)) |>
ungroup()ggplot(field_minutes, aes(x = minute, y = field_nt)) +
geom_line(linewidth = 0.4) +
facet_wrap(~component, ncol = 1, scales = "free_y",
labeller = labeller(component = \(x) paste0("B", x))) +
labs(x = "Time (UTC)", y = "Field (nT)")
The slow swings are the quiet-day variation, driven by currents in the ionosphere that follow the Sun. The step at about 14:20 is a sudden impulse: a pressure pulse in the solar wind compressing Earth’s magnetic field. It is visible in all three panels at once because they share a time axis, which is exactly what the long shape made easy.
Neither shape is “the” tidy one. The wide table is tidy for vector arithmetic, the long one for plotting by component, and moving between them costs one function call. Keep whichever shape the next step wants.
2.3 Gamma-ray spectra in the wrong shape
Many instruments write a spectrum as a single row: the detector name followed by the counts in each channel, a thousand or more columns wide. Here are three gamma-ray detectors, each recording the same source, a mix of caesium-137 and cobalt-60. The data are simulated; unfold the code if you want to see how.
Simulate three gamma-ray spectra
set.seed(137)
lines_kev <- c(661.657, 1173.228, 1332.492)
line_counts <- c(9000, 4200, 3800)
simulate_spectrum <- function(gain_kev, offset_kev, resolution) {
energy_kev <- offset_kev + gain_kev * (1:1024)
expected <- 400 * exp(-energy_kev / 350) + 15
for (i in seq_along(lines_kev)) {
sigma_kev <- resolution * sqrt(lines_kev[i])
expected <- expected +
line_counts[i] * gain_kev * dnorm(energy_kev, lines_kev[i], sigma_kev)
}
rpois(1024, expected)
}
calibration <- tribble(
~detector, ~gain_kev, ~offset_kev, ~resolution,
"A", 1.46, -2.0, 0.20,
"B", 1.61, 3.5, 0.30,
"C", 1.53, -7.1, 0.25
)
spectra_wide <- calibration |>
mutate(counts = pmap(list(gain_kev, offset_kev, resolution), simulate_spectrum)) |>
select(detector, counts) |>
unnest_longer(counts, indices_to = "channel") |>
pivot_wider(names_from = channel, values_from = counts, names_prefix = "ch_")spectra_wide
#> # A tibble: 3 × 1,025
#> detector ch_1 ch_2 ch_3 ch_4 ch_5 ch_6 ch_7 ch_8 ch_9 ch_10 ch_11
#> <chr> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1 A 423 441 405 425 395 430 410 426 390 407 395
#> 2 B 450 420 396 405 353 408 387 384 440 400 388
#> 3 C 401 405 479 404 397 452 434 408 395 380 401
#> # ℹ 1,013 more variables: ch_12 <int>, ch_13 <int>, ch_14 <int>,
#> # ch_15 <int>, ch_16 <int>, ch_17 <int>, ch_18 <int>, ch_19 <int>,
#> # ch_20 <int>, ch_21 <int>, ch_22 <int>, ch_23 <int>, ch_24 <int>,
#> # ch_25 <int>, ch_26 <int>, ch_27 <int>, ch_28 <int>, ch_29 <int>,
#> # ch_30 <int>, ch_31 <int>, ch_32 <int>, ch_33 <int>, ch_34 <int>,
#> # ch_35 <int>, ch_36 <int>, ch_37 <int>, ch_38 <int>, ch_39 <int>,
#> # ch_40 <int>, ch_41 <int>, ch_42 <int>, ch_43 <int>, ch_44 <int>, …Three rows and 1,025 columns. The observation here is one count in one channel of one detector, so the channel number is a variable that has been smeared across a thousand column names. pivot_longer() puts it back:
spectra <- spectra_wide |>
pivot_longer(
cols = starts_with("ch_"),
names_to = "channel",
names_prefix = "ch_",
names_transform = as.integer,
values_to = "counts"
)
spectra
#> # A tibble: 3,072 × 3
#> detector channel counts
#> <chr> <int> <int>
#> 1 A 1 423
#> 2 A 2 441
#> 3 A 3 405
#> 4 A 4 425
#> 5 A 5 395
#> 6 A 6 430
#> 7 A 7 410
#> 8 A 8 426
#> 9 A 9 390
#> 10 A 10 407
#> # ℹ 3,062 more rowsnames_prefix strips the ch_ and names_transform turns what is left into an integer, so channel is a number you can compute with.
Each detector has its own energy calibration, a gain in keV per channel and an offset, kept in a separate table. Joining the two tables attaches the right calibration to every row, and one mutate() converts channels to energies:
spectra <- spectra |>
left_join(calibration, join_by(detector)) |>
mutate(energy_kev = offset_kev + gain_kev * channel)spectra |>
filter(energy_kev > 550, energy_kev < 1450) |>
ggplot(aes(x = energy_kev, y = counts, colour = detector)) +
geom_step(linewidth = 0.4) +
labs(x = "Energy (keV)", y = "Counts per channel", colour = "Detector")
In channel number the three peaks sat in different places for each detector. In energy they line up, and the differences that remain are physics: detector A has the best resolution, so its peaks are the narrowest. That comparison took a pivot, a join and a mutate. Doing it with the wide table would have meant writing a loop over a thousand columns.
2.4 One row per event, or one per muon?
The dimuon file from Chapter 1 has one row per event, with four columns for each muon:
dimuon <- read_csv("data/dimuon.csv.gz")
names(dimuon)
#> [1] "run" "event" "mu1_pt" "mu1_eta" "mu1_phi"
#> [6] "mu1_charge" "mu2_pt" "mu2_eta" "mu2_phi" "mu2_charge"For anything about the pair, like its invariant mass, this is the tidy shape: the pair is the observation. For anything about single muons, like how their pseudorapidities are distributed, the observation is a muon, and the table is too wide. This time each column name holds two pieces of information, which muon and which quantity, separated by an underscore. The special name ".value" tells pivot_longer() that the second piece names an output column:
muons <- dimuon |>
pivot_longer(
cols = starts_with("mu"),
names_to = c("muon", ".value"),
names_sep = "_"
)
muons
#> # A tibble: 239,056 × 7
#> run event muon pt eta phi charge
#> <dbl> <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 2301 1 mu1 11.3 1.49 1.64 1
#> 2 2301 1 mu2 5.53 1.96 1.86 1
#> 3 2301 2 mu1 24.3 0.286 -0.640 1
#> 4 2301 2 mu2 4.77 0.223 -0.357 -1
#> 5 2301 3 mu1 13.4 -1.45 -3.01 1
#> 6 2301 3 mu2 12.0 -1.59 2.89 -1
#> 7 2301 4 mu1 19.1 0.149 1.72 1
#> 8 2301 4 mu2 16.6 -0.034 1.93 -1
#> 9 2301 5 mu1 11.8 -2.21 2.19 1
#> 10 2301 5 mu2 7.29 -2.26 1.97 -1
#> # ℹ 239,046 more rowsNow there are two rows per event, one per muon, with columns pt, eta, phi and charge. Questions about single muons become one-liners. The detector’s central barrel covers |η| < 1.2 and the endcaps cover the rest, so this counts muons by region:
muons |>
mutate(region = if_else(abs(eta) < 1.2, "barrel", "endcap")) |>
count(muon, region)
#> # A tibble: 4 × 3
#> muon region n
#> <chr> <chr> <int>
#> 1 mu1 barrel 64476
#> 2 mu1 endcap 55052
#> 3 mu2 barrel 64392
#> 4 mu2 endcap 55136pivot_wider() goes the other way, which is most useful for making a table for people to read. Here is the number of muons per run and region, laid out as a small table with one column per region:
muons |>
mutate(region = if_else(abs(eta) < 1.2, "barrel", "endcap")) |>
count(run, region) |>
pivot_wider(names_from = region, values_from = n)
#> # A tibble: 8 × 3
#> run barrel endcap
#> <dbl> <int> <int>
#> 1 2301 16209 13743
#> 2 2302 16000 13818
#> 3 2303 15677 13867
#> 4 2304 16084 13934
#> 5 2305 16562 13440
#> 6 2306 15938 14082
#> 7 2307 16178 13546
#> 8 2308 16220 137582.5 Code that others can read
Tidy data has a companion, tidy code. The tidyverse style guide (Wickham, n.d.) collects conventions that make code easier to read, and R for Data Science has a short chapter on them (Wickham et al. 2023). The ones that matter most for physics:
- Name columns in
snake_caseand end each name with its unit:field_nt,energy_kev,mass_gev. A column calledEwill mean something different to the next person, and a column calledenergyleaves them guessing the unit. - Put each verb of a pipeline on its own line, with the pipe at the end of the line. A pipeline then reads top to bottom like a list of steps.
- Put spaces around
<-,=,+and the other operators, and after commas. - Prefer the native pipe
|>, which is part of R itself, to the older%>%from the magrittr package. Both work.
None of this is decoration. An analysis that has to be checked, rerun or extended in five years will be read far more often than it is written.
2.6 Summary
A table is tidy when each row is an observation, each column a variable and each cell one value. Deciding what the observation is comes first, and the answer can change from one step of an analysis to the next: the field vector or one component, a spectrum or one channel, a pair or one muon. pivot_longer() and pivot_wider() move between shapes, a join attaches information from another table, and once the data are tidy every tidyverse function works on them without special cases.
2.7 Exercises
- Using
magnetometerin its wide form, compute the change in the total field from one second to the next withlag(). At what time is the largest one-second jump? Is it during the sudden impulse? - Turn
muonsback into one row per event withpivot_wider(). Check that you recover the original table:arrange()both and compare withall.equal(). - For each detector in
spectra, find the channel with the most counts between energies of 600 and 720 keV withslice_max(). Use that channel and the known energy of 661.657 keV to estimate each detector’s gain, assuming the offsets are known. How close do you get to the true gains incalibration? - Is the star catalog in
data/stars.csv.gztidy? Describe a way of storing the same information that would not be. - Remake the run-by-region table so that it shows the fraction of muons in the barrel for each run, rather than counts.