2021-02-22 19:47:39 +08:00
# Data transformation {#data-transform}
2015-12-12 02:34:20 +08:00
2016-07-14 23:46:37 +08:00
## Introduction
2021-02-21 23:40:40 +08:00
Visualisation is an important tool for insight generation, but it is rare that you get the data in exactly the right form you need.
Often you'll need to create some new variables or summaries, or maybe you just want to rename the variables or reorder the observations in order to make the data a little easier to work with.
You'll learn how to do all that (and more!) in this chapter, which will teach you how to transform your data using the dplyr package and a new dataset on flights departing New York City in 2013.
2015-12-09 00:28:54 +08:00
2016-07-08 23:31:52 +08:00
### Prerequisites
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
In this chapter we're going to focus on how to use the dplyr package, another core member of the tidyverse.
We'll illustrate the key ideas using data from the nycflights13 package, and use ggplot2 to help us understand the data.
2015-12-09 00:28:54 +08:00
2016-10-04 20:49:10 +08:00
```{r setup, message = FALSE}
2015-12-09 00:28:54 +08:00
library(nycflights13)
2016-10-04 01:30:24 +08:00
library(tidyverse)
2015-12-14 23:45:41 +08:00
```
2021-02-21 23:40:40 +08:00
Take careful note of the conflicts message that's printed when you load the tidyverse.
It tells you that dplyr overwrites some functions in base R.
If you want to use the base version of these functions after loading dplyr, you'll need to use their full names: `stats::filter()` and `stats::lag()`.
2016-07-22 22:15:55 +08:00
2016-07-14 23:46:37 +08:00
### nycflights13
2015-12-14 23:45:41 +08:00
2021-02-21 23:40:40 +08:00
To explore the basic data manipulation verbs of dplyr, we'll use `nycflights13::flights`.
This data frame contains all `r format(nrow(nycflights13::flights), big.mark = ",")` flights that departed from New York City in 2013.
The data comes from the US [Bureau of Transportation Statistics](http://www.transtats.bts.gov/DatabaseInfo.asp?DB_ID=120&Link=0), and is documented in `?flights`.
2015-12-14 23:45:41 +08:00
```{r}
2016-07-08 23:31:52 +08:00
flights
2015-12-14 23:45:41 +08:00
```
2021-02-21 23:40:40 +08:00
You might notice that this data frame prints a little differently from other data frames you might have used in the past: it only shows the first few rows and all the columns that fit on one screen.
2021-03-29 21:58:27 +08:00
It also displays the number of rows (`r format(nrow(nycflights13::flights), big.mark = ",")`) and columns (`r ncol(nycflights13::flights)`).
2021-02-21 23:40:40 +08:00
(To see the whole dataset, you can run `View(flights)` which will open the dataset in the RStudio viewer).
It prints differently because it's a **tibble**.
Tibbles are data frames, but slightly tweaked to work better in the tidyverse.
2021-03-29 21:58:27 +08:00
For now, you don't need to worry about the differences; we'll come back to tibbles in more detail in Chapter \@ref(tibbles).
2015-12-14 23:45:41 +08:00
2021-02-21 23:40:40 +08:00
You might also have noticed the row of three (or four) letter abbreviations under the column names.
These describe the type of each variable:
2016-10-04 05:08:44 +08:00
2021-02-21 23:40:40 +08:00
- `int` stands for integers.
2016-10-04 05:08:44 +08:00
2021-02-21 23:40:40 +08:00
- `dbl` stands for doubles, or real numbers.
2016-01-04 22:43:33 +08:00
2021-03-29 21:58:27 +08:00
- `chr` stands for characters, or strings.
2021-02-21 23:40:40 +08:00
- `dttm` stands for date-times (a date + a time).
2016-10-04 05:08:44 +08:00
There are three other common types of variables that aren't used in this dataset but you'll encounter later in the book:
2021-02-21 23:40:40 +08:00
- `lgl` stands for logical, vectors that contain only `TRUE` or `FALSE`.
2016-10-04 05:08:44 +08:00
2021-02-21 23:40:40 +08:00
- `fctr` stands for factors, which R uses to represent categorical variables with fixed possible values.
2016-10-04 05:08:44 +08:00
2021-02-21 23:40:40 +08:00
- `date` stands for dates.
2016-10-04 05:08:44 +08:00
2016-10-04 20:49:10 +08:00
### dplyr basics
2015-12-14 23:45:41 +08:00
2016-08-16 20:11:45 +08:00
In this chapter you are going to learn the five key dplyr functions that allow you to solve the vast majority of your data manipulation challenges:
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
- Pick observations by their values (`filter()`).
- Reorder the rows (`arrange()`).
- Pick variables by their names (`select()`).
- Create new variables with functions of existing variables (`mutate()`).
- Collapse many values down to a single summary (`summarise()`).
2015-12-14 23:45:41 +08:00
2021-02-21 23:40:40 +08:00
These can all be used in conjunction with `group_by()` which changes the scope of each function from operating on the entire dataset to operating on it group-by-group.
These six functions provide the verbs for a language of data manipulation.
2015-12-14 23:45:41 +08:00
2021-02-21 23:40:40 +08:00
All verbs work similarly:
2015-12-14 23:45:41 +08:00
1. The first argument is a data frame.
2021-02-21 23:40:40 +08:00
2. The subsequent arguments describe what to do with the data frame, using the variable names (without quotes).
3. The result is a new data frame.
2015-12-14 23:45:41 +08:00
2021-02-21 23:40:40 +08:00
Together these properties make it easy to chain together multiple simple steps to achieve a complex result.
Let's dive in and see how these verbs work.
2015-12-14 23:45:41 +08:00
## Filter rows with `filter()`
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
`filter()` allows you to subset observations based on their values.
The first argument is the name of the data frame.
The second and subsequent arguments are the expressions that filter the data frame.
For example, we can select all flights on January 1st with:
2015-12-09 00:28:54 +08:00
```{r}
filter(flights, month == 1, day == 1)
```
2015-09-21 21:41:14 +08:00
2021-02-21 23:40:40 +08:00
When you run that line of code, dplyr executes the filtering operation and returns a new data frame.
dplyr functions never modify their inputs, so if you want to save the result, you'll need to use the assignment operator, `<-`:
2016-01-01 00:24:18 +08:00
```{r}
jan1 <- filter(flights, month == 1, day == 1)
```
2021-02-21 23:40:40 +08:00
R either prints out the results, or saves them to a variable.
If you want to do both, you can wrap the assignment in parentheses:
2016-01-01 00:24:18 +08:00
```{r}
(dec25 <- filter(flights, month == 12, day == 25))
```
2015-12-14 23:45:41 +08:00
### Comparisons
2021-02-21 23:40:40 +08:00
To use filtering effectively, you have to know how to select the observations that you want using the comparison operators.
R provides the standard suite: `>`, `>=`, `<`, `<=`, `!=` (not equal), and `==` (equal).
2016-01-01 00:24:18 +08:00
2021-02-21 23:40:40 +08:00
When you're starting out with R, the easiest mistake to make is to use `=` instead of `==` when testing for equality.
When this happens you'll get an informative error:
2015-12-14 23:45:41 +08:00
2015-12-15 23:26:47 +08:00
```{r, error = TRUE}
filter(flights, month = 1)
```
2015-12-14 23:45:41 +08:00
### Exercises
2016-07-16 23:59:32 +08:00
1. Find all flights that
2015-12-14 23:45:41 +08:00
2021-02-22 01:32:37 +08:00
a. Had an arrival delay of two or more hours
b. Flew to Houston (`IAH` or `HOU`)
c. Were operated by United, American, or Delta
d. Departed in summer (July, August, and September)
e. Arrived more than two hours late, but didn't leave late
f. Were delayed by at least an hour, but made up over 30 minutes in flight
g. Departed between midnight and 6am (inclusive)
2016-07-15 00:07:51 +08:00
2021-04-19 20:56:29 +08:00
2. How many flights have a missing `dep_time`?
2021-02-21 23:40:40 +08:00
What other variables are missing?
What might these rows represent?
2015-09-21 21:41:14 +08:00
2015-12-09 00:28:54 +08:00
## Arrange rows with `arrange()`
2021-02-21 23:40:40 +08:00
`arrange()` works similarly to `filter()` except that instead of selecting rows, it changes their order.
It takes a data frame and a set of column names (or more complicated expressions) to order by.
If you provide more than one column name, each additional column will be used to break ties in the values of preceding columns:
2015-12-09 00:28:54 +08:00
```{r}
arrange(flights, year, month, day)
```
2016-04-06 08:56:21 +08:00
Use `desc()` to re-order by a column in descending order:
2015-12-09 00:28:54 +08:00
```{r}
2018-06-20 15:58:12 +08:00
arrange(flights, desc(dep_delay))
2015-12-09 00:28:54 +08:00
```
2015-12-15 23:26:47 +08:00
### Exercises
2021-03-29 21:58:27 +08:00
1. Sort `flights` to find the flights with longest departure delays.
2021-02-21 23:40:40 +08:00
Find the flights that left earliest.
2016-07-14 23:46:37 +08:00
2021-03-29 21:58:27 +08:00
2. Sort `flights` to find the fastest (highest speed) flights.
2021-02-21 23:40:40 +08:00
2021-03-29 21:58:27 +08:00
3. Which flights travelled the farthest?
2021-02-21 23:40:40 +08:00
Which travelled the shortest?
2016-07-14 23:46:37 +08:00
2016-07-26 00:28:05 +08:00
## Select columns with `select()` {#select}
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
It's not uncommon to get datasets with hundreds or even thousands of variables.
In this case, the first challenge is often narrowing in on the variables you're actually interested in.
`select()` allows you to rapidly zoom in on a useful subset using operations based on the names of the variables.
2016-07-14 23:46:37 +08:00
2016-08-26 23:14:17 +08:00
`select()` is not terribly useful with the flights data because we only have 19 variables, but you can still get the general idea:
2015-12-09 00:28:54 +08:00
```{r}
# Select columns by name
select(flights, year, month, day)
# Select all columns between year and day (inclusive)
select(flights, year:day)
# Select all columns except those from year to day (inclusive)
select(flights, -(year:day))
```
2015-12-15 23:26:47 +08:00
There are a number of helper functions you can use within `select()`:
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
- `starts_with("abc")`: matches names that begin with "abc".
- `ends_with("xyz")`: matches names that end with "xyz".
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
- `contains("ijk")`: matches names that contain "ijk".
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
- `matches("(.)\\1")`: selects variables that match a regular expression. This one matches any variables that contain repeated characters. You'll learn more about regular expressions in [strings].
- `num_range("x", 1:3)`: matches `x1`, `x2` and `x3`.
2015-12-15 23:26:47 +08:00
See `?select` for more details.
2021-02-21 23:40:40 +08:00
`select()` can be used to rename variables, but it's rarely useful because it drops all of the variables not explicitly mentioned.
Instead, use `rename()`, which is a variant of `select()` that keeps all the variables that aren't explicitly mentioned:
2015-12-06 22:02:29 +08:00
2015-12-09 00:28:54 +08:00
```{r}
2021-04-19 04:57:30 +08:00
rename(flights, tail_num = tailnum)
2015-12-09 00:28:54 +08:00
```
2015-09-21 21:41:14 +08:00
2021-03-29 21:58:27 +08:00
If you want to move certain variables to the start of the data frame but not drop the others, you can do this in two ways: using `select()` in conjunction with the `everything()` helper or using `relocate()`.
2016-07-14 23:46:37 +08:00
```{r}
select(flights, time_hour, air_time, everything())
2021-03-29 21:58:27 +08:00
relocate(flights, time_hour, air_time)
2016-07-14 23:46:37 +08:00
```
2016-01-08 03:46:28 +08:00
### Exercises
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
1. Brainstorm as many ways as possible to select `dep_time`, `dep_delay`, `arr_time`, and `arr_delay` from `flights`.
2. What happens if you include the name of a variable multiple times in a `select()` call?
3. What does the `any_of()` function do?
Why might it be helpful in conjunction with this vector?
2016-07-14 23:46:37 +08:00
```{r}
2021-03-29 21:58:27 +08:00
variables <- c("year", "month", "day", "dep_delay", "arr_delay")
2016-07-14 23:46:37 +08:00
```
2021-02-21 23:40:40 +08:00
4. Does the result of running the following code surprise you?
How do the select helpers deal with case by default?
How can you change that default?
2016-07-14 23:46:37 +08:00
```{r, eval = FALSE}
select(flights, contains("TIME"))
```
2015-12-15 23:26:47 +08:00
2016-01-16 07:45:13 +08:00
## Add new variables with `mutate()`
2015-09-21 21:41:14 +08:00
2021-02-21 23:40:40 +08:00
Besides selecting sets of existing columns, it's often useful to add new columns that are functions of existing columns.
That's the job of `mutate()`.
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
`mutate()` always adds new columns at the end of your dataset so we'll start by creating a narrower dataset so we can see the new variables.
Remember that when you're in RStudio, the easiest way to see all the columns is `View()`.
2015-12-06 22:02:29 +08:00
2015-12-09 00:28:54 +08:00
```{r}
2015-12-14 23:45:41 +08:00
flights_sml <- select(flights,
year:day,
ends_with("delay"),
distance,
air_time
)
mutate(flights_sml,
2018-06-20 16:00:48 +08:00
gain = dep_delay - arr_delay,
2015-12-14 23:45:41 +08:00
speed = distance / air_time * 60
)
2015-12-09 00:28:54 +08:00
```
2015-09-21 21:41:14 +08:00
2016-07-14 23:46:37 +08:00
Note that you can refer to columns that you've just created:
2015-12-09 00:28:54 +08:00
```{r}
2015-12-14 23:45:41 +08:00
mutate(flights_sml,
2018-06-20 16:00:48 +08:00
gain = dep_delay - arr_delay,
2015-12-29 23:59:14 +08:00
hours = air_time / 60,
gain_per_hour = gain / hours
2015-12-09 00:28:54 +08:00
)
```
If you only want to keep the new variables, use `transmute()`:
```{r}
2015-12-15 23:26:47 +08:00
transmute(flights,
2018-06-20 16:00:48 +08:00
gain = dep_delay - arr_delay,
2015-12-29 23:59:14 +08:00
hours = air_time / 60,
gain_per_hour = gain / hours
2015-12-09 00:28:54 +08:00
)
```
2015-12-15 23:26:47 +08:00
### Exercises
2015-12-09 00:28:54 +08:00
2015-12-15 23:26:47 +08:00
```{r, eval = FALSE, echo = FALSE}
2021-03-29 21:58:27 +08:00
# For data checking, not used in results shown in book
2015-12-15 23:26:47 +08:00
flights <- flights %>% mutate(
dep_time = hour * 60 + minute,
arr_time = (arr_time %/% 100) * 60 + (arr_time %% 100),
airtime2 = arr_time - dep_time,
dep_sched = dep_time + dep_delay
2015-12-14 23:45:41 +08:00
)
2015-12-16 23:58:52 +08:00
2015-12-15 23:26:47 +08:00
ggplot(flights, aes(dep_sched)) + geom_histogram(binwidth = 60)
ggplot(flights, aes(dep_sched %% 60)) + geom_histogram(binwidth = 1)
ggplot(flights, aes(air_time - airtime2)) + geom_histogram()
2015-12-14 23:45:41 +08:00
```
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
1. Currently `dep_time` and `sched_dep_time` are convenient to look at, but hard to compute with because they're not really continuous numbers.
Convert them to a more convenient representation of number of minutes since midnight.
2. Compare `air_time` with `arr_time - dep_time`.
What do you expect to see?
What do you see?
What do you need to do to fix it?
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
3. Compare `dep_time`, `sched_dep_time`, and `dep_delay`.
How would you expect those three numbers to be related?
2015-12-29 23:59:14 +08:00
2021-02-21 23:40:40 +08:00
4. Find the 10 most delayed flights using a ranking function.
How do you want to handle ties?
Carefully read the documentation for `min_rank()`.
2016-07-22 22:15:55 +08:00
2021-02-21 23:40:40 +08:00
5. What does `1:3 + 1:10` return?
Why?
6. What trigonometric functions does R provide?
2016-07-22 22:15:55 +08:00
2015-12-15 23:26:47 +08:00
## Grouped summaries with `summarise()`
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
The last key verb is `summarise()`.
It collapses a data frame to a single row:
2015-12-09 00:28:54 +08:00
2015-12-15 23:26:47 +08:00
```{r}
summarise(flights, delay = mean(dep_delay, na.rm = TRUE))
```
2015-12-09 00:28:54 +08:00
2016-07-30 11:05:08 +08:00
(We'll come back to what that `na.rm = TRUE` means very shortly.)
2016-07-14 23:46:37 +08:00
2021-02-21 23:40:40 +08:00
`summarise()` is not terribly useful unless we pair it with `group_by()`.
This changes the unit of analysis from the complete dataset to individual groups.
Then, when you use the dplyr verbs on a grouped data frame they'll be automatically applied "by group".
2021-03-29 21:58:27 +08:00
For example, if we applied exactly the same code to a data frame grouped by month, we get the average delay per month:
2015-12-09 00:28:54 +08:00
2015-12-15 23:26:47 +08:00
```{r}
2021-03-29 21:58:27 +08:00
by_month <- group_by(flights, month)
summarise(by_month, delay = mean(dep_delay, na.rm = TRUE))
2015-12-09 00:28:54 +08:00
```
2021-02-21 23:40:40 +08:00
Together `group_by()` and `summarise()` provide one of the tools that you'll use most commonly when working with dplyr: grouped summaries.
But before we go any further with this, we need to introduce a powerful new idea: the pipe.
2015-12-15 23:26:47 +08:00
2015-12-29 23:59:14 +08:00
### Combining multiple operations with the pipe
2015-12-16 23:58:52 +08:00
2021-02-21 23:40:40 +08:00
Imagine that we want to explore the relationship between the distance and average delay for each location.
Using what you know about dplyr, you might write code like this:
2015-12-16 23:58:52 +08:00
```{r, fig.width = 6}
by_dest <- group_by(flights, dest)
delay <- summarise(by_dest,
count = n(),
dist = mean(distance, na.rm = TRUE),
2016-07-22 22:15:55 +08:00
delay = mean(arr_delay, na.rm = TRUE)
)
2015-12-16 23:58:52 +08:00
delay <- filter(delay, count > 20, dest != "HNL")
2016-07-22 22:15:55 +08:00
# It looks like delays increase with distance up to ~750 miles
# and then decrease. Maybe as flights get longer there's more
# ability to make up delays in the air?
2016-07-15 00:07:51 +08:00
ggplot(data = delay, mapping = aes(x = dist, y = delay)) +
2015-12-16 23:58:52 +08:00
geom_point(aes(size = count), alpha = 1/3) +
geom_smooth(se = FALSE)
2015-12-15 23:26:47 +08:00
```
2016-04-06 08:56:21 +08:00
There are three steps to prepare this data:
2015-12-15 23:26:47 +08:00
2016-07-14 23:46:37 +08:00
1. Group flights by destination.
2015-09-21 21:41:14 +08:00
2021-02-21 23:40:40 +08:00
2. Summarise to compute distance, average delay, and number of flights.
2015-12-16 23:58:52 +08:00
2021-02-21 23:40:40 +08:00
3. Filter to remove noisy points and Honolulu airport, which is almost twice as far away as the next closest airport.
2015-12-16 23:58:52 +08:00
2021-03-29 21:58:27 +08:00
This code is a little frustrating to write because we have to give each intermediate data frame a name, even though we don't care about them.
2021-02-21 23:40:40 +08:00
Naming things is hard, so this slows down our analysis.
2015-12-29 23:59:14 +08:00
There's another way to tackle the same problem with the pipe, `%>%`:
2015-12-09 00:28:54 +08:00
```{r}
2021-02-22 20:59:50 +08:00
sdelays <- flights %>%
2015-12-16 23:58:52 +08:00
group_by(dest) %>%
summarise(
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE)
) %>%
2016-03-24 22:36:27 +08:00
filter(count > 20, dest != "HNL")
2015-12-09 00:28:54 +08:00
```
2021-02-21 23:40:40 +08:00
This focuses on the transformations, not what's being transformed, which makes the code easier to read.
You can read it as a series of imperative statements: group, then summarise, then filter.
As suggested by this reading, a good way to pronounce `%>%` when reading code is "then".
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
Behind the scenes, `x %>% f(y)` turns into `f(x, y)`, and `x %>% f(y) %>% g(z)` turns into `g(f(x, y), z)` and so on.
You can use the pipe to rewrite multiple operations in a way that you can read left-to-right, top-to-bottom.
2021-02-22 20:59:50 +08:00
We'll use piping frequently from now on because it considerably improves the readability of code, and we'll come back to it in more detail in Chapter \@ref(pipes).
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
Working with the pipe is one of the key criteria for belonging to the tidyverse.
The only exception is ggplot2: it was written before the pipe was discovered.
Unfortunately, the next iteration of ggplot2, ggvis, which does use the pipe, isn't quite ready for prime time yet.
2015-12-29 23:59:14 +08:00
2021-04-19 20:56:29 +08:00
## Missing values {#missing-values-summarise}
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
You may have wondered about the `na.rm` argument we used above.
What happens if we don't set it?
2015-12-17 22:46:44 +08:00
2015-12-29 23:59:14 +08:00
```{r}
flights %>%
2021-03-29 21:58:27 +08:00
group_by(month) %>%
2015-12-30 23:43:15 +08:00
summarise(mean = mean(dep_delay))
2015-12-29 23:59:14 +08:00
```
2015-12-17 22:46:44 +08:00
2021-02-21 23:40:40 +08:00
We get a lot of missing values!
That's because aggregation functions obey the usual rule of missing values: if there's any missing value in the input, the output will be a missing value.
Fortunately, all aggregation functions have an `na.rm` argument which removes the missing values prior to computation:
2015-12-29 23:59:14 +08:00
```{r}
flights %>%
2021-03-29 21:58:27 +08:00
group_by(month) %>%
2015-12-30 23:43:15 +08:00
summarise(mean = mean(dep_delay, na.rm = TRUE))
2015-12-29 23:59:14 +08:00
```
2021-03-29 21:58:27 +08:00
In this case, missing values represent cancelled flights, therefore we could also tackle the problem by first removing the cancelled flights.
2021-02-21 23:40:40 +08:00
We'll save this dataset so we can reuse it in the next few examples.
2015-12-29 23:59:14 +08:00
```{r}
2016-08-19 03:51:47 +08:00
not_cancelled <- flights %>%
filter(!is.na(dep_delay), !is.na(arr_delay))
2015-12-29 23:59:14 +08:00
not_cancelled %>%
2021-03-29 21:58:27 +08:00
group_by(month) %>%
2015-12-30 23:43:15 +08:00
summarise(mean = mean(dep_delay))
2015-12-29 23:59:14 +08:00
```
2015-12-15 23:26:47 +08:00
2021-04-19 20:56:29 +08:00
## Grouping by multiple variables
2021-03-29 21:58:27 +08:00
You can group a data frame by multiple variables as well.
Note that the grouping information is printed on top of the output.
The number in the square brackets indicates how many groups are created.
```{r}
daily <- group_by(flights, year, month, day)
daily
```
When you group by multiple variables, each summary peels off one level of the grouping by default, and a message is printed that tells you how you can change this behaviour.
```{r}
summarise(daily, flights = n())
```
If you're happy with this behaviour, you can also explicitly define it, in which case the message won't be printed out.
```{r}
summarise(daily, flights = n(), .groups = "drop_last")
```
Or you can change the default behaviour by setting a different value, e.g. `"drop"` for dropping all levels of grouping or `"keep"` for same grouping structure as `daily`.
```{r}
# Note the difference between the grouping structures
summarise(daily, flights = n(), .groups = "drop")
summarise(daily, flights = n(), .groups = "keep")
```
The fact that each summary peels off one level of the grouping by default makes it easy to progressively roll up a dataset:
```{r}
(per_day <- summarise(daily, flights = n()))
(per_month <- summarise(per_day, flights = sum(flights)))
(per_year <- summarise(per_month, flights = sum(flights)))
```
Be careful when progressively rolling up summaries: it's OK for sums and counts, but you need to think about weighting means and variances, and it's not possible to do it exactly for rank-based statistics like the median.
In other words, the sum of groupwise sums is the overall sum, but the median of groupwise medians is not the overall median.
### Ungrouping
You might also want to remove grouping outside of `summarise()`.
You can do this and return to operations on ungrouped data using `ungroup()`.
```{r}
daily %>%
ungroup() %>% # no longer grouped by date
summarise(flights = n()) # all flights
```
2015-12-16 23:58:52 +08:00
### Counts
2015-12-09 00:28:54 +08:00
2021-02-21 23:40:40 +08:00
Whenever you do any aggregation, it's always a good idea to include either a count (`n()`), or a count of non-missing values (`sum(!is.na(x))`).
That way you can check that you're not drawing conclusions based on very small amounts of data.
For example, let's look at the planes (identified by their tail number) that have the highest average delays:
2015-12-15 23:26:47 +08:00
2015-12-16 23:58:52 +08:00
```{r}
2015-12-30 23:43:15 +08:00
delays <- not_cancelled %>%
group_by(tailnum) %>%
2015-12-16 23:58:52 +08:00
summarise(
2016-07-15 00:07:51 +08:00
delay = mean(arr_delay)
2015-12-16 23:58:52 +08:00
)
2015-12-15 23:26:47 +08:00
2016-07-15 00:07:51 +08:00
ggplot(data = delays, mapping = aes(x = delay)) +
2016-07-22 22:15:55 +08:00
geom_freqpoly(binwidth = 10)
2015-12-15 23:26:47 +08:00
```
2021-02-21 23:40:40 +08:00
Wow, there are some planes that have an *average* delay of 5 hours (300 minutes)!
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
The story is actually a little more nuanced.
We can get more insight if we draw a scatterplot of number of flights vs. average delay:
2015-12-16 23:58:52 +08:00
```{r}
2015-12-30 23:43:15 +08:00
delays <- not_cancelled %>%
group_by(tailnum) %>%
2015-12-16 23:58:52 +08:00
summarise(
2021-02-09 00:29:21 +08:00
delay = mean(arr_delay),
2015-12-30 23:43:15 +08:00
n = n()
2015-12-16 23:58:52 +08:00
)
2016-07-15 00:07:51 +08:00
ggplot(data = delays, mapping = aes(x = n, y = delay)) +
2016-10-04 20:49:10 +08:00
geom_point(alpha = 1/10)
2015-12-09 00:28:54 +08:00
```
2021-02-21 23:40:40 +08:00
Not surprisingly, there is much greater variation in the average delay when there are few flights.
The shape of this plot is very characteristic: whenever you plot a mean (or other summary) vs. group size, you'll see that the variation decreases as the sample size increases.
2015-12-16 23:58:52 +08:00
2021-02-21 23:40:40 +08:00
When looking at this sort of plot, it's often useful to filter out the groups with the smallest numbers of observations, so you can see more of the pattern and less of the extreme variation in the smallest groups.
This is what the following code does, as well as showing you a handy pattern for integrating ggplot2 into dplyr flows.
It's a bit painful that you have to switch from `%>%` to `+`, but once you get the hang of it, it's quite convenient.
2015-12-17 22:46:44 +08:00
```{r}
delays %>%
filter(n > 25) %>%
2016-07-15 00:07:51 +08:00
ggplot(mapping = aes(x = n, y = delay)) +
2021-03-29 21:58:27 +08:00
geom_point(alpha = 1/10)
2015-12-17 22:46:44 +08:00
```
2021-02-21 23:40:40 +08:00
------------------------------------------------------------------------
2015-12-17 22:46:44 +08:00
2021-02-21 23:40:40 +08:00
RStudio tip: a useful keyboard shortcut is Cmd/Ctrl + Shift + P.
This resends the previously sent chunk from the editor to the console.
This is very convenient when you're (e.g.) exploring the value of `n` in the example above.
You send the whole block once with Cmd/Ctrl + Enter, then you modify the value of `n` and press Cmd/Ctrl + Shift + P to resend the complete block.
2015-12-17 22:46:44 +08:00
2021-02-21 23:40:40 +08:00
------------------------------------------------------------------------
2015-12-17 22:46:44 +08:00
2021-02-21 23:40:40 +08:00
There's another common variation of this type of pattern.
Let's look at how the average performance of batters in baseball is related to the number of times they're at bat.
Here I use data from the **Lahman** package to compute the batting average (number of hits / number of attempts) of every major league baseball player.
2016-08-01 00:32:16 +08:00
When I plot the skill of the batter (measured by the batting average, `ba`) against the number of opportunities to hit the ball (measured by at bat, `ab`), you see two patterns:
2015-12-16 23:58:52 +08:00
2021-02-21 23:40:40 +08:00
1. As above, the variation in our aggregate decreases as we get more data points.
2. There's a positive correlation between skill (`ba`) and opportunities to hit the ball (`ab`).
This is because teams control who gets to play, and obviously they'll pick their best players.
2015-12-09 00:28:54 +08:00
```{r}
2016-07-15 00:07:51 +08:00
# Convert to a tibble so it prints nicely
2016-10-04 03:10:05 +08:00
batting <- as_tibble(Lahman::Batting)
2015-12-16 23:58:52 +08:00
batters <- batting %>%
group_by(playerID) %>%
2015-12-09 00:28:54 +08:00
summarise(
2016-07-15 00:07:51 +08:00
ba = sum(H, na.rm = TRUE) / sum(AB, na.rm = TRUE),
ab = sum(AB, na.rm = TRUE)
2015-12-17 22:46:44 +08:00
)
2015-12-16 23:58:52 +08:00
2015-12-17 22:46:44 +08:00
batters %>%
filter(ab > 100) %>%
2016-07-15 00:07:51 +08:00
ggplot(mapping = aes(x = ab, y = ba)) +
2015-12-17 22:46:44 +08:00
geom_point() +
geom_smooth(se = FALSE)
2015-12-09 00:28:54 +08:00
```
2021-02-21 23:40:40 +08:00
This also has important implications for ranking.
If you naively sort on `desc(ba)`, the people with the best batting averages are clearly lucky, not skilled:
2015-12-16 23:58:52 +08:00
```{r}
2016-08-01 00:32:16 +08:00
batters %>%
arrange(desc(ba))
2015-12-09 00:28:54 +08:00
```
2015-12-17 22:46:44 +08:00
You can find a good explanation of this problem at <http://varianceexplained.org/r/empirical_bayes_baseball/> and <http://www.evanmiller.org/how-not-to-sort-by-average-rating.html>.
2015-12-16 23:58:52 +08:00
2015-12-29 23:59:14 +08:00
### Exercises
2021-02-21 23:40:40 +08:00
1. Brainstorm at least 5 different ways to assess the typical delay characteristics of a group of flights.
Consider the following scenarios:
- A flight is 15 minutes early 50% of the time, and 15 minutes late 50% of the time.
- A flight is always 10 minutes late.
- A flight is 30 minutes early 50% of the time, and 30 minutes late 50% of the time.
- 99% of the time a flight is on time.
1% of the time it's 2 hours late.
2015-12-29 23:59:14 +08:00
Which is more important: arrival delay or departure delay?
2021-02-21 23:40:40 +08:00
2. Come up with another approach that will give you the same output as `not_cancelled %>% count(dest)` and `not_cancelled %>% count(tailnum, wt = distance)` (without using `count()`).
2016-08-01 00:32:16 +08:00
2021-02-21 23:40:40 +08:00
3. Our definition of cancelled flights (`is.na(dep_delay) | is.na(arr_delay)` ) is slightly suboptimal.
Why?
Which is the most important column?
2016-07-23 00:16:50 +08:00
2021-02-21 23:40:40 +08:00
4. Look at the number of cancelled flights per day.
Is there a pattern?
2015-12-30 23:43:15 +08:00
Is the proportion of cancelled flights related to the average delay?
2021-02-21 23:40:40 +08:00
5. Which carrier has the worst delays?
Challenge: can you disentangle the effects of bad airports vs. bad carriers?
Why/why not?
(Hint: think about `flights %>% group_by(carrier, dest) %>% summarise(n())`)
2015-12-29 23:59:14 +08:00
2021-02-21 23:40:40 +08:00
6. What does the `sort` argument to `count()` do.
When might you use it?
2016-07-22 22:15:55 +08:00
2021-03-29 21:58:27 +08:00
## Grouped mutates and filters
2015-12-16 23:58:52 +08:00
2015-12-30 23:43:15 +08:00
Grouping is most useful in conjunction with `summarise()`, but you can also do convenient operations with `mutate()` and `filter()`:
2015-12-16 23:58:52 +08:00
2021-02-21 23:40:40 +08:00
- Find the worst members of each group:
2015-12-17 22:46:44 +08:00
```{r}
2016-07-22 22:15:55 +08:00
flights_sml %>%
2015-12-17 22:46:44 +08:00
group_by(year, month, day) %>%
2016-07-23 00:22:02 +08:00
filter(rank(desc(arr_delay)) < 10)
2015-12-17 22:46:44 +08:00
```
2021-02-21 23:40:40 +08:00
- Find all groups bigger than a threshold:
2015-12-17 22:46:44 +08:00
```{r}
popular_dests <- flights %>%
group_by(dest) %>%
filter(n() > 365)
2016-10-04 05:08:44 +08:00
popular_dests
2015-12-17 22:46:44 +08:00
```
2021-02-21 23:40:40 +08:00
- Standardise to compute per group metrics:
2015-12-17 22:46:44 +08:00
```{r}
popular_dests %>%
filter(arr_delay > 0) %>%
2016-07-22 22:15:55 +08:00
mutate(prop_delay = arr_delay / sum(arr_delay)) %>%
select(year:day, dest, arr_delay, prop_delay)
2015-12-17 22:46:44 +08:00
```
2021-02-21 23:40:40 +08:00
A grouped filter is a grouped mutate followed by an ungrouped filter.
I generally avoid them except for quick and dirty manipulations: otherwise it's hard to check that you've done the manipulation correctly.
2015-12-15 23:26:47 +08:00
2021-02-21 23:40:40 +08:00
Functions that work most naturally in grouped mutates and filters are known as window functions (vs. the summary functions used for summaries).
You can learn more about useful window functions in the corresponding vignette: `vignette("window-functions")`.
2015-12-18 23:53:15 +08:00
### Exercises
2021-02-21 23:40:40 +08:00
1. Refer back to the lists of useful mutate and filtering functions.
2016-01-04 22:43:33 +08:00
Describe how each operation changes when you combine it with grouping.
2021-02-21 23:40:40 +08:00
2. Which plane (`tailnum`) has the worst on-time record?
3. What time of day should you fly if you want to avoid delays as much as possible?
4. For each destination, compute the total minutes of delay.
For each flight, compute the proportion of the total delay for its destination.
5. Delays are typically temporally correlated: even once the problem that caused the initial delay has been resolved, later flights are delayed to allow earlier flights to leave.
Using `lag()`, explore how the delay of a flight is related to the delay of the immediately preceding flight.
6. Look at each destination.
Can you find flights that are suspiciously fast?
(i.e. flights that represent a potential data entry error).
Compute the air time of a flight relative to the shortest flight to that destination.
2015-12-18 23:53:15 +08:00
Which flights were most delayed in the air?
2017-05-03 21:00:32 +08:00
2021-02-21 23:40:40 +08:00
7. Find all destinations that are flown by at least two carriers.
Use that information to rank the carriers.
8. For each plane, count the number of flights before the first delay of greater than 1 hour.