The dplyr Verbs
In Lesson 1 you got Maya's bakery sales off her till, into R, and into tidy shape. The data is ready. So what do you actually DO with it? Almost every analysis is a handful of small, sharply named verbs, each doing one job to a table: keep some rows, keep some columns, add a column, sort, tally. Learn these and you can answer most questions you will ever put to a data frame.
By the end of this lesson you will be able to:
- Pick rows with
filter()and columns withselect() - Derive new columns with
mutate(), and order, dedupe and tally witharrange(),distinct()andcount() - Chain them with the pipe into one line that reads like a sentence
Prerequisites: Lesson 1, so your data is imported and tidy. No dplyr experience needed; we define every verb as it appears.
One shape in, one shape out: filter()
Here is Maya's tidy sales table from Lesson 1, six sales over three days. We will use this one table for the whole lesson.
Every dplyr verb works the same way: it is a function whose first argument is a data frame, and whose result is a brand new data frame. Table in, table out. That single rule is why the verbs snap together later.
The first verb, filter(), keeps the rows that pass a test. "Keep the busy sales" means "keep the rows where units is above 20":
The test units > 20 is checked on every row; rows where it is TRUE stay, the rest are dropped. Use == (two equals signs, "is equal to") to test a value, never a single =. Give several conditions and a row must pass them all: filter(sales, units > 20, item == "Bagel") keeps only busy Bagel sales.
filter(sales, ...) returns a new table and leaves sales exactly as it was. To keep a result, you must assign it: busy <- filter(sales, units > 20).Drag your eye down the widget: the three rows that fail units > 20 are struck out, the three that pass remain.