library(tidyverse)3 From Fortran to the tidyverse
3.1 Introduction
FORTRAN was designed so that a scientist could write Y = A*X**2 + B and have the machine work out the instructions (Backus et al. 1957). That was abstraction, and in 1957 it was revolutionary. The tidyverse takes the same step one level up: where Fortran freed you from registers and memory addresses, dplyr frees you from loop counters and array bounds. You say which rows, which groups and which summary, and the loop is written for you, in compiled code.
This chapter is for readers who learned to program with loops, whether in Fortran, C, IDL or anything else. It puts the loop you would write next to the tidyverse code that replaces it, shows when a loop is still the right tool, and then shows how much of Fortran is still underneath R, including how to call your own Fortran subroutines from a tidy pipeline. Your old code does not have to be thrown away.
Prerequisites
The examples use the dimuon data from Chapter 1. Computing the invariant mass is a job we will do often, so it is worth a function. A Fortran FUNCTION becomes an R function:
invariant_mass <- function(pt1, eta1, phi1, pt2, eta2, phi2) {
sqrt(2 * pt1 * pt2 * (cosh(eta1 - eta2) - cos(phi1 - phi2)))
}
dimuon <- read_csv("data/dimuon.csv.gz") |>
mutate(
mass_gev = invariant_mass(mu1_pt, mu1_eta, mu1_phi, mu2_pt, mu2_eta, mu2_phi)
)The function takes whole columns, not single numbers. Every operation inside it works element by element on vectors, so one call computes all 119,528 masses. There is no loop in sight, but there is one underneath: R’s arithmetic runs a loop in compiled C over the elements, which is why it is fast (Wickham 2019, chap. 24).
3.2 A selection and a sum
Here is the kind of loop every physicist has written: the mean mass of the pairs above 60 GeV.
total = 0.0d0
nsel = 0
do i = 1, n
if (mass(i) > 60.0d0) then
total = total + mass(i)
nsel = nsel + 1
end if
end do
mean_mass = total / nselTen lines, two accumulators to initialise, an index to manage and a division that fails if nothing passed the cut. In R the whole loop is one expression, by logical indexing:
mean(dimuon$mass_gev[dimuon$mass_gev > 60])
#> [1] 90.87084In the tidyverse it is a sentence: filter the table, then summarise it.
dimuon |>
filter(mass_gev > 60) |>
summarise(mean_mass_gev = mean(mass_gev), n = n())
#> # A tibble: 1 × 2
#> mean_mass_gev n
#> <dbl> <int>
#> 1 90.9 5854Both R versions say what to compute. Neither can get the bounds wrong, forget to reset an accumulator, or divide by a stale count.
3.3 Groups without bookkeeping
Now do it for each run. In Fortran you need an array of accumulators, one per run, and a way to turn a run number into an array index:
total = 0.0d0
nsel = 0
do i = 1, n
if (mass(i) > 60.0d0) then
k = run(i) - 2300 ! assumes runs are numbered 2301 to 2308
total(k) = total(k) + mass(i)
nsel(k) = nsel(k) + 1
end if
end do
do k = 1, 8
print *, 2300 + k, total(k) / nsel(k), nsel(k)
end doThat code works only for this data set. It hard-codes how many runs there are and how they are numbered, and the day a run 2309 appears it writes past the end of an array. The tidyverse version discovers the groups from the data:
dimuon |>
filter(mass_gev > 60) |>
group_by(run) |>
summarise(mean_mass_gev = mean(mass_gev), n = n())
#> # A tibble: 8 × 3
#> run mean_mass_gev n
#> <dbl> <dbl> <int>
#> 1 2301 90.8 698
#> 2 2302 91.5 731
#> 3 2303 90.5 695
#> 4 2304 90.4 743
#> 5 2305 90.9 747
#> 6 2306 91.0 774
#> 7 2307 90.5 749
#> 8 2308 91.4 717group_by() is the abstraction that Fortran lacks. Grouping by two variables, say run and the charge of the leading muon, is a change of one line in R and a redesign in Fortran.
3.4 A simulation with no loops
Loops are not only for data. Simulations are where most physicists first write nested loops, and many simulations can be written without them. Take Brownian motion, the random walk of a particle kicked by molecules, which Einstein explained in 1905 (Einstein 1905). Each particle takes a sequence of independent random steps. The Fortran is two nested loops:
msd = 0.0d0
do p = 1, nparticles
x = 0.0d0
y = 0.0d0
do s = 1, nsteps
x = x + gauss() ! one standard normal random number
y = y + gauss()
msd(s) = msd(s) + x**2 + y**2
end do
end do
msd = msd / nparticlesIn the tidyverse you build a table with one row for every particle at every step, draw all the random kicks at once, and let a cumulative sum within each particle turn kicks into positions:
set.seed(1905)
walks <- expand_grid(particle = 1:500, step = 1:1000) |>
mutate(dx = rnorm(n()), dy = rnorm(n())) |>
group_by(particle) |>
mutate(x = cumsum(dx), y = cumsum(dy)) |>
ungroup()
walks
#> # A tibble: 500,000 × 6
#> particle step dx dy x y
#> <int> <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1.12 -1.23 1.12 -1.23
#> 2 1 2 2.05 1.10 3.18 -0.132
#> 3 1 3 -0.333 1.26 2.84 1.13
#> 4 1 4 -0.164 1.50 2.68 2.63
#> 5 1 5 -0.406 -0.366 2.27 2.26
#> 6 1 6 0.954 0.699 3.23 2.96
#> 7 1 7 -1.23 -1.59 2.00 1.37
#> 8 1 8 -0.142 -0.561 1.86 0.806
#> 9 1 9 -0.674 -1.05 1.18 -0.244
#> 10 1 10 0.392 0.249 1.57 0.00517
#> # ℹ 499,990 more rowsThe loop over steps became cumsum() and the loop over particles became group_by(). The mean squared displacement at each step is a grouped summary, this time grouped by step:
msd <- walks |>
group_by(step) |>
summarise(msd = mean(x^2 + y^2))For a random walk in two dimensions with unit variance per step in each direction, the mean squared displacement grows as ⟨r²⟩ = 2s, so its slope against the step number should be 2, and the diffusion coefficient, defined by ⟨r²⟩ = 4Dt in two dimensions, should be 0.5 in these units. A straight-line fit through the origin checks it:
fit <- lm(msd ~ 0 + step, data = msd)
coef(fit)
#> step
#> 1.931342
coef(fit) / 4
#> step
#> 0.4828354The slope is 1.93 rather than exactly 2, which is what 500 walks should give: each walk’s squared displacement scatters by about 100% around its mean, so the average of 500 of them is uncertain by about 1/√500, or 4.5%.
walks |>
filter(particle <= 8) |>
ggplot(aes(x, y, group = particle, colour = factor(particle))) +
geom_path(linewidth = 0.3, show.legend = FALSE) +
coord_equal() +
labs(x = "x", y = "y")
ggplot(msd, aes(step, msd)) +
geom_line() +
geom_abline(slope = 2, intercept = 0, linetype = "dashed", colour = "firebrick") +
labs(x = "Step", y = "Mean squared displacement")
Half a million random kicks, cumulated and summarised, with no index variable anywhere.
3.5 When a loop is the right tool
Some calculations really are sequential: each step needs the result of the one before, through a function that is not a simple sum. Integrating an equation of motion is the classic case. A ball falling through air feels gravity and a drag force proportional to the square of its speed, so
\[ \frac{dv}{dt} = g - k v^2 , \]
where k is the drag coefficient divided by the mass. The speed at the next instant depends on the square of the speed now, so cumsum() cannot help. Write the loop, and write it the way Advanced R recommends: create the output vector at full length before the loop, rather than growing it one element at a time, which forces R to copy the vector at every step (Wickham 2019, sec. 5.3).
fall_with_drag <- function(k, dt = 0.01, t_max = 15, g = 9.81) {
n <- round(t_max / dt) + 1
v <- numeric(n) # allocate once, before the loop
for (i in 2:n) {
v[i] <- v[i - 1] + (g - k * v[i - 1]^2) * dt
}
tibble(t_s = (seq_len(n) - 1) * dt, v_ms = v)
}The outer loop, over different values of k, is the kind purrr’s map() replaces (Wickham et al. 2023; Wickham 2019, chap. 9). map() applies a function to each element of a vector and returns a list; stored in a column and unnested, the list becomes one tidy table of all the runs:
falls <- tibble(k = c(0.002, 0.005, 0.01, 0.02)) |>
mutate(trajectory = map(k, fall_with_drag)) |>
unnest(trajectory)
falls
#> # A tibble: 6,004 × 3
#> k t_s v_ms
#> <dbl> <dbl> <dbl>
#> 1 0.002 0 0
#> 2 0.002 0.01 0.0981
#> 3 0.002 0.02 0.196
#> 4 0.002 0.03 0.294
#> 5 0.002 0.04 0.392
#> 6 0.002 0.05 0.490
#> 7 0.002 0.06 0.589
#> 8 0.002 0.07 0.687
#> 9 0.002 0.08 0.785
#> 10 0.002 0.09 0.883
#> # ℹ 5,994 more rowsSetting dv/dt = 0 gives the terminal speed, √(g/k), which the plot should approach:
ggplot(falls, aes(t_s, v_ms, colour = factor(k))) +
geom_line() +
geom_hline(
aes(yintercept = sqrt(9.81 / k), colour = factor(k)),
data = distinct(falls, k),
linetype = "dashed"
) +
labs(x = "Time (s)", y = "Speed (m/s)", colour = expression(italic(k) ~ (m^-1)))
The rule of thumb: describe results with verbs when the work is a selection, a transformation or a summary, which covers almost all data analysis. Write a loop when each step genuinely depends on the last. And when the loop is slow, the cure is often to move its expensive inner part into compiled code, which is the next subject. My N-body package orbitr (Rosenman 2026) is built that way: its time loop is ordinary R, and the costly part of each step, summing the gravitational pull of every body on every other, runs in compiled C++.
3.6 Fortran is still inside R
R and Fortran are closer relatives than they look.
Both count from 1. Both store a matrix column by column, so the elements of a column sit next to each other in memory. Build a matrix and look at the order in which R stores it:
m <- matrix(1:6, nrow = 2)
m
#> [,1] [,2] [,3]
#> [1,] 1 3 5
#> [2,] 2 4 6
as.vector(m)
#> [1] 1 2 3 4 5 6The numbers run down the first column, then the second: column-major order, exactly as in Fortran and the reverse of C. When you hand an R matrix to Fortran code, no transposing is needed.
R’s linear algebra is Fortran. solve() calls the LAPACK routine DGESV, qr() and therefore lm() use a modified version of LINPACK’s DQRDC, and eigen() calls LAPACK’s eigenvalue routines; all of these libraries were written in Fortran, and R ships them. La_version() reports which LAPACK your R is using:
La_version()
#> [1] "3.12.1"Here is LAPACK doing physics. Three equal masses on a line are joined to each other and to two walls by four equal springs. The squared frequencies of the normal modes are the eigenvalues of the stiffness matrix divided by the mass, and the mode shapes are its eigenvectors:
k_over_m <- 1 # spring constant / mass, in s^-2
stiffness <- k_over_m * matrix(
c( 2, -1, 0,
-1, 2, -1,
0, -1, 2),
nrow = 3
)
modes <- eigen(stiffness, symmetric = TRUE)
sqrt(modes$values) # angular frequencies, rad/s
#> [1] 1.8477591 1.4142136 0.7653669
round(modes$vectors, 3) # one mode shape per column
#> [,1] [,2] [,3]
#> [1,] -0.500 -0.707 0.500
#> [2,] 0.707 0.000 0.707
#> [3,] -0.500 0.707 0.500The frequencies come out as √(2 + √2), √2 and √(2 − √2) rad/s, the textbook result. The slowest mode, in the last column, moves all three masses the same way; the middle one holds the centre mass still while the outer two swing against each other; and the fastest, in the first column, moves the centre mass against the outer two.
3.7 Calling your own Fortran
You can call your own Fortran subroutines from R with .Fortran(). Here is the selection-and-sum loop from earlier as a Fortran 90 subroutine. .Fortran() passes every argument by reference, so results come back through arguments, the way Fortran programmers are used to. (The name has no underscore because .Fortran() handles such names unreliably.)
fortran_source <- "
subroutine selmean(n, x, cut, total, nsel)
implicit none
integer, intent(in) :: n
double precision, intent(in) :: x(n), cut
double precision, intent(out) :: total
integer, intent(out) :: nsel
integer :: i
total = 0.0d0
nsel = 0
do i = 1, n
if (x(i) > cut) then
total = total + x(i)
nsel = nsel + 1
end if
end do
end subroutine selmean
"R CMD SHLIB compiles it with the same compiler that built R, and dyn.load() loads the result into the running session:
dir.create("scratch", showWarnings = FALSE)
writeLines(fortran_source, "scratch/selmean.f90")
system2(
file.path(R.home("bin"), "R"),
c("CMD", "SHLIB", "scratch/selmean.f90"),
stdout = FALSE
)
dyn.load(paste0("scratch/selmean", .Platform$dynlib.ext))A short R function hides the call. Note the types: Fortran integer must be an R integer and double precision an R double, so 0L and 0 are not interchangeable here.
fortran_mean_above <- function(x, cut) {
result <- .Fortran(
"selmean",
n = length(x),
x = as.double(x),
cut = as.double(cut),
total = 0,
nsel = 0L
)
result$total / result$nsel
}Now the Fortran runs inside a tidy pipeline, once per group, and agrees with dplyr:
dimuon |>
group_by(run) |>
summarise(
fortran = fortran_mean_above(mass_gev, 60),
dplyr = mean(mass_gev[mass_gev > 60])
)
#> # A tibble: 8 × 3
#> run fortran dplyr
#> <dbl> <dbl> <dbl>
#> 1 2301 90.8 90.8
#> 2 2302 91.5 91.5
#> 3 2303 90.5 90.5
#> 4 2304 90.4 90.4
#> 5 2305 90.9 90.9
#> 6 2306 91.0 91.0
#> 7 2307 90.5 90.5
#> 8 2308 91.4 91.4This is how decades of physics code stays useful: the numerical core stays in Fortran, and the data handling around it moves to tools that are easier to read and change. For anything beyond a quick experiment, put the Fortran in the src/ folder of an R package, where R compiles it for you, and consider the newer .Call() interface, which the R documentation describes as more flexible and faster; Writing R Extensions, R’s manual for package authors, explains both.
3.8 Summary
A loop that selects, transforms or summarises becomes a chain of verbs: filter() for the IF, mutate() for the arithmetic, group_by() for the arrays of accumulators, summarise() for the sums. A simulation built from independent random steps becomes a table and a cumulative sum. A truly sequential calculation stays a loop, written with its output allocated up front, and purrr’s map() replaces the loop around it. Underneath, R is closer to Fortran than it looks: column-major matrices, indices from 1, LAPACK and LINPACK for linear algebra, and .Fortran() for your own code.
3.9 Exercises
Translate this loop into a dplyr pipeline on the magnetometer data, which has one reading per second: for each hour of the day, compute the root-mean-square deviation of
bx_ntfrom that hour’s mean. Which hour is the most disturbed?do h = 0, 23 s = 0.0d0 s2 = 0.0d0 do i = 1, 3600 b = bx(3600*h + i) s = s + b s2 = s2 + b**2 end do rms(h) = sqrt(s2/3600 - (s/3600)**2) end doExtend the random walk to three dimensions. What slope do you expect for the mean squared displacement against step number, and what diffusion coefficient? Check both.
Add
k = 0to the drag simulation and compare the result with free fall, v = gt. How large is the error of the simple integration after 15 seconds, and how does it change if you halvedt?Extend the normal-mode example to five masses and four, six springs, and plot the five mode shapes as lines against mass number.
If you have a Fortran compiler, write a subroutine that computes the invariant mass of every pair from six input arrays and returns an output array. Check it against
invariant_mass().