Skip to main content

7  Transforming Data with dplyr

Raw lab data is never the table you want. You timed ten swings, but you need the period. You took three trials, but you need their mean and some idea of how much they disagree. dplyr is the tidyverse package for getting from the first table to the second. It is built around a handful of functions, called verbs, that each do one job.

Load the tidyverse and read the pendulum data into a tibble, as in Chapter 6:

library(tidyverse)

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

Every dplyr verb works the same way. The first argument is a data frame, the remaining arguments say what to do using bare column names (no pendulum$, no quotes), and the result is a new data frame. The original is never changed. If you want to keep a result, assign it to a name.

7.1 Keeping rows with filter()

filter() keeps the rows where a condition is true. The conditions are the comparisons from Chapter 3, written with column names:

pendulum |>
  filter(length_m == 0.5)
#> # A tibble: 3 × 3
#>   length_m trial time_10_s
#>      <dbl> <dbl>     <dbl>
#> 1      0.5     1      14.2
#> 2      0.5     2      14.1
#> 3      0.5     3      14.2

Combine conditions with & (and) or | (or). Separating conditions with a comma also means “and”.

pendulum |>
  filter(length_m > 0.8 & trial == 1)
#> # A tibble: 2 × 3
#>   length_m trial time_10_s
#>      <dbl> <dbl>     <dbl>
#> 1      0.9     1      19.0
#> 2      1       1      20.0

To match any of several values, %in% is tidier than a chain of |:

pendulum |>
  filter(length_m %in% c(0.2, 1.0), trial != 2)
#> # A tibble: 4 × 3
#>   length_m trial time_10_s
#>      <dbl> <dbl>     <dbl>
#> 1      0.2     1      8.98
#> 2      0.2     3      8.99
#> 3      1       1     20.0 
#> 4      1       3     20.0

7.2 Keeping columns with select()

select() keeps the columns you name, in the order you name them. A minus sign drops a column instead.

pendulum |>
  select(length_m, time_10_s)
#> # A tibble: 27 × 2
#>    length_m time_10_s
#>       <dbl>     <dbl>
#>  1      0.2      8.98
#>  2      0.2      8.95
#>  3      0.2      8.99
#>  4      0.3     11.1 
#>  5      0.3     11.0 
#>  6      0.3     10.9 
#>  7      0.4     12.7 
#>  8      0.4     12.6 
#>  9      0.4     12.8 
#> 10      0.5     14.2 
#> # ℹ 17 more rows

pendulum |> select(-trial) gives the same table. A data logger will happily give you forty columns, and you will want five of them.

rename() keeps every column and changes a name. The new name goes on the left:

pendulum |>
  rename(swing_time_s = time_10_s)
#> # A tibble: 27 × 3
#>    length_m trial swing_time_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

7.3 Adding columns with mutate()

mutate() adds new columns computed from existing ones. The period is the time for ten swings divided by ten:

pendulum <- pendulum |>
  mutate(period_s = time_10_s / 10)

This is the first time the result has been assigned back to pendulum, so this is the first change that sticks.

For small swings the period of a simple pendulum is \(T = 2\pi\sqrt{L/g}\). Solve for \(g\) and every row of the table becomes a measurement of the acceleration due to gravity:

\[ g = \frac{4\pi^2 L}{T^2} \]

pendulum <- pendulum |>
  mutate(g_m_s2 = 4 * pi^2 * length_m / period_s^2)

pendulum
#> # A tibble: 27 × 5
#>    length_m trial time_10_s period_s g_m_s2
#>       <dbl> <dbl>     <dbl>    <dbl>  <dbl>
#>  1      0.2     1      8.98    0.898   9.79
#>  2      0.2     2      8.95    0.895   9.86
#>  3      0.2     3      8.99    0.899   9.77
#>  4      0.3     1     11.1     1.11    9.66
#>  5      0.3     2     11.0     1.10    9.88
#>  6      0.3     3     10.9     1.09    9.90
#>  7      0.4     1     12.7     1.27    9.82
#>  8      0.4     2     12.6     1.27    9.87
#>  9      0.4     3     12.8     1.28    9.70
#> 10      0.5     1     14.2     1.42    9.79
#> # ℹ 17 more rows

A column created inside a mutate() call can be used later in the same call, so the two steps could have been one.

7.4 Sorting with arrange()

arrange() sorts the rows, smallest first. Wrap a column in desc() to sort largest first:

pendulum |>
  arrange(desc(g_m_s2))
#> # A tibble: 27 × 5
#>    length_m trial time_10_s period_s g_m_s2
#>       <dbl> <dbl>     <dbl>    <dbl>  <dbl>
#>  1      0.3     3     10.9     1.09    9.90
#>  2      0.9     1     19.0     1.90    9.89
#>  3      0.3     2     11.0     1.10    9.88
#>  4      0.5     2     14.1     1.41    9.87
#>  5      0.4     2     12.6     1.27    9.87
#>  6      1       1     20.0     2.00    9.86
#>  7      0.6     1     15.5     1.55    9.86
#>  8      0.2     2      8.95    0.895   9.86
#>  9      0.9     2     19.0     1.90    9.85
#> 10      0.7     1     16.8     1.68    9.84
#> # ℹ 17 more rows

The largest single estimate of \(g\) is 9.90 m/s² and the smallest, which arrange(g_m_s2) puts at the top, is 9.66 m/s². Nothing is wildly off, which is worth knowing before you average anything.

7.5 Collapsing rows with summarise()

summarise() reduces a table to a single row of summary values. You name each summary and say how to compute it. The helper n() counts the rows.

pendulum |>
  summarise(
    mean_g = mean(g_m_s2),
    sd_g   = sd(g_m_s2),
    n      = n()
  )
#> # A tibble: 1 × 3
#>   mean_g   sd_g     n
#>    <dbl>  <dbl> <int>
#> 1   9.82 0.0530    27

More often you want one row per something: per length, per trial, per sample. The .by argument names the column that defines the groups, and summarise() then produces one row for each distinct value in it.

pendulum |>
  summarise(mean_time_10_s = mean(time_10_s), .by = length_m)
#> # A tibble: 9 × 2
#>   length_m mean_time_10_s
#>      <dbl>          <dbl>
#> 1      0.2           8.97
#> 2      0.3          11.0 
#> 3      0.4          12.7 
#> 4      0.5          14.2 
#> 5      0.6          15.5 
#> 6      0.7          16.8 
#> 7      0.8          17.9 
#> 8      0.9          19.0 
#> 9      1            20.0

That is the job aggregate() did in Chapter 5, written so you can read it.

Notegroup_by() in older code

.by arrived in dplyr 1.1.0, in 2023. Code written before that, and plenty written since, does the same job with a separate step: pendulum |> group_by(length_m) |> summarise(...). The results are the same. This book uses .by throughout.

7.6 The payoff: a summary table with uncertainties

Three trials at each length give you three things: a best estimate of the period (the mean), a measure of the scatter between trials (the standard deviation \(s\)), and the uncertainty in the mean itself, the standard error \(s/\sqrt{n}\). The standard error is the number that belongs after the \(\pm\) in a lab report and on the error bars of a plot.

One summarise() computes all of them. Start from the file so the whole calculation is in one place:

pendulum_summary <- read_csv("data/pendulum.csv", show_col_types = FALSE) |>
  mutate(period_s = time_10_s / 10) |>
  summarise(
    period_sd = sd(period_s),
    n         = n(),
    period_s  = mean(period_s),
    period_se = period_sd / sqrt(n),
    .by = length_m
  ) |>
  select(length_m, period_s, period_sd, period_se, n)

pendulum_summary
#> # A tibble: 9 × 5
#>   length_m period_s period_sd period_se     n
#>      <dbl>    <dbl>     <dbl>     <dbl> <int>
#> 1      0.2    0.897   0.00208  0.00120      3
#> 2      0.3    1.10    0.00723  0.00418      3
#> 3      0.4    1.27    0.00569  0.00328      3
#> 4      0.5    1.42    0.00300  0.00173      3
#> 5      0.6    1.55    0.00321  0.00186      3
#> 6      0.7    1.68    0.00173  0.001000     3
#> 7      0.8    1.79    0.00153  0.000882     3
#> 8      0.9    1.90    0.00351  0.00203      3
#> 9      1      2.00    0.00351  0.00203      3

Read it top to bottom: read the file, compute the period, then for each length compute the standard deviation, the count, the mean, and the standard error, and finally put the columns in a sensible order. The next two chapters and the report in Chapter 12 all start by building pendulum_summary, with as many of these columns as they need.

WarningOrder matters inside summarise()

Like mutate(), summarise() can use a summary it has just made, which is how period_se uses period_sd and n. It also means that once you write period_s = mean(period_s), the name period_s refers to the mean, a single number, and sd(period_s) after that line would be NA. That is why the standard deviation is computed first here.

The standard errors are a few milliseconds, from about 0.001 s to 0.004 s. Timing ten swings instead of one is what makes them that small.

Now the result of the experiment. Each row of pendulum_summary gives an estimate of \(g\), and the mean of the nine, with its standard error, is the answer:

g_result <- pendulum_summary |>
  mutate(g_m_s2 = 4 * pi^2 * length_m / period_s^2) |>
  summarise(
    g_mean = mean(g_m_s2),
    g_se   = sd(g_m_s2) / sqrt(n())
  )

g_result
#> # A tibble: 1 × 2
#>   g_mean    g_se
#>    <dbl>   <dbl>
#> 1   9.82 0.00582

The mean is 9.82 m/s² with a standard error of 0.006 m/s². Quoted to two decimal places that is \(g = 9.82 \pm 0.01\) m/s², consistent with the standard value of 9.81 m/s². Chapter 9 gets \(g\) the way most lab manuals ask for it, from the slope of a fitted line.

7.7 Counting with count()

count() is a shortcut for the most common summary of all, the number of rows in each group. It is a good check that the data has the shape you think it has:

pendulum |>
  count(trial)
#> # A tibble: 3 × 2
#>   trial     n
#>   <dbl> <int>
#> 1     1     9
#> 2     2     9
#> 3     3     9

Nine measurements in each trial, so nothing is missing.

7.8 Joining two tables

Sometimes the information you need is in a second table. Suppose the short strings were swung at bench A and the long ones at bench B, and that was written down separately:

benches <- tibble(
  length_m = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0),
  bench    = c("A", "A", "A", "A", "B", "B", "B", "B", "B")
)

pendulum_summary |>
  left_join(benches, by = "length_m") |>
  select(length_m, period_s, bench)
#> # A tibble: 9 × 3
#>   length_m period_s bench
#>      <dbl>    <dbl> <chr>
#> 1      0.2    0.897 A    
#> 2      0.3    1.10  A    
#> 3      0.4    1.27  A    
#> 4      0.5    1.42  A    
#> 5      0.6    1.55  B    
#> 6      0.7    1.68  B    
#> 7      0.8    1.79  B    
#> 8      0.9    1.90  B    
#> 9      1      2.00  B

left_join() keeps every row of the left-hand table and attaches the matching columns from the right-hand one, matching rows on the key column named in by. A row with no match gets NA.

7.9 Saving the result

write_csv() is readr’s counterpart to read_csv(). It never writes row names, so there is nothing to switch off:

write_csv(pendulum_summary, "data/pendulum_summary.csv")

You now have a table of periods with uncertainties, built by a short script you can rerun whenever the data changes. Chapter 8 turns it into a plot, error bars included.