Skip to main content

14  Arrow datasets: dplyr on data bigger than memory

14.1 Introduction

Apache Arrow began in 2016 with a simple observation: every data system kept tables in memory in its own private layout, so moving data between them meant converting it, slowly, every time. Arrow defined one standard columnar layout for tables in memory, and libraries in about a dozen languages adopted it, so that R, Python, C++, Rust and the rest can hand each other data without copying or converting it. Around that standard grew fast readers and writers for Parquet, a query engine, and a way to treat a whole folder of files as one table.

The arrow R package (Richardson et al. 2026) brings all of that to R, and it does so through dplyr. You have already used it in Chapter 1 and Chapter 13. This chapter is about its most important feature, datasets: tables made of many files, possibly much larger than your computer’s memory, that you query with the same verbs you use on a data frame. R for Data Science has an introduction to the same tools in its chapter on Arrow (Wickham et al. 2023).

Prerequisites

library(tidyverse)
library(arrow)

14.2 A year of running

Real experiments write data in runs, and a year of running is far bigger than one file. To have something larger to work with, this section fabricates one from the dimuon sample. Each new run is a random resample of the original events, with every event’s azimuthal angles rotated together by the same random amount. A detector is symmetric around the beam, so a rotation in azimuth changes nothing physical, and in particular it leaves every invariant mass unchanged:

dimuon <- read_csv("data/dimuon.csv.gz", col_types = "iidddidddi")

wrap_phi <- function(phi) (phi + pi) %% (2 * pi) - pi

fabricate_run <- function(run_number) {
  rotation <- runif(1, -pi, pi)
  dimuon |>
    slice_sample(n = nrow(dimuon), replace = TRUE) |>
    mutate(
      run = run_number,
      event = row_number(),
      mu1_phi = round(wrap_phi(mu1_phi + rotation), 4),
      mu2_phi = round(wrap_phi(mu2_phi + rotation), 4)
    )
}

The important habit here is how the runs are written: one at a time. walk(), purrr’s version of map() for functions you call for their side effects, makes each run and appends it to the dataset, so no more than one run is ever in memory. write_dataset() puts each run in its own folder, and the existing_data_behavior argument tells it that adding files to an existing dataset is intended:

set.seed(2016)
unlink("scratch/year", recursive = TRUE)

walk(3001:3040, \(run_number) {
  fabricate_run(run_number) |>
    write_dataset(
      "scratch/year",
      partitioning = "run",
      compression = "zstd",
      existing_data_behavior = "overwrite"
    )
})

Forty runs, one Parquet file each, in folders named in the style run=3001, called Hive-style partitioning after the data warehouse system that popularised it:

year_files <- list.files("scratch/year", recursive = TRUE, full.names = TRUE)
length(year_files)
#> [1] 40
sum(file.size(year_files)) / 1e6
#> [1] 138.4014

14.3 Opening a dataset

open_dataset() points at the folder. It reads the folder names and the schemas in the file footers, and nothing else:

events <- open_dataset("scratch/year")
events
#> FileSystemDataset with 40 Parquet files
#> 10 columns
#> event: int32
#> mu1_pt: double
#> mu1_eta: double
#> mu1_phi: double
#> mu1_charge: int32
#> mu2_pt: double
#> mu2_eta: double
#> mu2_phi: double
#> mu2_charge: int32
#> run: int32
nrow(events)
#> [1] 4781120

Almost five million events, and so far R holds none of them. nrow() came from the row counts in the Parquet footers. Notice that run is listed as a column even though no file contains it: arrow recovered it from the folder names.

14.4 Lazy queries

dplyr verbs on a dataset do not compute anything. They build a description of a query, which arrow runs only when you ask for the result:

spectrum_query <- events |>
  filter(mu1_charge != mu2_charge) |>
  mutate(
    mass_gev = sqrt(
      2 * mu1_pt * mu2_pt * (cosh(mu1_eta - mu2_eta) - cos(mu1_phi - mu2_phi))
    ),
    log_bin = floor(log10(mass_gev) / 0.005)
  ) |>
  count(log_bin)

spectrum_query
#> FileSystemDataset (query)
#> log_bin: double
#> n: int64
#> 
#> See $.data for the source Arrow object

The printout shows the columns the result will have, and nothing else, because nothing else exists yet. collect() runs the query and returns a tibble. arrow reads the files in parallel, a batch of rows at a time, filters, computes and counts, and throws each batch away when it is done, so memory use stays small however big the dataset is:

system.time(spectrum <- collect(spectrum_query))
#>    user  system elapsed 
#>    1.64    0.20    1.48
nrow(spectrum)
#> [1] 381

A histogram of five million events in about a second, and the only thing in R’s memory is the 381-row result. This is the pattern for big data in this book: filter, compute and summarise where the data live, and bring only the summary into R.

If you want to see what arrow will actually do, show_exec_plan() prints the query plan, from reading the source at the bottom to the final aggregation at the top:

show_exec_plan(spectrum_query)
#> ExecPlan with 5 nodes:
#> 4:SinkNode{}
#>   3:GroupByNode{keys=["log_bin"], aggregates=[
#>      hash_count_all(*),
#>   ]}
#>     2:ProjectNode{projection=["log_bin": floor(divide(cast(log10_checked(sqrt_checked(multiply_checked(multiply_checked(multiply_checked(2, mu1_pt), mu2_pt), subtract_checked(cosh(subtract_checked(mu1_eta, mu2_eta)), cos_checked(subtract_checked(mu1_phi, mu2_phi)))))), {to_type=double, allow_int_overflow=false, allow_time_truncate=false, allow_time_overflow=false, allow_decimal_truncate=false, allow_float_truncate=false, allow_invalid_utf8=false}), cast(0.005, {to_type=double, allow_int_overflow=false, allow_time_truncate=false, allow_time_overflow=false, allow_decimal_truncate=false, allow_float_truncate=false, allow_invalid_utf8=false})))]}
#>       1:FilterNode{filter=(mu1_charge != mu2_charge)}
#>         0:SourceNode{}

compute() is the third way to finish a query: it runs the query but keeps the result as an Arrow table, in Arrow’s memory, without converting it to an R data frame. That is useful for an intermediate result you will query again.

14.5 Skipping files

Partitioning pays off when you filter on the partition column. A query for one run opens one file out of forty, because arrow knows from the folder names that the other files cannot contain run 3017:

system.time(
  events |>
    filter(run == 3017) |>
    count() |>
    collect()
)
#>    user  system elapsed 
#>    0.04    0.00    0.05

Inside each file, the row-group statistics of Chapter 13 let arrow skip still more. Between partitions and statistics, a well-organised dataset lets most queries read a small fraction of the data. Choose partition columns that you filter on often and that have a modest number of values: runs, days, detector regions or sky tiles. Thousands of tiny files are slower than dozens of large ones, because every file has a cost to open.

14.6 What arrow can and cannot do

arrow translates dplyr verbs, and a long list of R functions, into its own compute engine: arithmetic and mathematics, comparisons, if_else() and case_when(), many string functions from stringr, date and time functions from lubridate, and the usual summaries. list_compute_functions() lists the 287 functions underneath. When arrow meets something it cannot translate, it stops and says so, rather than quietly giving a wrong answer. A window function, such as ranking muons within each run, is one example:

events |>
  group_by(run) |>
  mutate(rank = min_rank(desc(mu1_pt))) |>
  filter(rank == 1) |>
  collect()
#> Error in `min_rank()`:
#> ! Expression not supported in Arrow
#> → Call collect() first to pull data into R.

The message offers one fix: collect() first and do the rest in R, which is fine when the data that remain after filtering fit in memory. The other fix is DuckDB, which handles window functions and joins on data of any size, and to which arrow can hand a dataset without copying it (Chapter 15). A few functions are approximations in arrow; median() and quantile(), for example, return approximate results on datasets and warn you once per session.

14.7 Arrow in memory

An Arrow table is not an R data frame. It lives in Arrow’s own memory, outside R’s, and its columns can have types R lacks. One that matters for physics is the 4-byte floating-point type, float32(), which R does not have (Chapter 11). A float32 holds about seven significant digits, which is more than most measurements have. arrow_table() converts a data frame, and cast() inside mutate() changes a column’s type:

dimuon_arrow <- arrow_table(dimuon)

dimuon_float <- dimuon_arrow |>
  mutate(
    mu1_pt = cast(mu1_pt, float32()),
    mu1_eta = cast(mu1_eta, float32()),
    mu1_phi = cast(mu1_phi, float32()),
    mu2_pt = cast(mu2_pt, float32()),
    mu2_eta = cast(mu2_eta, float32()),
    mu2_phi = cast(mu2_phi, float32())
  ) |>
  compute()

c(doubles = dimuon_arrow$nbytes(), floats = dimuon_float$nbytes()) / 1e6
#>  doubles   floats 
#> 7.649792 4.781120

The table shrinks by more than a third. The largest change in any momentum is a few keV, a thousand times smaller than the 1 MeV precision the data were recorded with:

max(abs(as_tibble(dimuon_float)$mu1_pt - dimuon$mu1_pt))
#> [1] 3.78418e-06

14.8 Arrow IPC files

Arrow also has a file format of its own, which writes the in-memory layout straight to disk. It is called the Arrow IPC format, for inter-process communication; its first version was called Feather, a name you will still see. write_ipc_file() and read_ipc_file() write and read it. (The older write_feather() still works but is superseded by write_ipc_file(); arrow will tell you so if you use it.) LZ4 is the default compression:

write_ipc_file(dimuon, "scratch/dimuon.arrow")
file.size("scratch/dimuon.arrow") / 1e6
#> [1] 4.112322

Because the file layout is the memory layout, an IPC file can be memory-mapped: the operating system maps the file into memory and loads pages only when they are touched, so opening even a huge file is instant. That needs an uncompressed file:

write_ipc_file(dimuon, "scratch/dimuon-raw.arrow", compression = "uncompressed")
system.time(mapped <- read_ipc_file("scratch/dimuon-raw.arrow", as_data_frame = FALSE, mmap = TRUE))
#>    user  system elapsed 
#>       0       0       0

IPC files are the fastest way to pass a table between steps of an analysis, or between R and Python on the same machine. For long-term storage and for sharing, prefer Parquet: it is more compact, more widely supported and designed for exactly that.

14.9 Summary

Apache Arrow is a standard columnar layout for tables in memory, shared by libraries in about a dozen languages, and the arrow package brings it to R through dplyr. You wrote a dataset of forty runs one run at a time with write_dataset() and walk(), opened it with open_dataset(), and histogrammed five million events with an ordinary dplyr pipeline in about a second, bringing only the result into R with collect(). Hive-style partitions let arrow skip whole files, and row-group statistics skip parts of files. arrow stops with a clear message when it cannot translate a function; window functions are the usual case, and DuckDB is the usual answer. Arrow tables can use 4-byte floats, which R lacks, and Arrow IPC files map straight into memory.

14.10 Exercises

  1. Using events, find the number of opposite-sign pairs between 80 and 100 GeV in each run, and plot it against the run number with error bars of √n. Does any run stand out?
  2. Write the year’s data again, partitioned by run and by the sign of the leading muon’s charge. How many files are there, and how does the time of a query for one run change?
  3. Run spectrum_query with compute() instead of collect(). What kind of object do you get? How do you turn it into a tibble?
  4. Write the year of data as one big Parquet file with write_parquet() after collecting it, if your computer has the memory, and compare the time of the one-run query against the partitioned dataset.
  5. Cast the momenta in dimuon_arrow to 16-bit floats with cast(mu1_pt, float16()), if your version of arrow supports it, or work out by hand how many significant digits a 16-bit float holds. Would that be enough for these data?