r4ds/missing-values.qmd

304 lines
11 KiB
Plaintext
Raw Permalink Normal View History

# Missing values {#sec-missing-values}
2021-03-04 01:13:14 +08:00
```{r}
#| echo: false
source("_common.R")
2021-05-04 21:10:39 +08:00
```
2021-03-04 01:13:14 +08:00
## Introduction
2021-04-19 20:56:29 +08:00
2022-06-01 12:15:55 +08:00
You've already learned the basics of missing values earlier in the book.
2022-12-05 15:46:05 +08:00
You first saw them in @sec-data-visualization where they resulted in a warning when making a plot as well as in @sec-summarize where they interfered with computing summary statistics, and you learned about their infectious nature and how to check for their presence in @sec-na-comparison.
Now we'll come back to them in more depth, so you can learn more of the details.
2021-04-21 21:25:39 +08:00
We'll start by discussing some general tools for working with missing values recorded as `NA`s.
2023-11-11 01:48:02 +08:00
We'll then explore the idea of implicitly missing values, values that are simply absent from your data, and show some tools you can use to make them explicit.
We'll finish off with a related discussion of empty groups, caused by factor levels that don't appear in the data.
2021-04-21 21:25:39 +08:00
2022-03-31 21:10:52 +08:00
### Prerequisites
2021-04-21 21:25:39 +08:00
2022-06-01 12:15:55 +08:00
The functions for working with missing data mostly come from dplyr and tidyr, which are core members of the tidyverse.
2022-05-05 00:57:28 +08:00
```{r}
#| label: setup
#| message: false
2022-03-31 21:10:52 +08:00
library(tidyverse)
```
2021-04-19 20:59:07 +08:00
2022-05-05 00:57:28 +08:00
## Explicit missing values
To begin, let's explore a few handy tools for creating or eliminating missing explicit values, i.e. cells where you see an `NA`.
2022-05-05 00:57:28 +08:00
### Last observation carried forward
A common use for missing values is as a data entry convenience.
2022-09-29 23:58:31 +08:00
When data is entered by hand, missing values sometimes indicate that the value in the previous row has been repeated (or carried forward):
2021-04-19 20:59:07 +08:00
2022-05-05 00:57:28 +08:00
```{r}
treatment <- tribble(
~person, ~treatment, ~response,
"Derrick Whitmore", 1, 7,
NA, 2, 10,
2022-05-05 05:08:53 +08:00
NA, 3, NA,
2022-05-05 00:57:28 +08:00
"Katherine Burke", 1, 4
)
```
You can fill in these missing values with `tidyr::fill()`.
2022-05-11 10:04:14 +08:00
It works like `select()`, taking a set of columns:
2022-05-05 00:57:28 +08:00
```{r}
treatment |>
2022-05-05 05:08:53 +08:00
fill(everything())
2022-05-05 00:57:28 +08:00
```
2022-05-11 10:04:14 +08:00
This treatment is sometimes called "last observation carried forward", or **locf** for short.
2022-06-01 12:15:55 +08:00
You can use the `.direction` argument to fill in missing values that have been generated in more exotic ways.
2022-05-05 00:57:28 +08:00
### Fixed values
2022-09-29 23:58:31 +08:00
Some times missing values represent some fixed and known value, most commonly 0.
2022-05-05 05:08:53 +08:00
You can use `dplyr::coalesce()` to replace them:
2022-05-05 00:57:28 +08:00
```{r}
x <- c(1, 4, 5, 7, NA)
coalesce(x, 0)
```
2022-06-01 12:15:55 +08:00
Sometimes you'll hit the opposite problem where some concrete value actually represents a missing value.
2022-05-11 10:04:14 +08:00
This typically arises in data generated by older software that doesn't have a proper way to represent missing values, so it must instead use some special value like 99 or -999.
2022-05-05 05:08:53 +08:00
2023-04-10 23:22:08 +08:00
If possible, handle this when reading in the data, for example, by using the `na` argument to `readr::read_csv()`, e.g., `read_csv(path, na = "99")`.
2023-05-25 02:09:53 +08:00
If you discover the problem later, or your data source doesn't provide a way to handle it on read, you can use `dplyr::na_if()`:
2022-05-05 00:57:28 +08:00
```{r}
x <- c(1, 4, 5, 7, -99)
na_if(x, -99)
```
### NaN
2022-06-01 12:15:55 +08:00
Before we continue, there's one special type of missing value that you'll encounter from time to time: a `NaN` (pronounced "nan"), or **n**ot **a** **n**umber.
2022-05-05 20:43:36 +08:00
It's not that important to know about because it generally behaves just like `NA`:
2022-05-05 00:57:28 +08:00
```{r}
x <- c(NA, NaN)
x * 10
x == 1
is.na(x)
```
In the rare case you need to distinguish an `NA` from a `NaN`, you can use `is.nan(x)`.
2022-05-05 20:43:36 +08:00
You'll generally encounter a `NaN` when you perform a mathematical operation that has an indeterminate result:
2022-05-05 00:57:28 +08:00
```{r}
0 / 0
0 * Inf
Inf - Inf
sqrt(-1)
```
2022-09-16 21:00:35 +08:00
## Implicit missing values {#sec-missing-implicit}
2022-05-05 00:57:28 +08:00
2022-05-11 10:04:14 +08:00
So far we've talked about missing values that are **explicitly** missing, i.e. you can see an `NA` in your data.
2022-05-05 20:43:36 +08:00
But missing values can also be **implicitly** missing, if an entire row of data is simply absent from the data.
Let's illustrate the difference with a simple dataset that records the price of some stock each quarter:
2021-04-19 20:59:07 +08:00
```{r}
stocks <- tibble(
2022-05-05 20:43:36 +08:00
year = c(2020, 2020, 2020, 2020, 2021, 2021, 2021),
qtr = c( 1, 2, 3, 4, 2, 3, 4),
price = c(1.88, 0.59, 0.35, NA, 0.92, 0.17, 2.66)
2021-04-19 20:59:07 +08:00
)
```
2022-05-05 20:43:36 +08:00
This dataset has two missing observations:
2021-04-19 20:59:07 +08:00
- The `price` in the fourth quarter of 2020 is explicitly missing, because its value is `NA`.
- The `price` for the first quarter of 2021 is implicitly missing, because it simply does not appear in the dataset.
2021-04-19 20:59:07 +08:00
One way to think about the difference is with this Zen-like koan:
2021-04-19 20:59:07 +08:00
> An explicit missing value is the presence of an absence.\
2022-05-04 21:41:40 +08:00
>
> An implicit missing value is the absence of a presence.
2021-04-19 20:59:07 +08:00
2022-05-11 10:04:14 +08:00
Sometimes you want to make implicit missings explicit in order to have something physical to work with.
In other cases, explicit missings are forced upon you by the structure of the data and you want to get rid of them.
The following sections discuss some tools for moving between implicit and explicit missingness.
2022-05-05 00:57:28 +08:00
### Pivoting
2022-03-31 21:10:52 +08:00
2022-05-05 20:43:36 +08:00
You've already seen one tool that can make implicit missings explicit and vice versa: pivoting.
Making data wider can make implicit missing values explicit because every combination of the rows and new columns must have some value.
2022-06-01 12:15:55 +08:00
For example, if we pivot `stocks` to put the `quarter` in the columns, both missing values become explicit:
2022-03-31 21:10:52 +08:00
```{r}
stocks |>
pivot_wider(
2022-05-05 20:43:36 +08:00
names_from = qtr,
values_from = price
)
2022-03-31 21:10:52 +08:00
```
2022-06-01 12:15:55 +08:00
By default, making data longer preserves explicit missing values, but if they are structurally missing values that only exist because the data is not tidy, you can drop them (make them implicit) by setting `values_drop_na = TRUE`.
See the examples in @sec-tidy-data for more details.
### Complete
2022-05-11 10:04:14 +08:00
`tidyr::complete()` allows you to generate explicit missing values by providing a set of variables that define the combination of rows that should exist.
For example, we know that all combinations of `year` and `qtr` should exist in the `stocks` data:
```{r}
stocks |>
complete(year, qtr)
2022-03-31 21:10:52 +08:00
```
2022-05-11 10:04:14 +08:00
Typically, you'll call `complete()` with names of existing variables, filling in the missing combinations.
However, sometimes the individual variables are themselves incomplete, so you can instead provide your own data.
For example, you might know that the `stocks` dataset is supposed to run from 2019 to 2021, so you could explicitly supply those values for `year`:
2022-03-31 21:10:52 +08:00
```{r}
stocks |>
2022-05-05 20:43:36 +08:00
complete(year = 2019:2021, qtr)
```
2022-05-05 20:43:36 +08:00
If the range of a variable is correct, but not all values are present, you could use `full_seq(x, 1)` to generate all values from `min(x)` to `max(x)` spaced out by 1.
2022-03-31 21:10:52 +08:00
2022-05-11 10:04:14 +08:00
In some cases, the complete set of observations can't be generated by a simple combination of variables.
2022-05-05 20:43:36 +08:00
In that case, you can do manually what `complete()` does for you: create a data frame that contains all the rows that should exist (using whatever combination of techniques you need), then combine it with your original dataset with `dplyr::full_join()`.
### Joins
2022-05-05 00:57:28 +08:00
This brings us to another important way of revealing implicitly missing observations: joins.
You'll learn more about joins in @sec-joins, but we wanted to quickly mention them to you here since you can often only know that values are missing from one dataset when you compare it to another.
`dplyr::anti_join(x, y)` is a particularly useful tool here because it selects only the rows in `x` that don't have a match in `y`.
2023-01-23 22:35:09 +08:00
For example, we can use two `anti_join()`s to reveal that we're missing information for four airports and 722 planes mentioned in `flights`:
2022-03-31 21:10:52 +08:00
```{r}
2022-05-05 05:08:53 +08:00
library(nycflights13)
2022-03-31 21:10:52 +08:00
flights |>
distinct(faa = dest) |>
anti_join(airports)
flights |>
distinct(tailnum) |>
anti_join(planes)
```
2022-05-05 00:57:28 +08:00
### Exercises
2021-04-19 20:59:07 +08:00
2022-05-05 20:43:36 +08:00
1. Can you find any relationship between the carrier and the rows that appear to be missing from `planes`?
2021-04-19 20:59:07 +08:00
2022-05-05 00:57:28 +08:00
## Factors and empty groups
2022-02-16 01:59:19 +08:00
2022-05-11 10:04:14 +08:00
A final type of missingness is the empty group, a group that doesn't contain any observations, which can arise when working with factors.
For example, imagine we have a dataset that contains some health information about people:
```{r}
health <- tibble(
name = c("Ikaia", "Oletta", "Leriah", "Dashay", "Tresaun"),
smoker = factor(c("no", "no", "no", "no", "no"), levels = c("yes", "no")),
2023-03-01 21:45:54 +08:00
age = c(34, 88, 75, 47, 56),
)
```
2022-05-05 05:08:53 +08:00
And we want to count the number of smokers with `dplyr::count()`:
```{r}
health |> count(smoker)
```
2023-10-25 21:26:48 +08:00
This dataset only contains non-smokers, but we know that smokers exist; the group of non-smokers is empty.
2022-05-05 20:43:36 +08:00
We can request `count()` to keep all the groups, even those not seen in the data by using `.drop = FALSE`:
```{r}
health |> count(smoker, .drop = FALSE)
```
2022-05-05 20:43:36 +08:00
The same principle applies to ggplot2's discrete axes, which will also drop levels that don't have any values.
2022-06-01 12:15:55 +08:00
You can force them to display by supplying `drop = FALSE` to the appropriate discrete axis:
2022-05-05 00:57:28 +08:00
```{r}
#| layout-ncol: 2
#| fig-width: 3
#| fig-alt:
#| - A bar chart with a single value on the x-axis, "no".
#| - The same bar chart as the last plot, but now with two values on
#| the x-axis, "yes" and "no". There is no bar for the "yes" category.
2022-12-05 16:12:12 +08:00
ggplot(health, aes(x = smoker)) +
2022-05-05 00:57:28 +08:00
geom_bar() +
scale_x_discrete()
2022-12-05 16:12:12 +08:00
ggplot(health, aes(x = smoker)) +
2022-05-05 00:57:28 +08:00
geom_bar() +
scale_x_discrete(drop = FALSE)
```
2022-05-05 20:43:36 +08:00
The same problem comes up more generally with `dplyr::group_by()`.
And again you can use `.drop = FALSE` to preserve all factor levels:
```{r}
2023-03-01 21:45:54 +08:00
#| warning: false
health |>
group_by(smoker, .drop = FALSE) |>
summarize(
n = n(),
mean_age = mean(age),
min_age = min(age),
max_age = max(age),
sd_age = sd(age)
)
```
2022-05-11 10:04:14 +08:00
We get some interesting results here because when summarizing an empty group, the summary functions are applied to zero-length vectors.
2022-06-01 12:15:55 +08:00
There's an important distinction between empty vectors, which have length 0, and missing values, each of which has length 1.
2022-05-05 00:57:28 +08:00
```{r}
2022-05-11 10:04:14 +08:00
# A vector containing two missing values
2022-05-05 00:57:28 +08:00
x1 <- c(NA, NA)
length(x1)
2022-05-11 10:04:14 +08:00
# A vector containing nothing
2022-05-05 00:57:28 +08:00
x2 <- numeric()
length(x2)
```
2022-05-11 10:04:14 +08:00
All summary functions work with zero-length vectors, but they may return results that are surprising at first glance.
2022-05-05 00:57:28 +08:00
Here we see `mean(age)` returning `NaN` because `mean(age)` = `sum(age)/length(age)` which here is 0/0.
2022-05-11 10:04:14 +08:00
`max()` and `min()` return -Inf and Inf for empty vectors so if you combine the results with a non-empty vector of new data and recompute you'll get the minimum or maximum of the new data[^missing-values-1].
[^missing-values-1]: In other words, `min(c(x, y))` is always equal to `min(min(x), min(y))`.
2022-04-30 04:01:54 +08:00
2022-06-01 12:15:55 +08:00
Sometimes a simpler approach is to perform the summary and then make the implicit missings explicit with `complete()`.
```{r}
health |>
group_by(smoker) |>
summarize(
n = n(),
mean_age = mean(age),
min_age = min(age),
max_age = max(age),
sd_age = sd(age)
) |>
2022-05-05 00:57:28 +08:00
complete(smoker)
2022-04-30 04:01:54 +08:00
```
2022-05-05 20:43:36 +08:00
The main drawback of this approach is that you get an `NA` for the count, even though you know that it should be zero.
## Summary
Missing values are weird!
Sometimes they're recorded as an explicit `NA` but other times you only notice them by their absence.
This chapter has given you some tools for working with explicit missing values, tools for uncovering implicit missing values, and discussed some of the ways that implicit can become explicit and vice versa.
In the next chapter, we tackle the final chapter in this part of the book: joins.
This is a bit of a change from the chapters so far because we're going to discuss tools that work with data frames as a whole, not something that you put inside a data frame.