Group & Summarise
In Lesson 2 you learned the verbs that act on a table as a whole: filter, select, mutate, arrange. But Maya rarely wants the whole table. She wants answers about parts of it: how many of each loaf did I sell, what is the average revenue per item, which days were busy. That means splitting the table into groups, computing a number for each group, and stacking the results back together. This three-move pattern, plus labelling rows by a rule and dealing with the blanks that real data always has, is the last set of skills that turns a tidy table into an answer.
By the end of this lesson you will be able to:
- Collapse a column to one number with
summarise(), and a column per group withgroup_by() - Tag every row with a category using
case_when() - Handle missing values honestly:
na.rm, dropping the rows, or filling them in
Prerequisites: Lesson 2, so you know the dplyr verbs and the pipe. We define everything new as it appears.
summarise() turns a whole column into one number
Here is Maya's week off the till: eight sales over four days. It is the same tidy table from Lesson 2, now with the last two days added. Each lesson starts in a fresh R session, so we build it right here (run this once). Look at the final row: the revenue is NA, because Maya forgot to log that Bagel sale. Hold that thought; we deal with it at the end of the lesson.
Every verb so far returned a table with many rows. summarise() is the first verb that gives you back one row. You hand it a name and a function that reduces a whole column to a single value, and that value is all you get back:
sum(units) adds all eight counts into one total (209 loaves), and mean(units) averages them. The arithmetic mean is worth stating exactly, because it returns in a moment. For a column of values \(x_1, x_2, \dots, x_n\), where \(x_i\) is the units sold in sale \(i\) and \(n\) is the number of sales,
\[ \bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i \]
so \(\bar{x} = 209 / 8 = 26.1\). The whole point of summarise() is that many rows go in, one row comes out: the eight-row tibble above became a single summary row. In the next step you will see that collapse happen group by group.