Skip to main content

6  Meet the Tidyverse

Everything so far has been base R: the functions that come with the language. The rest of this book leans on the tidyverse, a set of packages written to work together. They share one design: data lives in a table, functions take a table as their first argument and return a table, and names say what the function does.

This chapter is vocabulary: the tibble, reading a file, the pipe, and what “tidy” means. The next three chapters put it to work.

6.1 Loading the tidyverse

You installed the tidyverse in Chapter 1. Load it at the top of every session or script:

library(tidyverse)
#> ── Attaching core tidyverse packages ──────────────────── tidyverse 2.0.0 ──
#> ✔ dplyr     1.2.1     ✔ readr     2.2.0
#> ✔ forcats   1.0.1     ✔ stringr   1.6.0
#> ✔ ggplot2   4.0.3     ✔ tibble    3.3.1
#> ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
#> ✔ purrr     1.2.2     
#> ── Conflicts ────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()
#> ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

That message is not an error. It has two parts.

The first part lists the nine core packages that library(tidyverse) attached, with their versions. The ones this book uses are readr (reading files), tibble (a better data frame), tidyr (reshaping tables), dplyr (transforming tables, Chapter 7), and ggplot2 (plotting, Chapter 8). You can ignore the rest until you need them.

The second part, under “Conflicts”, says that two functions in dplyr have the same names as functions already loaded from base R. dplyr::filter() masks stats::filter() means that from now on, typing filter() gets you the dplyr one. That is the one you want.

The double colon is worth knowing on its own. package::function() names exactly one function from exactly one package, whether or not the package is loaded.

6.2 Tibbles

A tibble is the tidyverse’s version of the data frame from Chapter 5. You build one with tibble(), the same way you would use data.frame():

drop_test <- tibble(
  ball     = c("steel", "wood", "cork"),
  mass_kg  = c(0.0283, 0.0026, 0.0009),
  bounces  = c(3L, 5L, 2L),
  time_s   = c(0.452, 0.455, 0.471)
)
drop_test
#> # A tibble: 3 × 4
#>   ball  mass_kg bounces time_s
#>   <chr>   <dbl>   <int>  <dbl>
#> 1 steel  0.0283       3  0.452
#> 2 wood   0.0026       5  0.455
#> 3 cork   0.0009       2  0.471

The printout has more in it than a data frame’s. The first line gives the size: 3 rows by 4 columns. Under each column name is its type: <chr> for character (text), <dbl> for double (an ordinary decimal number, what class() calls numeric), and <int> for integer. The L in 3L is how you type an integer; a plain 3 is a double. A column you expected to be <dbl> showing up as <chr> is the most common sign that something in a data file is wrong.

The other difference appears with larger tables. A data frame prints as many rows as it can, which for a thousand-row table buries your Console. A tibble prints the first ten and tells you how many it left out.

Otherwise a tibble is a data frame. $ pulls out a column, nrow() counts rows, and nearly any function that wants a data frame will take a tibble.

6.3 Reading a file with read_csv()

The readr package provides read_csv(), with an underscore, as the tidyverse counterpart of base R’s read.csv(), with a dot. Here it is on the pendulum data from Chapter 5:

pendulum <- read_csv("data/pendulum.csv")
#> Rows: 27 Columns: 3
#> ── Column specification ────────────────────────────────────────────────────
#> Delimiter: ","
#> dbl (3): length_m, trial, time_10_s
#> 
#> ℹ 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.

read_csv() reports what it found: 27 rows, 3 columns, comma-delimited, and all three columns read as dbl. It reads every number as a double, including the whole-number trial column that read.csv() called int. Read the report once to check that numbers came in as numbers. When you are tired of seeing it, add show_col_types = FALSE. Like read.csv(), read_csv() also accepts a web address.

pendulum <- read_csv("data/pendulum.csv", show_col_types = FALSE)
pendulum
#> # A tibble: 27 × 3
#>    length_m trial time_10_s
#>       <dbl> <dbl>     <dbl>
#>  1      0.2     1      8.98
#>  2      0.2     2      8.95
#>  3      0.2     3      8.99
#>  4      0.3     1     11.1 
#>  5      0.3     2     11.0 
#>  6      0.3     3     10.9 
#>  7      0.4     1     12.7 
#>  8      0.4     2     12.6 
#>  9      0.4     3     12.8 
#> 10      0.5     1     14.2 
#> # ℹ 17 more rows

The result is a tibble, so it prints ten rows and notes that 17 more exist.

For a second view of the same table, glimpse() turns it on its side: one line per column, with the type and as many values as fit.

glimpse(pendulum)
#> Rows: 27
#> Columns: 3
#> $ length_m  <dbl> 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.5, 0…
#> $ trial     <dbl> 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1,…
#> $ time_10_s <dbl> 8.98, 8.95, 8.99, 11.07, 10.95, 10.94, 12.68, 12.65, 12.…

With thirty columns, glimpse() is the only way to see them all at once.

6.4 The pipe

Suppose you measured the speed of a cart five times and want the root-mean-square speed, rounded to two decimals. Square, take the mean, take the square root, round:

speed_m_s <- c(1.82, 1.95, 1.77, 2.04, 1.88)

round(sqrt(mean(speed_m_s^2)), 2)
#> [1] 1.89

That works, but you have to read it from the inside out. The pipe, written |>, lets you write the steps in the order they happen:

speed_m_s^2 |>
  mean() |>
  sqrt() |>
  round(2)
#> [1] 1.89

The rule is short. x |> f(y) means f(x, y): the pipe takes whatever is on its left and hands it to the function on its right as the first argument. Any other arguments stay where you wrote them, which is why round(2) still rounds to two places. Read |> aloud as “then”: square the speeds, then take the mean, then the square root, then round.

The pipe earns its keep with tables. Every tidyverse function takes the table first, so a table can flow down a column of steps, one per line:

pendulum |>
  head(3)
#> # A tibble: 3 × 3
#>   length_m trial time_10_s
#>      <dbl> <dbl>     <dbl>
#> 1      0.2     1      8.98
#> 2      0.2     2      8.95
#> 3      0.2     3      8.99

In RStudio, Ctrl+Shift+M (Cmd+Shift+M on a Mac) types a pipe for you. Check which one it types: under Tools → Global Options → Code, tick “Use native pipe operator, |>”.

NoteThe other pipe

The native pipe arrived with R 4.1 in 2021. Older code, and plenty of newer code, uses %>%, a pipe that comes from a package called magrittr rather than from R itself. For everything in this book the two behave the same. If you meet %>% in an old script or a forum answer, read it as |>.

6.5 Tidy data

The same measurements can be laid out in a table many ways. The tidyverse expects one of them, called tidy data, defined by three rules:

  1. Every column is a variable.
  2. Every row is an observation.
  3. Every cell is a single value.

Here is how a lab notebook usually records part of the pendulum experiment, with one column per trial:

notebook <- tibble(
  length_m = c(0.2, 0.3, 0.4),
  trial_1  = c(8.98, 11.07, 12.68),
  trial_2  = c(8.95, 10.95, 12.65),
  trial_3  = c(8.99, 10.94, 12.76)
)
notebook
#> # A tibble: 3 × 4
#>   length_m trial_1 trial_2 trial_3
#>      <dbl>   <dbl>   <dbl>   <dbl>
#> 1      0.2    8.98    8.95    8.99
#> 2      0.3   11.1    11.0    10.9 
#> 3      0.4   12.7    12.6    12.8

This is easy to write by hand and it is not tidy. Each row holds three observations, not one. The variable “trial number” is hiding in the column names, and the variable “time” is spread over three columns. Ask for a plot of time against length, and there is no single column to point at.

pivot_longer() from tidyr fixes it. You say which columns to gather, what to call the new column that holds their names, and what to call the new column that holds their values:

notebook |>
  pivot_longer(
    cols      = c(trial_1, trial_2, trial_3),
    names_to  = "trial",
    values_to = "time_10_s"
  )
#> # A tibble: 9 × 3
#>   length_m trial   time_10_s
#>      <dbl> <chr>       <dbl>
#> 1      0.2 trial_1      8.98
#> 2      0.2 trial_2      8.95
#> 3      0.2 trial_3      8.99
#> 4      0.3 trial_1     11.1 
#> 5      0.3 trial_2     11.0 
#> 6      0.3 trial_3     10.9 
#> 7      0.4 trial_1     12.7 
#> 8      0.4 trial_2     12.6 
#> 9      0.4 trial_3     12.8

Three rows of three trials became nine rows, one per measurement. The trial labels came from column names, so they are text (<chr>). Now there is one time column, and every tool in the next chapters can use it. pivot_wider() is the inverse.

TipRecord it tidy in the first place

When you set up a spreadsheet for a lab, give it one row per measurement and one column per quantity, with the unit in the column name. pendulum.csv is already laid out this way, which is why it needed no reshaping.

You now have the nouns: a tibble holding tidy data, read from a file, passed along by a pipe. Chapter 7 supplies the verbs.