2022-05-14 04:46:49 +08:00
# Numbers {#sec-numbers}
2022-03-17 22:46:35 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| echo: false
2023-03-07 21:52:43 +08:00
2022-05-14 04:46:49 +08:00
source("_common.R")
2022-03-17 22:46:35 +08:00
```
## Introduction
2022-11-08 07:06:29 +08:00
Numeric vectors are the backbone of data science, and you've already used them a bunch of times earlier in the book.
Now it's time to systematically survey what you can do with them in R, ensuring that you're well situated to tackle any future problem involving numeric vectors.
2022-11-17 23:56:08 +08:00
We'll start by giving you a couple of tools to make numbers if you have strings, and then going into a little more detail of `count()`.
2023-04-16 22:06:53 +08:00
Then we'll dive into various numeric transformations that pair well with `mutate()`, including more general transformations that can be applied to other types of vectors, but are often used with numeric vectors.
2022-11-19 06:07:54 +08:00
We'll finish off by covering the summary functions that pair well with `summarize()` and show you how they can also be used with `mutate()`.
2022-03-17 22:46:35 +08:00
2022-03-31 20:57:41 +08:00
### Prerequisites
This chapter mostly uses functions from base R, which are available without loading any packages.
But we still need the tidyverse because we'll use these base R functions inside of tidyverse functions like `mutate()` and `filter()`.
2022-04-15 22:08:10 +08:00
Like in the last chapter, we'll use real examples from nycflights13, as well as toy examples made with `c()` and `tribble()`.
2022-03-17 22:46:35 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| label: setup
#| message: false
2022-03-17 22:46:35 +08:00
library(tidyverse)
library(nycflights13)
```
2022-11-17 23:56:08 +08:00
## Making numbers
In most cases, you'll get numbers already recorded in one of R's numeric types: integer or double.
2022-12-01 15:11:30 +08:00
In some cases, however, you'll encounter them as strings, possibly because you've created them by pivoting from column headers or because something has gone wrong in your data import process.
2022-11-17 23:56:08 +08:00
readr provides two useful functions for parsing strings into numbers: `parse_double()` and `parse_number()`.
Use `parse_double()` when you have numbers that have been written as strings:
```{r}
x <- c("1.2", "5.6", "1e3")
parse_double(x)
```
Use `parse_number()` when the string contains non-numeric text that you want to ignore.
This is particularly useful for currency data and percentages:
```{r}
x <- c("$1,234", "USD 3,513", "59%")
parse_number(x)
```
2023-03-07 21:52:43 +08:00
## Counts {#sec-counts}
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
It's surprising how much data science you can do with just counts and a little basic arithmetic, so dplyr strives to make counting as easy as possible with `count()`.
This function is great for quick exploration and checks during analysis:
2022-03-17 22:46:35 +08:00
2022-03-18 03:15:24 +08:00
```{r}
2022-03-23 22:52:38 +08:00
flights |> count(dest)
2022-03-18 03:15:24 +08:00
```
2022-08-10 00:43:12 +08:00
(Despite the advice in @sec-workflow-style, we usually put `count()` on a single line because it's usually used at the console for a quick check that a calculation is working as expected.)
2022-03-23 22:52:38 +08:00
2022-12-01 15:11:30 +08:00
If you want to see the most common values, add `sort = TRUE`:
2022-04-15 22:08:10 +08:00
```{r}
flights |> count(dest, sort = TRUE)
```
And remember that if you want to see all the values, you can use `|> View()` or `|> print(n = Inf)`.
2022-11-19 06:07:54 +08:00
You can perform the same computation "by hand" with `group_by()`, `summarize()` and `n()`.
2022-04-15 22:08:10 +08:00
This is useful because it allows you to compute other summaries at the same time:
2022-03-23 22:52:38 +08:00
```{r}
flights |>
group_by(dest) |>
2022-11-19 06:07:54 +08:00
summarize(
2022-03-31 20:57:41 +08:00
n = n(),
delay = mean(arr_delay, na.rm = TRUE)
)
2022-03-23 22:52:38 +08:00
```
2022-09-29 23:58:31 +08:00
`n()` is a special summary function that doesn't take any arguments and instead accesses information about the "current" group.
2022-04-15 22:08:10 +08:00
This means that it only works inside dplyr verbs:
2022-03-23 22:52:38 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| error: true
2022-03-23 22:52:38 +08:00
n()
```
2023-02-28 06:42:29 +08:00
There are a couple of variants of `n()` and `count()` that you might find useful:
2022-03-23 22:52:38 +08:00
2022-03-31 20:57:41 +08:00
- `n_distinct(x)` counts the number of distinct (unique) values of one or more variables.
2022-04-15 22:08:10 +08:00
For example, we could figure out which destinations are served by the most carriers:
2022-03-17 22:46:35 +08:00
```{r}
2022-03-23 22:52:38 +08:00
flights |>
2022-03-17 22:46:35 +08:00
group_by(dest) |>
2023-01-24 23:16:09 +08:00
summarize(carriers = n_distinct(carrier)) |>
2022-03-17 22:46:35 +08:00
arrange(desc(carriers))
```
2022-04-15 22:08:10 +08:00
- A weighted count is a sum.
2022-03-23 22:52:38 +08:00
For example you could "count" the number of miles each plane flew:
2022-03-17 22:46:35 +08:00
```{r}
2022-03-23 22:52:38 +08:00
flights |>
group_by(tailnum) |>
2022-11-19 06:07:54 +08:00
summarize(miles = sum(distance))
2022-03-17 22:46:35 +08:00
```
2022-04-15 22:08:10 +08:00
Weighted counts are a common problem so `count()` has a `wt` argument that does the same thing:
2022-03-17 22:46:35 +08:00
```{r}
2023-01-24 23:16:09 +08:00
#| results: false
2022-03-23 22:52:38 +08:00
flights |> count(tailnum, wt = distance)
2022-03-17 22:46:35 +08:00
```
2022-04-15 22:08:10 +08:00
- You can count missing values by combining `sum()` and `is.na()`.
2022-09-01 19:43:57 +08:00
In the `flights` dataset this represents flights that are cancelled:
2022-03-17 22:46:35 +08:00
```{r}
2022-03-23 22:52:38 +08:00
flights |>
group_by(dest) |>
2022-11-19 06:07:54 +08:00
summarize(n_cancelled = sum(is.na(dep_time)))
2022-03-17 22:46:35 +08:00
```
2022-03-23 22:52:38 +08:00
### Exercises
2022-03-24 21:53:11 +08:00
1. How can you use `count()` to count the number rows with a missing value for a given variable?
2022-11-19 06:07:54 +08:00
2. Expand the following calls to `count()` to instead use `group_by()`, `summarize()`, and `arrange()`:
2022-03-29 21:26:18 +08:00
1. `flights |> count(dest, sort = TRUE)`
2. `flights |> count(tailnum, wt = distance)`
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
## Numeric transformations
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
Transformation functions work well with `mutate()` because their output is the same length as the input.
The vast majority of transformation functions are already built into base R.
2022-06-01 12:52:33 +08:00
It's impractical to list them all so this section will show the most useful ones.
2022-08-10 00:43:12 +08:00
As an example, while R provides all the trigonometric functions that you might dream of, we don't list them here because they're rarely needed for data science.
2022-03-17 22:46:35 +08:00
2022-09-29 23:49:03 +08:00
### Arithmetic and recycling rules {#sec-recycling}
2022-03-17 22:46:35 +08:00
2022-09-29 23:49:03 +08:00
We introduced the basics of arithmetic (`+`, `-`, `*`, `/`, `^`) in @sec-workflow-basics and have used them a bunch since.
2022-04-15 22:08:10 +08:00
These functions don't need a huge amount of explanation because they do what you learned in grade school.
But we need to briefly talk about the **recycling rules** which determine what happens when the left and right hand sides have different lengths.
This is important for operations like `flights |> mutate(air_time = air_time / 60)` because there are 336,776 numbers on the left of `/` but only one on the right.
2022-03-31 20:57:41 +08:00
2022-04-15 22:08:10 +08:00
R handles mismatched lengths by **recycling,** or repeating, the short vector.
2022-03-31 20:57:41 +08:00
We can see this in operation more easily if we create some vectors outside of a data frame:
2022-03-23 22:52:38 +08:00
```{r}
x <- c(1, 2, 10, 20)
x / 5
2022-03-24 21:53:11 +08:00
# is shorthand for
2022-03-23 22:52:38 +08:00
x / c(5, 5, 5, 5)
```
2022-04-15 22:08:10 +08:00
Generally, you only want to recycle single numbers (i.e. vectors of length 1), but R will recycle any shorter length vector.
2022-06-01 12:52:33 +08:00
It usually (but not always) gives you a warning if the longer vector isn't a multiple of the shorter:
2022-03-23 22:52:38 +08:00
```{r}
x * c(1, 2)
x * c(1, 2, 3)
```
2022-04-15 22:08:10 +08:00
These recycling rules are also applied to logical comparisons (`==`, `<`, `<=`, `>`, `>=`, `!=`) and can lead to a surprising result if you accidentally use `==` instead of `%in%` and the data frame has an unfortunate number of rows.
2022-03-24 21:53:11 +08:00
For example, take this code which attempts to find all flights in January and February:
2022-03-23 22:52:38 +08:00
```{r}
flights |>
filter(month == c(1, 2))
```
2022-03-24 21:53:11 +08:00
The code runs without error, but it doesn't return what you want.
2022-04-15 22:08:10 +08:00
Because of the recycling rules it finds flights in odd numbered rows that departed in January and flights in even numbered rows that departed in February.
2023-01-03 23:25:47 +08:00
And unfortunately there's no warning because `flights` has an even number of rows.
2022-03-23 22:52:38 +08:00
2022-04-15 22:08:10 +08:00
To protect you from this type of silent failure, most tidyverse functions use a stricter form of recycling that only recycles single values.
Unfortunately that doesn't help here, or in many other cases, because the key computation is performed by the base R function `==`, not `filter()`.
2022-03-23 22:52:38 +08:00
### Minimum and maximum
2022-03-24 21:53:11 +08:00
The arithmetic functions work with pairs of variables.
Two closely related functions are `pmin()` and `pmax()`, which when given two or more variables will return the smallest or largest value in each row:
```{r}
df <- tribble(
~x, ~y,
1, 3,
5, 2,
7, NA,
)
df |>
mutate(
2022-04-15 22:08:10 +08:00
min = pmin(x, y, na.rm = TRUE),
max = pmax(x, y, na.rm = TRUE)
2022-03-24 21:53:11 +08:00
)
```
2022-04-18 22:42:43 +08:00
Note that these are different to the summary functions `min()` and `max()` which take multiple observations and return a single value.
You can tell that you've used the wrong form when all the minimums and all the maximums have the same value:
```{r}
df |>
mutate(
min = min(x, y, na.rm = TRUE),
max = max(x, y, na.rm = TRUE)
)
```
2022-03-23 22:52:38 +08:00
### Modular arithmetic
2023-02-28 06:42:29 +08:00
Modular arithmetic is the technical name for the type of math you did before you learned about decimal places, i.e. division that yields a whole number and a remainder.
2022-04-15 22:08:10 +08:00
In R, `%/%` does integer division and `%%` computes the remainder:
2022-03-23 22:52:38 +08:00
```{r}
1:10 %/% 3
1:10 %% 3
```
2022-03-17 22:46:35 +08:00
2023-02-14 21:32:09 +08:00
Modular arithmetic is handy for the `flights` dataset, because we can use it to unpack the `sched_dep_time` variable into `hour` and `minute`:
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
```{r}
2022-03-24 21:53:11 +08:00
flights |>
mutate(
hour = sched_dep_time %/% 100,
minute = sched_dep_time %% 100,
.keep = "used"
)
2022-03-23 22:52:38 +08:00
```
2022-03-17 22:46:35 +08:00
2022-05-14 04:46:49 +08:00
We can combine that with the `mean(is.na(x))` trick from @sec-logical-summaries to see how the proportion of cancelled flights varies over the course of the day.
The results are shown in @fig-prop-cancelled.
2022-03-31 20:57:41 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| label: fig-prop-cancelled
2023-05-26 23:44:08 +08:00
#| fig-cap: |
2022-03-31 20:57:41 +08:00
#| A line plot with scheduled departure hour on the x-axis, and proportion
#| of cancelled flights on the y-axis. Cancellations seem to accumulate
#| over the course of the day until 8pm, very late flights are much
#| less likely to be cancelled.
2023-05-26 23:44:08 +08:00
#| fig-alt: |
2022-03-31 20:57:41 +08:00
#| A line plot showing how proportion of cancelled flights changes over
#| the course of the day. The proportion starts low at around 0.5% at
#| 6am, then steadily increases over the course of the day until peaking
#| at 4% at 7pm. The proportion of cancelled flights then drops rapidly
#| getting down to around 1% by midnight.
2022-03-17 22:46:35 +08:00
flights |>
group_by(hour = sched_dep_time %/% 100) |>
2022-11-19 06:07:54 +08:00
summarize(prop_cancelled = mean(is.na(dep_time)), n = n()) |>
2022-03-17 22:46:35 +08:00
filter(hour > 1) |>
2022-12-05 19:39:35 +08:00
ggplot(aes(x = hour, y = prop_cancelled)) +
2022-05-14 04:46:49 +08:00
geom_line(color = "grey50") +
2022-03-24 21:53:11 +08:00
geom_point(aes(size = n))
2022-03-17 22:46:35 +08:00
```
2022-03-31 20:57:41 +08:00
### Logarithms
2022-03-17 22:46:35 +08:00
2023-04-25 20:36:14 +08:00
Logarithms are an incredibly useful transformation for dealing with data that ranges across multiple orders of magnitude and converting exponential growth to linear growth.
2023-02-08 00:52:35 +08:00
In R, you have a choice of three logarithms: `log()` (the natural log, base e), `log2()` (base 2), and `log10()` (base 10).
2022-08-10 00:43:12 +08:00
We recommend using `log2()` or `log10()`.
2022-12-01 15:11:30 +08:00
`log2()` is easy to interpret because a difference of 1 on the log scale corresponds to doubling on the original scale and a difference of -1 corresponds to halving; whereas `log10()` is easy to back-transform because (e.g.) 3 is 10\^3 = 1000.
2022-03-31 20:57:41 +08:00
The inverse of `log()` is `exp()`; to compute the inverse of `log2()` or `log10()` you'll need to use `2^` or `10^`.
2022-03-17 22:46:35 +08:00
2022-05-14 04:46:49 +08:00
### Rounding {#sec-rounding}
2022-03-17 22:46:35 +08:00
2022-03-31 20:57:41 +08:00
Use `round(x)` to round a number to the nearest integer:
```{r}
round(123.456)
```
You can control the precision of the rounding with the second argument, `digits`.
2022-04-15 22:08:10 +08:00
`round(x, digits)` rounds to the nearest `10^-n` so `digits = 2` will round to the nearest 0.01.
This definition is useful because it implies `round(x, -3)` will round to the nearest thousand, which indeed it does:
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
```{r}
2022-03-31 20:57:41 +08:00
round(123.456, 2) # two digits
round(123.456, 1) # one digit
round(123.456, -1) # round to nearest ten
round(123.456, -2) # round to nearest hundred
2022-03-23 22:52:38 +08:00
```
2022-03-17 22:46:35 +08:00
2022-03-31 20:57:41 +08:00
There's one weirdness with `round()` that seems surprising at first glance:
2022-03-24 21:53:11 +08:00
```{r}
round(c(1.5, 2.5))
```
2022-04-15 22:08:10 +08:00
`round()` uses what's known as "round half to even" or Banker's rounding: if a number is half way between two integers, it will be rounded to the **even** integer.
This is a good strategy because it keeps the rounding unbiased: half of all 0.5s are rounded up, and half are rounded down.
2022-03-24 21:53:11 +08:00
2022-04-15 22:08:10 +08:00
`round()` is paired with `floor()` which always rounds down and `ceiling()` which always rounds up:
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
```{r}
2022-03-24 21:53:11 +08:00
x <- 123.456
2022-03-31 20:57:41 +08:00
floor(x)
ceiling(x)
```
2022-12-01 15:11:30 +08:00
These functions don't have a `digits` argument, so you can instead scale down, round, and then scale back up:
2022-03-31 20:57:41 +08:00
```{r}
2022-03-24 21:53:11 +08:00
# Round down to nearest two digits
floor(x / 0.01) * 0.01
# Round up to nearest two digits
ceiling(x / 0.01) * 0.01
2022-03-23 22:52:38 +08:00
```
2022-03-17 22:46:35 +08:00
2022-03-31 20:57:41 +08:00
You can use the same technique if you want to `round()` to a multiple of some other number:
2022-03-24 21:53:11 +08:00
```{r}
# Round to nearest multiple of 4
round(x / 4) * 4
2022-03-17 22:46:35 +08:00
2022-03-24 21:53:11 +08:00
# Round to nearest 0.25
round(x / 0.25) * 0.25
```
2022-03-17 22:46:35 +08:00
2022-08-09 02:44:06 +08:00
### Cutting numbers into ranges
2023-02-28 06:42:29 +08:00
Use `cut()`[^numbers-1] to break up (aka bin) a numeric vector into discrete buckets:
2022-08-09 02:44:06 +08:00
[^numbers-1]: ggplot2 provides some helpers for common cases in `cut_interval()`, `cut_number()`, and `cut_width()`.
ggplot2 is an admittedly weird place for these functions to live, but they are useful as part of histogram computation and were written before any other parts of the tidyverse existed.
```{r}
x <- c(1, 2, 5, 10, 15, 20)
cut(x, breaks = c(0, 5, 10, 15, 20))
```
The breaks don't need to be evenly spaced:
```{r}
cut(x, breaks = c(0, 5, 10, 100))
```
You can optionally supply your own `labels`.
Note that there should be one less `labels` than `breaks`.
```{r}
cut(x,
breaks = c(0, 5, 10, 15, 20),
labels = c("sm", "md", "lg", "xl")
)
```
Any values outside of the range of the breaks will become `NA`:
```{r}
y <- c(NA, -10, 5, 10, 30)
cut(y, breaks = c(0, 5, 10, 15, 20))
```
2022-08-09 02:58:29 +08:00
See the documentation for other useful arguments like `right` and `include.lowest`, which control if the intervals are `[a, b)` or `(a, b]` and if the lowest interval should be `[a, b]`.
2023-01-05 05:31:49 +08:00
### Cumulative and rolling aggregates {#sec-cumulative-and-rolling-aggregates}
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
Base R provides `cumsum()`, `cumprod()`, `cummin()`, `cummax()` for running, or cumulative, sums, products, mins and maxes.
dplyr provides `cummean()` for cumulative means.
Cumulative sums tend to come up the most in practice:
2022-03-17 22:46:35 +08:00
```{r}
x <- 1:10
cumsum(x)
```
2023-04-13 06:18:36 +08:00
If you need more complex rolling or sliding aggregates, try the [slider](https://slider.r-lib.org/) package.
2022-03-24 21:53:11 +08:00
### Exercises
2022-05-14 04:46:49 +08:00
1. Explain in words what each line of the code used to generate @fig-prop-cancelled does.
2022-03-24 21:53:11 +08:00
2022-04-26 21:27:48 +08:00
2. What trigonometric functions does R provide?
Guess some names and look up the documentation.
Do they use degrees or radians?
2022-04-18 22:42:43 +08:00
2022-04-26 21:27:48 +08:00
3. Currently `dep_time` and `sched_dep_time` are convenient to look at, but hard to compute with because they're not really continuous numbers.
2023-02-08 00:52:35 +08:00
You can see the basic problem by running the code below: there's a gap between each hour.
2022-04-18 22:42:43 +08:00
```{r}
2023-02-08 00:52:35 +08:00
#| eval: false
2022-04-18 22:42:43 +08:00
flights |>
filter(month == 1, day == 1) |>
2022-12-13 02:35:15 +08:00
ggplot(aes(x = sched_dep_time, y = dep_delay)) +
2022-04-18 22:42:43 +08:00
geom_point()
```
Convert them to a more truthful representation of time (either fractional hours or minutes since midnight).
2023-02-28 06:42:29 +08:00
4. Round `dep_time` and `arr_time` to the nearest five minutes.
2022-03-23 22:52:38 +08:00
## General transformations
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
The following sections describe some general transformations which are often used with numeric vectors, but can be applied to all other column types.
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
### Ranks
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
dplyr provides a number of ranking functions inspired by SQL, but you should always start with `dplyr::min_rank()`.
2023-04-10 23:22:08 +08:00
It uses the typical method for dealing with ties, e.g., 1st, 2nd, 2nd, 4th.
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
```{r}
2022-04-15 22:08:10 +08:00
x <- c(1, 2, 2, 3, 4, NA)
min_rank(x)
2022-03-23 22:52:38 +08:00
```
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
Note that the smallest values get the lowest ranks; use `desc(x)` to give the largest values the smallest ranks:
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
```{r}
min_rank(desc(x))
```
If `min_rank()` doesn't do what you need, look at the variants `dplyr::row_number()`, `dplyr::dense_rank()`, `dplyr::percent_rank()`, and `dplyr::cume_dist()`.
See the documentation for details.
```{r}
2022-04-18 22:42:43 +08:00
df <- tibble(x = x)
df |>
mutate(
row_number = row_number(x),
dense_rank = dense_rank(x),
percent_rank = percent_rank(x),
cume_dist = cume_dist(x)
)
2022-04-15 22:08:10 +08:00
```
You can achieve many of the same results by picking the appropriate `ties.method` argument to base R's `rank()`; you'll probably also want to set `na.last = "keep"` to keep `NA`s as `NA`.
2022-04-18 22:42:43 +08:00
`row_number()` can also be used without any arguments when inside a dplyr verb.
In this case, it'll give the number of the "current" row.
When combined with `%%` or `%/%` this can be a useful tool for dividing data into similarly sized groups:
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
```{r}
2023-02-28 06:42:29 +08:00
df <- tibble(id = 1:10)
2022-04-18 22:42:43 +08:00
df |>
2022-03-23 22:52:38 +08:00
mutate(
2022-04-18 22:42:43 +08:00
row0 = row_number() - 1,
2022-06-01 12:52:33 +08:00
three_groups = row0 %% 3,
2023-02-28 06:42:29 +08:00
three_in_each_group = row0 %/% 3
2022-03-23 22:52:38 +08:00
)
```
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
### Offsets
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
`dplyr::lead()` and `dplyr::lag()` allow you to refer the values just before or just after the "current" value.
2022-04-18 22:42:43 +08:00
They return a vector of the same length as the input, padded with `NA`s at the start or end:
2022-03-17 22:46:35 +08:00
2022-03-23 22:52:38 +08:00
```{r}
2022-04-15 22:08:10 +08:00
x <- c(2, 5, 11, 11, 19, 35)
2022-03-23 22:52:38 +08:00
lag(x)
lead(x)
```
2022-03-17 22:46:35 +08:00
2022-03-24 21:53:11 +08:00
- `x - lag(x)` gives you the difference between the current and previous value.
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
```{r}
x - lag(x)
```
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
- `x == lag(x)` tells you when the current value changes.
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
```{r}
x == lag(x)
```
2022-03-17 22:46:35 +08:00
2022-04-18 22:42:43 +08:00
You can lead or lag by more than one position by using the second argument, `n`.
2023-01-05 10:21:34 +08:00
### Consecutive identifiers
2022-11-19 06:30:58 +08:00
Sometimes you want to start a new group every time some event occurs.
2023-02-28 06:42:29 +08:00
For example, when you're looking at website data, it's common to want to break up events into sessions, where you begin a new session after gap of more than `x` minutes since the last activity.
2022-11-19 06:30:58 +08:00
For example, imagine you have the times when someone visited a website:
```{r}
events <- tibble(
time = c(0, 1, 2, 3, 5, 10, 12, 15, 17, 19, 20, 27, 28, 30)
)
```
2023-02-28 06:42:29 +08:00
And you've computed the time between each event, and figured out if there's a gap that's big enough to qualify:
2022-11-19 06:30:58 +08:00
```{r}
events <- events |>
mutate(
diff = time - lag(time, default = first(time)),
2023-02-28 06:42:29 +08:00
has_gap = diff >= 5
2022-11-19 06:30:58 +08:00
)
events
```
But how do we go from that logical vector to something that we can `group_by()`?
2023-02-28 06:42:29 +08:00
`cumsum()`, from @sec-cumulative-and-rolling-aggregates, comes to the rescue as gap, i.e. `has_gap` is `TRUE`, will increment `group` by one (@sec-numeric-summaries-of-logicals):
2022-11-19 06:30:58 +08:00
```{r}
events |> mutate(
2023-02-28 06:42:29 +08:00
group = cumsum(has_gap)
2022-11-19 06:30:58 +08:00
)
```
2023-01-05 05:31:49 +08:00
Another approach for creating grouping variables is `consecutive_id()`, which starts a new group every time one of its arguments changes.
2022-11-19 06:30:58 +08:00
For example, inspired by [this stackoverflow question](https://stackoverflow.com/questions/27482712), imagine you have a data frame with a bunch of repeated values:
```{r}
df <- tibble(
x = c("a", "a", "a", "b", "c", "c", "d", "e", "a", "a", "b", "b"),
y = c(1, 2, 3, 2, 4, 1, 3, 9, 4, 8, 10, 199)
)
```
2023-02-28 06:42:29 +08:00
If you want to keep the first row from each repeated `x`, you could use `group_by()`, `consecutive_id()`, and `slice_head()`:
2022-11-19 06:30:58 +08:00
```{r}
df |>
group_by(id = consecutive_id(x)) |>
slice_head(n = 1)
```
2022-03-17 22:46:35 +08:00
### Exercises
1. Find the 10 most delayed flights using a ranking function.
How do you want to handle ties?
Carefully read the documentation for `min_rank()`.
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?
2022-12-01 15:11:30 +08:00
4. What does `flights |> group_by(dest) |> filter(row_number() < 4)` do?
What does `flights |> group_by(dest) |> filter(row_number(dep_delay) < 4)` do?
2022-04-15 22:08:10 +08:00
5. For each destination, compute the total minutes of delay.
2022-03-17 22:46:35 +08:00
For each flight, compute the proportion of the total delay for its destination.
2022-04-15 22:08:10 +08:00
6. 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.
2022-04-18 22:42:43 +08:00
Using `lag()`, explore how the average flight delay for an hour is related to the average delay for the previous hour.
2022-05-14 04:46:49 +08:00
```{r}
#| results: false
2022-04-18 22:42:43 +08:00
flights |>
mutate(hour = dep_time %/% 100) |>
group_by(year, month, day, hour) |>
2022-11-19 06:07:54 +08:00
summarize(
2022-04-18 22:42:43 +08:00
dep_delay = mean(dep_delay, na.rm = TRUE),
n = n(),
.groups = "drop"
) |>
filter(n > 5)
```
2022-03-17 22:46:35 +08:00
2022-04-15 22:08:10 +08:00
7. Look at each destination.
2022-12-01 15:11:30 +08:00
Can you find flights that are suspiciously fast (i.e. flights that represent a potential data entry error)?
2022-03-17 22:46:35 +08:00
Compute the air time of a flight relative to the shortest flight to that destination.
Which flights were most delayed in the air?
2022-04-15 22:08:10 +08:00
8. Find all destinations that are flown by at least two carriers.
2022-04-18 22:42:43 +08:00
Use those destinations to come up with a relative ranking of the carriers based on their performance for the same destination.
2022-03-17 22:46:35 +08:00
2022-09-29 23:58:31 +08:00
## Numeric summaries
2022-03-23 22:52:38 +08:00
2022-04-18 22:42:43 +08:00
Just using the counts, means, and sums that we've introduced already can get you a long way, but R provides many other useful summary functions.
2022-12-01 15:11:30 +08:00
Here is a selection that you might find useful.
2022-03-23 22:52:38 +08:00
### Center
2022-04-18 22:42:43 +08:00
So far, we've mostly used `mean()` to summarize the center of a vector of values.
2023-03-02 13:26:43 +08:00
As we've seen in @sec-sample-size, because the mean is the sum divided by the count, it is sensitive to even just a few unusually high or low values.
2022-05-08 10:17:21 +08:00
An alternative is to use the `median()`, which finds a value that lies in the "middle" of the vector, i.e. 50% of the values is above it and 50% are below it.
2022-04-18 22:42:43 +08:00
Depending on the shape of the distribution of the variable you're interested in, mean or median might be a better measure of center.
2022-04-26 21:27:48 +08:00
For example, for symmetric distributions we generally report the mean while for skewed distributions we usually report the median.
2023-04-08 22:17:50 +08:00
@fig-mean-vs-median compares the mean vs. the median departure delay (in minutes) for each destination.
2022-12-01 15:11:30 +08:00
The median delay is always smaller than the mean delay because flights sometimes leave multiple hours late, but never leave multiple hours early.
2022-04-18 22:42:43 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| label: fig-mean-vs-median
2023-05-26 23:44:08 +08:00
#| fig-cap: |
2023-11-25 23:38:06 +08:00
#| A scatterplot showing the differences of summarizing daily departure
2022-06-01 12:52:33 +08:00
#| delay with median instead of mean.
2023-05-26 23:44:08 +08:00
#| fig-alt: |
2022-04-26 21:27:48 +08:00
#| All points fall below a 45° line, meaning that the median delay is
#| always less than the mean delay. Most points are clustered in a
#| dense region of mean [0, 20] and median [0, 5]. As the mean delay
#| increases, the spread of the median also increases. There are two
#| outlying points with mean ~60, median ~50, and mean ~85, median ~55.
2022-03-23 22:52:38 +08:00
flights |>
2022-04-18 22:42:43 +08:00
group_by(year, month, day) |>
2022-11-19 06:07:54 +08:00
summarize(
2022-04-18 22:42:43 +08:00
mean = mean(dep_delay, na.rm = TRUE),
median = median(dep_delay, na.rm = TRUE),
n = n(),
.groups = "drop"
) |>
2022-12-13 02:35:15 +08:00
ggplot(aes(x = mean, y = median)) +
2023-01-26 06:53:02 +08:00
geom_abline(slope = 1, intercept = 0, color = "white", linewidth = 2) +
2022-04-18 22:42:43 +08:00
geom_point()
2022-03-23 22:52:38 +08:00
```
2022-04-26 21:27:48 +08:00
You might also wonder about the **mode**, or the most common value.
This is a summary that only works well for very simple cases (which is why you might have learned about it in high school), but it doesn't work well for many real datasets.
2022-06-01 12:52:33 +08:00
If the data is discrete, there may be multiple most common values, and if the data is continuous, there might be no most common value because every value is ever so slightly different.
2022-08-09 02:44:06 +08:00
For these reasons, the mode tends not to be used by statisticians and there's no mode function included in base R[^numbers-2].
2022-03-23 22:52:38 +08:00
2022-08-09 02:44:06 +08:00
[^numbers-2]: The `mode()` function does something quite different!
2022-04-18 22:42:43 +08:00
2022-05-14 04:46:49 +08:00
### Minimum, maximum, and quantiles {#sec-min-max-summary}
2022-03-23 22:52:38 +08:00
2022-04-26 21:27:48 +08:00
What if you're interested in locations other than the center?
`min()` and `max()` will give you the largest and smallest values.
2022-12-01 15:11:30 +08:00
Another powerful tool is `quantile()` which is a generalization of the median: `quantile(x, 0.25)` will find the value of `x` that is greater than 25% of the values, `quantile(x, 0.5)` is equivalent to the median, and `quantile(x, 0.95)` will find the value that's greater than 95% of the values.
2022-03-23 22:52:38 +08:00
2022-09-09 04:20:53 +08:00
For the `flights` data, you might want to look at the 95% quantile of delays rather than the maximum, because it will ignore the 5% of most delayed flights which can be quite extreme.
2022-03-24 21:53:11 +08:00
2022-04-18 22:42:43 +08:00
```{r}
flights |>
group_by(year, month, day) |>
2022-11-19 06:07:54 +08:00
summarize(
2022-04-26 21:27:48 +08:00
max = max(dep_delay, na.rm = TRUE),
2022-04-18 22:42:43 +08:00
q95 = quantile(dep_delay, 0.95, na.rm = TRUE),
.groups = "drop"
)
```
2022-03-23 22:52:38 +08:00
### Spread
2022-09-29 23:58:31 +08:00
Sometimes you're not so interested in where the bulk of the data lies, but in how it is spread out.
2022-04-26 21:27:48 +08:00
Two commonly used summaries are the standard deviation, `sd(x)`, and the inter-quartile range, `IQR()`.
2022-08-10 00:43:12 +08:00
We won't explain `sd()` here since you're probably already familiar with it, but `IQR()` might be new --- it's `quantile(x, 0.75) - quantile(x, 0.25)` and gives you the range that contains the middle 50% of the data.
2022-04-26 21:27:48 +08:00
2022-09-09 04:20:53 +08:00
We can use this to reveal a small oddity in the `flights` data.
2022-09-29 23:58:31 +08:00
You might expect the spread of the distance between origin and destination to be zero, since airports are always in the same place.
2023-03-09 07:33:52 +08:00
But the code below reveals a data oddity for airport [EGE](https://en.wikipedia.org/wiki/Eagle_County_Regional_Airport):
2022-03-23 22:52:38 +08:00
```{r}
flights |>
group_by(origin, dest) |>
2022-11-19 06:07:54 +08:00
summarize(
2022-04-26 21:27:48 +08:00
distance_sd = IQR(distance),
n = n(),
.groups = "drop"
) |>
2022-03-23 22:52:38 +08:00
filter(distance_sd > 0)
```
2022-04-18 22:42:43 +08:00
### Distributions
2022-04-26 21:27:48 +08:00
It's worth remembering that all of the summary statistics described above are a way of reducing the distribution down to a single number.
2022-04-18 22:42:43 +08:00
This means that they're fundamentally reductive, and if you pick the wrong summary, you can easily miss important differences between groups.
That's why it's always a good idea to visualize the distribution before committing to your summary statistics.
2022-05-14 04:46:49 +08:00
@fig-flights-dist shows the overall distribution of departure delays.
2022-04-26 21:27:48 +08:00
The distribution is so skewed that we have to zoom in to see the bulk of the data.
This suggests that the mean is unlikely to be a good summary and we might prefer the median instead.
2022-04-18 22:42:43 +08:00
2022-05-14 04:46:49 +08:00
```{r}
2023-02-08 00:52:35 +08:00
#| echo: false
2022-05-14 04:46:49 +08:00
#| label: fig-flights-dist
2023-05-26 23:44:08 +08:00
#| fig-cap: |
2023-02-08 00:52:35 +08:00
#| (Left) The histogram of the full data is extremely skewed making it
#| hard to get any details. (Right) Zooming into delays of less than two
#| hours makes it possible to see what's happening with the bulk of the
#| observations.
2023-05-26 23:44:08 +08:00
#| fig-alt: |
2022-04-26 21:27:48 +08:00
#| Two histograms of `dep_delay`. On the left, it's very hard to see
#| any pattern except that there's a very large spike around zero, the
#| bars rapidly decay in height, and for most of the plot, you can't
#| see any bars because they are too short to see. On the right,
#| where we've discarded delays of greater than two hours, we can
#| see that the spike occurs slightly below zero (i.e. most flights
#| leave a couple of minutes early), but there's still a very steep
#| decay after that.
2023-02-08 00:52:35 +08:00
#| fig-asp: 0.5
2023-03-11 05:52:40 +08:00
2023-02-08 00:52:35 +08:00
library(patchwork)
2022-05-14 04:46:49 +08:00
2023-02-08 00:52:35 +08:00
full <- flights |>
2022-12-13 02:35:15 +08:00
ggplot(aes(x = dep_delay)) +
2023-02-08 00:52:35 +08:00
geom_histogram(binwidth = 15, na.rm = TRUE)
2022-04-18 22:42:43 +08:00
2023-02-08 00:52:35 +08:00
delayed120 <- flights |>
2022-09-09 04:20:53 +08:00
filter(dep_delay < 120) |>
2022-12-13 02:35:15 +08:00
ggplot(aes(x = dep_delay)) +
2022-04-18 22:42:43 +08:00
geom_histogram(binwidth = 5)
2023-02-08 00:52:35 +08:00
full + delayed120
2022-04-18 22:42:43 +08:00
```
2022-04-26 21:27:48 +08:00
It's also a good idea to check that distributions for subgroups resemble the whole.
2023-03-11 05:52:40 +08:00
In the following plot 365 frequency polygons of `dep_delay`, one for each day, are overlaid.
2022-04-26 21:27:48 +08:00
The distributions seem to follow a common pattern, suggesting it's fine to use the same summary for each day.
2022-04-18 22:42:43 +08:00
2022-05-14 04:46:49 +08:00
```{r}
2023-05-26 23:44:08 +08:00
#| fig-alt: |
2022-04-26 21:27:48 +08:00
#| The distribution of `dep_delay` is highly right skewed with a strong
#| peak slightly less than 0. The 365 frequency polygons are mostly
#| overlapping forming a thick black bland.
2023-03-11 05:52:40 +08:00
2022-04-18 22:42:43 +08:00
flights |>
2022-04-26 21:27:48 +08:00
filter(dep_delay < 120) |>
2022-12-13 02:35:15 +08:00
ggplot(aes(x = dep_delay, group = interaction(day, month))) +
2022-04-26 21:27:48 +08:00
geom_freqpoly(binwidth = 5, alpha = 1/5)
2022-04-18 22:42:43 +08:00
```
2022-04-26 21:27:48 +08:00
Don't be afraid to explore your own custom summaries specifically tailored for the data that you're working with.
2022-12-07 00:51:11 +08:00
In this case, that might mean separately summarizing the flights that left early vs. the flights that left late, or given that the values are so heavily skewed, you might try a log-transformation.
2022-05-14 04:46:49 +08:00
Finally, don't forget what you learned in @sec-sample-size: whenever creating numerical summaries, it's a good idea to include the number of observations in each group.
2022-03-23 22:52:38 +08:00
2022-04-15 22:08:10 +08:00
### Positions
2023-02-28 06:42:29 +08:00
There's one final type of summary that's useful for numeric vectors, but also works with every other type of value: extracting a value at a specific position: `first(x)`, `last(x)`, and `nth(x, n)`.
2022-04-15 22:08:10 +08:00
For example, we can find the first and last departure for each day:
```{r}
flights |>
group_by(year, month, day) |>
2022-11-19 06:07:54 +08:00
summarize(
2023-02-28 06:42:29 +08:00
first_dep = first(dep_time, na_rm = TRUE),
fifth_dep = nth(dep_time, 5, na_rm = TRUE),
last_dep = last(dep_time, na_rm = TRUE)
2022-04-15 22:08:10 +08:00
)
```
2023-02-28 06:42:29 +08:00
(NB: Because dplyr functions use `_` to separate components of function and arguments names, these functions use `na_rm` instead of `na.rm`.)
2022-04-26 21:27:48 +08:00
2023-02-28 06:42:29 +08:00
If you're familiar with `[`, which we'll come back to in @sec-subset-many, you might wonder if you ever need these functions.
There are three reasons: the `default` argument allows you to provide a default if the specified position doesn't exist, the `order_by` argument allows you to locally override the order of the rows, and the `na_rm` argument allows you to drop missing values.
2022-04-15 22:08:10 +08:00
Extracting values at positions is complementary to filtering on ranks.
Filtering gives you all variables, with each observation in a separate row:
```{r}
flights |>
group_by(year, month, day) |>
2023-05-10 09:15:55 +08:00
mutate(r = min_rank(sched_dep_time)) |>
2022-04-15 22:08:10 +08:00
filter(r %in% c(1, max(r)))
```
2022-03-23 22:52:38 +08:00
### With `mutate()`
2022-11-19 06:07:54 +08:00
As the names suggest, the summary functions are typically paired with `summarize()`.
2022-09-29 23:49:03 +08:00
However, because of the recycling rules we discussed in @sec-recycling they can also be usefully paired with `mutate()`, particularly when you want do some sort of group standardization.
2022-04-18 22:42:43 +08:00
For example:
2022-03-23 22:52:38 +08:00
2022-03-24 21:53:11 +08:00
- `x / sum(x)` calculates the proportion of a total.
2022-04-18 22:42:43 +08:00
- `(x - mean(x)) / sd(x)` computes a Z-score (standardized to mean 0 and sd 1).
2023-02-28 06:42:29 +08:00
- `(x - min(x)) / (max(x) - min(x))` standardizes to range \[0, 1\].
2022-04-18 22:42:43 +08:00
- `x / first(x)` computes an index based on the first observation.
2022-03-23 22:52:38 +08:00
### Exercises
2022-04-18 22:42:43 +08:00
1. Brainstorm at least 5 different ways to assess the typical delay characteristics of a group of flights.
2023-02-28 06:42:29 +08:00
When is `mean()` useful?
When is `median()` useful?
When might you want to use something else?
Should you use arrival delay or departure delay?
Why might you want to use data from `planes`?
2022-04-26 21:27:48 +08:00
2. Which destinations show the greatest variation in air speed?
3. Create a plot to further explore the adventures of EGE.
Can you find any evidence that the airport moved locations?
2023-03-09 07:33:52 +08:00
Can you find another variable that might explain the difference?
2022-10-21 22:14:49 +08:00
## Summary
2022-11-17 23:56:08 +08:00
You're already familiar with many tools for working with numbers, and after reading this chapter you now know how to use them in R.
You've also learned a handful of useful general transformations that are commonly, but not exclusively, applied to numeric vectors like ranks and offsets.
Finally, you worked through a number of numeric summaries, and discussed a few of the statistical challenges that you should consider.
2022-10-21 22:14:49 +08:00
Over the next two chapters, we'll dive into working with strings with the stringr package.
2022-11-17 23:56:08 +08:00
Strings are a big topic so they get two chapters, one on the fundamentals of strings and one on regular expressions.