library(tidyverse)12 R’s own formats: CSV and RDS
12.1 Introduction
Without any extra packages, R can store a table in two kinds of file. One is text: CSV and its relatives, readable by anything. The other is R’s own binary format, RDS, which stores any R object exactly but which only R reads. Each is the right choice for some jobs, and the reasons are the ones this book keeps returning to: who needs to read the file, for how long, and how faithfully.
Prerequisites
dir.create("scratch", showWarnings = FALSE)12.2 CSV: the format that outlives everything
A CSV file is plain text: one line per row, values separated by commas. Its common form is written down in RFC 4180 (Shafranovich 2005), but its real strength is that it needs no specification at all. Every spreadsheet, every language and every operating system reads it, and so does a person with a text editor. A CSV file written in 1985 is as readable today as the day it was written, and that will still be true when every binary format in this book has been replaced.
readr reads and writes it, with compression by file extension, as earlier chapters showed. Its one serious weakness is that text has no types. Every reader has to guess whether a column holds integers, decimals, dates or text, and readr prints its guesses when it reads a file:
dimuon <- read_csv("data/dimuon.csv.gz")
#> Rows: 119528 Columns: 10
#> ── Column specification ────────────────────────────────────────────────────
#> Delimiter: ","
#> dbl (10): run, event, mu1_pt, mu1_eta, mu1_phi, mu1_charge, mu2_pt, mu2_...
#>
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.Guessing works most of the time, and fails in ways that matter: a column of detector IDs with leading zeros, read as numbers, silently loses them. The cure is to state the types. col_types accepts a full specification, as in Chapter 11, or a compact string with one letter per column, i for integer, d for double, c for character, l for logical:
dimuon <- read_csv("data/dimuon.csv.gz", col_types = "iidddidddi")
dimuon
#> # A tibble: 119,528 × 10
#> run event mu1_pt mu1_eta mu1_phi mu1_charge mu2_pt mu2_eta mu2_phi
#> <int> <int> <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 2301 1 11.3 1.49 1.64 1 5.53 1.96 1.86
#> 2 2301 2 24.3 0.286 -0.640 1 4.77 0.223 -0.357
#> 3 2301 3 13.4 -1.45 -3.01 1 12.0 -1.59 2.89
#> 4 2301 4 19.1 0.149 1.72 1 16.6 -0.034 1.93
#> 5 2301 5 11.8 -2.21 2.19 1 7.29 -2.26 1.97
#> 6 2301 6 11.1 1.39 1.08 1 4.57 1.37 0.635
#> 7 2301 7 14.5 -0.637 2.99 1 5.03 -0.813 -3.11
#> 8 2301 8 16.7 0.246 1.60 1 11.4 0.391 1.32
#> 9 2301 9 6.92 0.113 1.25 -1 4.55 -0.432 1.50
#> 10 2301 10 16.4 2.35 -2.08 -1 12.7 2.17 -1.95
#> # ℹ 119,518 more rows
#> # ℹ 1 more variable: mu2_charge <int>Precision is the second thing to watch. Text holds numbers as decimal digits, and a double needs up to 17 significant digits to be written down exactly. readr’s write_csv() writes enough digits; base R’s write.csv() writes 15, which is not always enough. Reading has a subtlety too. readr’s parser is built for speed, and for full-precision doubles it does not always return exactly the number that was written. Here a hundred thousand random doubles go through a round trip, and the fraction that come back bit-for-bit identical is counted:
set.seed(4180)
random_doubles <- tibble(x = rnorm(1e5) * 10^runif(1e5, -5, 5))
write_csv(random_doubles, "scratch/random.csv")
back <- read_csv("scratch/random.csv", col_types = "d")
mean(back$x == random_doubles$x)
#> [1] 0.77032The ones that differ are off by one unit in the last binary place, about one part in 1016, far below any physical significance. And for measured data written at its real precision, the round trip is exact. The dimuon file stores momenta to 1 MeV and angles to 10−4, so every value has a short decimal form, and every value comes back identical:
write_csv(dimuon, "scratch/dimuon.csv")
all.equal(dimuon, read_csv("scratch/dimuon.csv", col_types = "iidddidddi"))
#> [1] TRUEThat is the second time the lesson of Chapter 4 has paid off. Write numbers with the precision you measured, and plain text stores them exactly, compactly and forever.
For archives, a gzip-compressed CSV file with a short text file beside it describing each column and its units is the most durable dataset there is. Nothing about it depends on R, on a package, or on any software that might disappear.
12.3 RDS: R’s own format
saveRDS() writes any single R object to a file, and readRDS() reads it back. Unlike CSV, RDS keeps everything: column types, factor levels, dates and time zones, attributes, and objects that are not tables at all, such as a fitted model, a list of results or a function.
saveRDS(dimuon, "scratch/dimuon.rds")
all.equal(readRDS("scratch/dimuon.rds"), dimuon)
#> [1] TRUE(identical() would say FALSE here, for a technical reason worth knowing: readr attaches to each table a pointer to its record of parsing problems, and a pointer into memory cannot survive a trip through a file. all.equal() compares what matters, the data and its types.)
By default RDS files are compressed with gzip, and the compress argument selects another method: "bzip2", "xz", or, since R 4.5 on builds that support it, "zstd". The choice is the one Part II prepared you for:
time_rds <- function(compress) {
path <- tempfile(fileext = ".rds")
write_s <- system.time(saveRDS(dimuon, path, compress = compress))[["elapsed"]]
read_s <- system.time(readRDS(path))[["elapsed"]]
tibble(
compress = as.character(compress),
megabytes = file.size(path) / 1e6,
write_s = write_s,
read_s = read_s
)
}
list(FALSE, "gzip", "bzip2", "xz", "zstd") |>
map(time_rds) |>
list_rbind()
#> # A tibble: 5 × 4
#> compress megabytes write_s read_s
#> <chr> <dbl> <dbl> <dbl>
#> 1 FALSE 7.65 0.0200 0
#> 2 gzip 2.49 0.300 0.01000
#> 3 bzip2 1.73 0.49 0.250
#> 4 xz 1.62 2.74 0.0600
#> 5 zstd 2.11 0.25 0.0200For data you save and reload often, zstd is the natural choice: the fastest of the compressed options to write, fast to read, and smaller than gzip. bzip2 and xz make files about a quarter smaller again, and xz pays for it with by far the slowest writes, which is a good trade only for a file you will write once and keep.
The catch is in the format’s name: it is R’s. Only R reads RDS files, apart from a few third-party libraries in other languages that read some of them. And R’s own documentation is candid about the longer term. The help page for serialize(), the function underneath saveRDS(), warns that the format may change in future versions of R, and says that it “should not be used for long-term storage of R objects”. In practice R has been careful: the current format, version 3, has been the default since R 3.6.0, and R still reads version 2 files from the early 2000s. But careful is not guaranteed.
So use RDS for what only RDS can do: saving R objects between steps of an analysis, caching an expensive result, or storing a fitted model. For a table you want to keep, or to share with anyone who might not use R, use CSV or Parquet.
12.4 Choosing
| Format | Readable by | Keeps types | Compression | Best for |
|---|---|---|---|---|
CSV, .csv.gz |
Everything, forever | No; declare them with col_types |
gzip, bzip2, xz by extension | Archives and sharing, at measured precision |
| RDS | R | Every R type and object | gzip (default), bzip2, xz, zstd | Saving R objects between steps, fitted models |
| Parquet | R, Python, Julia, DuckDB, Spark and more | Yes | Per column: Snappy, gzip, zstd and others | Analysis and sharing of tables of any size |
The last row is the subject of the next chapter.
12.5 Summary
CSV is the most durable format there is: plain text, readable by anything, and exact for numbers written at their measured precision, though readers must be told the column types. readr writes enough digits to round-trip a double, while its fast parser can be off by one unit in the last place for full-precision values. RDS stores any R object exactly, with a choice of gzip, bzip2, xz or zstd compression, but only R reads it, and R’s own documentation advises against relying on it for long-term storage. Use CSV for archives, RDS for R objects between steps, and Parquet, next, for everything in between.
12.6 Exercises
- Read the star catalog with
read_csv()and look at the column specification it guesses withspec(). Write a compactcol_typesstring that makessource_idan integer and everything else a double. - Write
random_doubleswith base R’swrite.csv()and read it back withread.csv(). What fraction of the values survive exactly? Look at the file to see why. - Round
random_doubles$xto 6 significant digits withsignif(), then repeat the readr round trip. What fraction survives now? - Fit a straight line to the magnetometer’s
bx_ntagainst time withlm()and save the fitted model withsaveRDS(). Read it back and usepredict()on it. Why would this be awkward with CSV? - Compare the size of the dimuon table saved with
saveRDS(compress = "xz")with the gzipped CSV indata/. Which is smaller, and why might that be?