r4ds/rectangling.qmd

748 lines
27 KiB
Plaintext
Raw Normal View History

2022-11-24 04:57:55 +08:00
# Hierarchical data {#sec-rectangling}
```{r}
#| echo: false
source("_common.R")
2021-05-04 21:10:39 +08:00
```
## Introduction
In this chapter, you'll learn the art of data **rectangling**: taking data that is fundamentally hierarchical, or tree-like, and converting it into a rectangular data frame made up of rows and columns.
2022-09-01 21:27:21 +08:00
This is important because hierarchical data is surprisingly common, especially when working with data that comes from the web.
2022-06-07 22:18:14 +08:00
2022-09-01 21:27:21 +08:00
To learn about rectangling, you'll need to first learn about lists, the data structure that makes hierarchical data possible.
Then you'll learn about two crucial tidyr functions: `tidyr::unnest_longer()` and `tidyr::unnest_wider()`.
We'll then show you a few case studies, applying these simple functions again and again to solve real problems.
2022-08-08 21:27:25 +08:00
We'll finish off by talking about JSON, the most frequent source of hierarchical datasets and a common format for data exchange on the web.
### Prerequisites
2022-12-07 06:13:20 +08:00
In this chapter, we'll use many functions from tidyr, a core member of the tidyverse.
2022-09-01 21:27:21 +08:00
We'll also use repurrrsive to provide some interesting datasets for rectangling practice, and we'll finish by using jsonlite to read JSON files into R lists.
```{r}
#| label: setup
#| message: false
library(tidyverse)
2022-06-07 22:18:14 +08:00
library(repurrrsive)
2022-06-09 22:44:32 +08:00
library(jsonlite)
2022-06-07 22:18:14 +08:00
```
## Lists
2022-09-01 21:27:21 +08:00
So far you've worked with data frames that contain simple vectors like integers, numbers, characters, date-times, and factors.
2022-12-07 06:13:20 +08:00
These vectors are simple because they're homogeneous: every element is of the same data type.
If you want to store elements of different types in the same vector, you'll need a **list**, which you create with `list()`:
2022-06-07 22:18:14 +08:00
```{r}
x1 <- list(1:4, "a", TRUE)
x1
```
2022-06-20 22:48:56 +08:00
It's often convenient to name the components, or **children**, of a list, which you can do in the same way as naming the columns of a tibble:
2022-06-07 22:18:14 +08:00
```{r}
x2 <- list(a = 1:2, b = 1:3, c = 1:4)
x2
```
2022-06-18 22:06:54 +08:00
Even for these very simple lists, printing takes up quite a lot of space.
2022-06-20 22:48:56 +08:00
A useful alternative is `str()`, which generates a compact display of the **str**ucture, de-emphasizing the contents:
2022-06-07 22:18:14 +08:00
```{r}
str(x1)
str(x2)
```
2022-08-08 21:27:25 +08:00
As you can see, `str()` displays each child of the list on its own line.
2022-06-20 22:48:56 +08:00
It displays the name, if present, then an abbreviation of the type, then the first few values.
2022-06-07 22:18:14 +08:00
### Hierarchy
2022-06-18 22:06:54 +08:00
Lists can contain any type of object, including other lists.
2022-08-08 21:27:25 +08:00
This makes them suitable for representing hierarchical (tree-like) structures:
2022-06-07 22:18:14 +08:00
```{r}
x3 <- list(list(1, 2), list(3, 4))
str(x3)
```
2022-06-20 22:48:56 +08:00
This is notably different to `c()`, which generates a flat vector:
2022-06-18 22:06:54 +08:00
```{r}
c(c(1, 2), c(3, 4))
2022-06-20 22:48:56 +08:00
x4 <- c(list(1, 2), list(3, 4))
str(x4)
2022-06-18 22:06:54 +08:00
```
2022-06-20 22:48:56 +08:00
As lists get more complex, `str()` gets more useful, as it lets you see the hierarchy at a glance:
2022-06-07 22:18:14 +08:00
```{r}
2022-06-20 22:48:56 +08:00
x5 <- list(1, list(2, list(3, list(4, list(5)))))
str(x5)
2022-06-07 22:18:14 +08:00
```
2022-09-01 21:27:21 +08:00
As lists get even larger and more complex, `str()` eventually starts to fail, and you'll need to switch to `View()`[^rectangling-1].
@fig-view-collapsed shows the result of calling `View(x5)`. The viewer starts by showing just the top level of the list, but you can interactively expand any of the components to see more, as in @fig-view-expand-1. RStudio will also show you the code you need to access that element, as in @fig-view-expand-2. We'll come back to how this code works in @sec-subset-one.
2022-06-20 22:48:56 +08:00
2022-06-20 23:40:11 +08:00
[^rectangling-1]: This is an RStudio feature.
2022-06-07 22:18:14 +08:00
```{r}
#| label: fig-view-collapsed
#| fig.cap: >
2022-09-01 21:27:21 +08:00
#| The RStudio view lets you interactively explore a complex list.
2022-06-07 22:18:14 +08:00
#| The viewer opens showing only the top level of the list.
2022-09-01 21:27:21 +08:00
#| fig.alt: >
#| A screenshot of RStudio showing the list-viewer. It shows the
#| two children of x5: the first child is a double vector and the
2022-09-01 21:27:21 +08:00
#| second child is a list. A rightward facing triable indicates that the
#| second child itself has children but you can't see them.
2022-06-07 22:18:14 +08:00
#| echo: false
#| out-width: NULL
knitr::include_graphics("screenshots/View-1.png", dpi = 220)
```
```{r}
#| label: fig-view-expand-1
#| fig.cap: >
#| Clicking on the rightward facing triangle expands that component
#| of the list so that you can also see its children.
2022-09-01 21:27:21 +08:00
#| fig.alt: >
#| Another screenshot of the list-viewer having expand the second
#| child of x5. It also has two children, a double vector and another
2022-09-01 21:27:21 +08:00
#| list.
2022-06-07 22:18:14 +08:00
#| echo: false
#| out-width: NULL
knitr::include_graphics("screenshots/View-2.png", dpi = 220)
```
```{r}
#| label: fig-view-expand-2
#| fig.cap: >
#| You can repeat this operation as many times as needed to get to the
2022-09-01 21:27:21 +08:00
#| data you're interested in. Note the bottom-left corner: if you click
2022-06-18 22:06:54 +08:00
#| an element of the list, RStudio will give you the subsetting code
#| needed to access it, in this case `x5[[2]][[2]][[2]]`.
2022-09-01 21:27:21 +08:00
#| fig.alt: >
#| Another screenshot, having expanded the grandchild of x5 to see its
2022-09-01 21:27:21 +08:00
#| two children, again a double vector and a list.
2022-06-07 22:18:14 +08:00
#| echo: false
#| out-width: NULL
knitr::include_graphics("screenshots/View-3.png", dpi = 220)
```
2022-06-20 22:48:56 +08:00
### List-columns
2022-06-07 22:18:14 +08:00
2022-06-20 22:48:56 +08:00
Lists can also live inside a tibble, where we call them list-columns.
2022-12-07 06:13:20 +08:00
List-columns are useful because they allow you to place objects in a tibble that wouldn't usually belong in there.
In particular, list-columns are used a lot in the [tidymodels](https://www.tidymodels.org) ecosystem, because they allow you to store things like model outputs or resamples in a data frame.
2022-06-20 22:48:56 +08:00
Here's a simple example of a list-column:
2022-06-07 22:18:14 +08:00
```{r}
df <- tibble(
x = 1:2,
y = c("a", "b"),
2022-06-18 22:06:54 +08:00
z = list(list(1, 2), list(3, 4, 5))
2022-06-07 22:18:14 +08:00
)
df
```
2022-06-20 22:48:56 +08:00
There's nothing special about lists in a tibble; they behave like any other column:
2022-06-07 22:18:14 +08:00
```{r}
df |>
filter(x == 1)
```
2022-08-08 21:27:25 +08:00
Computing with list-columns is harder, but that's because computing with lists is harder in general; we'll come back to that in @sec-iteration.
In this chapter, we'll focus on unnesting list-columns out into regular variables so you can use your existing tools on them.
2022-06-20 22:48:56 +08:00
2022-06-07 22:18:14 +08:00
The default print method just displays a rough summary of the contents.
The list column could be arbitrarily complex, so there's no good way to print it.
If you want to see it, you'll need to pull out just the one list-column and apply one of the techniques that you've learned above, like `df |> pull(z) |> str()` or `df |> pull(z) |> View()`.
2022-06-07 22:18:14 +08:00
::: callout-note
## Base R
2022-08-08 21:27:25 +08:00
It's possible to put a list in a column of a `data.frame`, but it's a lot fiddlier because `data.frame()` treats a list as a list of columns:
2022-06-07 22:18:14 +08:00
```{r}
data.frame(x = list(1:3, 3:5))
```
2022-09-01 21:27:21 +08:00
You can force `data.frame()` to treat a list as a list of rows by wrapping it in list `I()`, but the result doesn't print particularly well:
2022-06-07 22:18:14 +08:00
```{r}
data.frame(
2022-09-01 21:27:21 +08:00
x = I(list(1:2, 3:5)),
2022-06-07 22:18:14 +08:00
y = c("1, 2", "3, 4, 5")
)
```
2022-12-07 06:13:20 +08:00
It's easier to use list-columns with tibbles because `tibble()` treats lists like vectors and the print method has been designed with lists in mind.
2022-06-07 22:18:14 +08:00
:::
## Unnesting
Now that you've learned the basics of lists and list-columns, let's explore how you can turn them back into regular rows and columns.
2022-09-01 21:27:21 +08:00
Here we'll use very simple sample data so you can get the basic idea; in the next section we'll switch to real data.
2022-06-07 22:18:14 +08:00
2022-06-20 22:48:56 +08:00
List-columns tend to come in two basic forms: named and unnamed.
When the children are **named**, they tend to have the same names in every row.
2022-09-01 21:27:21 +08:00
For example, in `df1`, every element of list-column `y` has two elements named `a` and `b`.
Named list-columns naturally unnest into columns: each named element becomes a new named column.
2022-06-07 22:18:14 +08:00
```{r}
df1 <- tribble(
~x, ~y,
1, list(a = 11, b = 12),
2022-06-09 22:44:32 +08:00
2, list(a = 21, b = 22),
3, list(a = 31, b = 32),
2022-06-07 22:18:14 +08:00
)
2022-09-01 21:27:21 +08:00
```
When the children are **unnamed**, the number of elements tends to vary from row-to-row.
For example, in `df2`, the elements of list-column `y` are unnamed and vary in length from one to three.
Unnamed list-columns naturally unnest into rows: you'll get one row for each child.
2022-09-01 21:27:21 +08:00
```{r}
2022-06-07 22:18:14 +08:00
df2 <- tribble(
~x, ~y,
2022-06-09 22:44:32 +08:00
1, list(11, 12, 13),
2, list(21),
3, list(31, 32),
2022-06-07 22:18:14 +08:00
)
```
2022-09-01 21:27:21 +08:00
tidyr provides two functions for these two cases: `unnest_wider()` and `unnest_longer()`.
2022-06-20 22:48:56 +08:00
The following sections explain how they work.
2022-06-07 22:18:14 +08:00
### `unnest_wider()`
2022-06-08 23:34:20 +08:00
When each row has the same number of elements with the same names, like `df1`, it's natural to put each component into its own column with `unnest_wider()`:
2022-06-07 22:18:14 +08:00
```{r}
2022-06-09 22:44:32 +08:00
df1 |>
unnest_wider(y)
2022-06-07 22:18:14 +08:00
```
2022-09-01 21:27:21 +08:00
By default, the names of the new columns come exclusively from the names of the list elements, but you can use the `names_sep` argument to request that they combine the column name and the element name.
2022-06-20 22:48:56 +08:00
This is useful for disambiguating repeated names.
2022-06-07 22:18:14 +08:00
```{r}
2022-06-09 22:44:32 +08:00
df1 |>
unnest_wider(y, names_sep = "_")
2022-06-08 23:34:20 +08:00
```
2022-06-07 22:18:14 +08:00
### `unnest_longer()`
2022-06-09 22:44:32 +08:00
When each row contains an unnamed list, it's most natural to put each element into its own row with `unnest_longer()`:
2022-06-07 22:18:14 +08:00
```{r}
2022-06-09 22:44:32 +08:00
df2 |>
unnest_longer(y)
2022-06-07 22:18:14 +08:00
```
2022-06-20 22:48:56 +08:00
Note how `x` is duplicated for each element inside of `y`: we get one row of output for each element inside the list-column.
2022-09-01 21:27:21 +08:00
But what happens if one of the elements is empty, as in the following example?
2022-06-07 22:18:14 +08:00
```{r}
2022-06-20 22:48:56 +08:00
df6 <- tribble(
~x, ~y,
"a", list(1, 2),
"b", list(3),
"c", list()
)
df6 |> unnest_longer(y)
2022-06-07 22:18:14 +08:00
```
2022-06-20 22:48:56 +08:00
We get zero rows in the output, so the row effectively disappears.
If you want to preserve that row, adding `NA` in `y`, set `keep_empty = TRUE`.
2022-06-18 22:06:54 +08:00
### Inconsistent types
2022-11-24 04:57:55 +08:00
What happens if you unnest a list-column that contains different types of vector?
For example, take the following dataset where the list-column `y` contains two numbers, a character, and a logical, which can't normally be mixed in a single column.
2022-06-18 22:06:54 +08:00
```{r}
df4 <- tribble(
~x, ~y,
2023-01-27 01:11:55 +08:00
"a", list(1),
"b", list("a", TRUE, 5)
2022-06-18 22:06:54 +08:00
)
```
2022-12-07 06:13:20 +08:00
`unnest_longer()` always keeps the set of columns unchanged, while changing the number of rows.
2022-06-18 22:06:54 +08:00
So what happens?
How does `unnest_longer()` produce five rows while keeping everything in `y`?
```{r}
2022-06-20 22:48:56 +08:00
df4 |>
unnest_longer(y)
2022-06-18 22:06:54 +08:00
```
2022-06-20 22:48:56 +08:00
As you can see, the output contains a list-column, but every element of the list-column contains a single element.
Because `unnest_longer()` can't find a common type of vector, it keeps the original types in a list-column.
2023-01-27 01:11:55 +08:00
You might wonder if this breaks the commandment that every element of a column must be the same type.
It doesn't: every element is a list, even though the contents are of different types.
2022-06-18 22:06:54 +08:00
Dealing with inconsistent types is challenging and the details depend on the precise nature of the problem and your goals, but you'll most likely need tools from @sec-iteration.
2022-09-01 21:27:21 +08:00
2022-06-07 22:18:14 +08:00
### Other functions
2022-06-20 22:48:56 +08:00
tidyr has a few other useful rectangling functions that we're not going to cover in this book:
2022-06-08 23:34:20 +08:00
2022-12-07 06:13:20 +08:00
- `unnest_auto()` automatically picks between `unnest_longer()` and `unnest_wider()` based on the structure of the list-column. It's great for rapid exploration, but ultimately it's a bad idea because it doesn't force you to understand how your data is structured, and makes your code harder to understand.
2022-12-07 06:17:25 +08:00
- `unnest()` expands both rows and columns. It's useful when you have a list-column that contains a 2d structure like a data frame, which you don't see in this book, but you might encounter if you use the [tidymodels](https://www.tmwr.org/base-r.html#combining-base-r-models-and-the-tidyverse) ecosystem.
2022-08-08 21:27:25 +08:00
2022-12-07 06:13:20 +08:00
These functions are good to know about as you might encounter them when reading other people's code or tackling rarer rectangling challenges yourself.
2022-06-08 23:34:20 +08:00
### Exercises
2022-06-07 22:18:14 +08:00
2023-01-27 01:11:55 +08:00
1. What happens when you use `unnest_wider()` with unnamed list-columns like `df2`?
What argument is now necessary?
What happens to missing values?
2023-01-27 01:11:55 +08:00
2. What happens when you use `unnest_longer()` with named list-columns like `df1`?
What additional information do you get in the output?
How can you suppress that extra detail?
3. From time-to-time you encounter data frames with multiple list-columns with aligned values.
2022-06-09 22:44:32 +08:00
For example, in the following data frame, the values of `y` and `z` are aligned (i.e. `y` and `z` will always have the same length within a row, and the first value of `y` corresponds to the first value of `z`).
What happens if you apply two `unnest_longer()` calls to this data frame?
How can you preserve the relationship between `x` and `y`?
(Hint: carefully read the docs).
2022-06-07 22:18:14 +08:00
2022-06-08 23:34:20 +08:00
```{r}
df4 <- tribble(
~x, ~y, ~z,
"a", list("y-a-1", "y-a-2"), list("z-a-1", "z-a-2"),
"b", list("y-b-1", "y-b-2", "y-b-3"), list("z-b-1", "z-b-2", "z-b-3")
)
```
2022-06-07 22:18:14 +08:00
## Case studies
2022-09-01 21:27:21 +08:00
The main difference between the simple examples we used above and real data is that real data typically contains multiple levels of nesting that require multiple calls to `unnest_longer()` and/or `unnest_wider()`.
2023-01-27 01:11:55 +08:00
To show that in action, this section works through three real rectangling challenges using datasets from the repurrrsive package.
2022-06-07 22:18:14 +08:00
### Very wide data
2022-11-24 04:57:55 +08:00
We'll start with `gh_repos`.
This is a list that contains data about a collection of GitHub repositories retrieved using the GitHub API. It's a very deeply nested list so it's difficult to show the structure in this book; we recommend exploring a little on your own with `View(gh_repos)` before we continue.
2022-06-20 22:48:56 +08:00
2022-08-08 21:27:25 +08:00
`gh_repos` is a list, but our tools work with list-columns, so we'll begin by putting it into a tibble.
2023-01-27 01:11:55 +08:00
We call this column `json` for reasons we'll get to later.
2022-06-07 22:18:14 +08:00
```{r}
2022-06-09 22:44:32 +08:00
repos <- tibble(json = gh_repos)
2022-06-07 22:18:14 +08:00
repos
2022-06-09 22:44:32 +08:00
```
2022-06-20 22:48:56 +08:00
This tibble contains 6 rows, one row for each child of `gh_repos`.
Each row contains a unnamed list with either 26 or 30 rows.
2022-09-01 21:27:21 +08:00
Since these are unnamed, we'll start with `unnest_longer()` to put each child in its own row:
2022-06-07 22:18:14 +08:00
2022-06-09 22:44:32 +08:00
```{r}
2022-06-07 22:18:14 +08:00
repos |>
2022-06-09 22:44:32 +08:00
unnest_longer(json)
```
2022-06-20 22:48:56 +08:00
At first glance, it might seem like we haven't improved the situation: while we have more rows (176 instead of 6) each element of `json` is still a list.
2022-08-15 21:50:31 +08:00
However, there's an important difference: now each element is a **named** list so we can use `unnest_wider()` to put each element into its own column:
2022-06-09 22:44:32 +08:00
```{r}
repos |>
unnest_longer(json) |>
unnest_wider(json)
```
2022-06-20 22:48:56 +08:00
This has worked but the result is a little overwhelming: there are so many columns that tibble doesn't even print all of them!
2023-01-24 23:33:18 +08:00
We can see them all with `names()`; and here we look at the first 10:
2022-06-09 22:44:32 +08:00
```{r}
repos |>
unnest_longer(json) |>
unnest_wider(json) |>
2023-01-24 23:33:18 +08:00
names() |>
head(10)
2022-06-07 22:18:14 +08:00
```
2023-01-27 01:11:55 +08:00
Let's pull out a few that look interesting:
2022-06-09 22:44:32 +08:00
```{r}
repos |>
unnest_longer(json) |>
unnest_wider(json) |>
select(id, full_name, owner, description)
```
2023-01-24 23:33:18 +08:00
You can use this to work back to understand how `gh_repos` was structured: each child was a GitHub user containing a list of up to 30 GitHub repositories that they created.
2022-06-20 22:48:56 +08:00
`owner` is another list-column, and since it contains a named list, we can use `unnest_wider()` to get at the values:
2022-06-09 22:44:32 +08:00
2022-06-18 22:06:54 +08:00
```{r}
#| error: true
2022-06-09 22:44:32 +08:00
repos |>
unnest_longer(json) |>
unnest_wider(json) |>
select(id, full_name, owner, description) |>
unnest_wider(owner)
```
Uh oh, this list column also contains an `id` column and we can't have two `id` columns in the same data frame.
2023-01-27 01:11:55 +08:00
As suggested, lets use `names_sep` to resolve the problem:
2022-06-09 22:44:32 +08:00
```{r}
repos |>
unnest_longer(json) |>
unnest_wider(json) |>
select(id, full_name, owner, description) |>
unnest_wider(owner, names_sep = "_")
```
2022-06-07 22:18:14 +08:00
2023-01-27 01:11:55 +08:00
This gives another wide dataset, but you can get the sense that `owner` appears to contain a lot of additional data about the person who "owns" the repository.
2022-06-20 22:48:56 +08:00
2022-06-07 22:18:14 +08:00
### Relational data
2023-01-27 01:11:55 +08:00
Nested data is sometimes used to represent data that we'd usually spread across multiple data frames.
For example, take `got_chars` which contains data about characters that appear in the Game of Thrones books and TV series.
2022-06-20 22:48:56 +08:00
Like `gh_repos` it's a list, so we start by turning it into a list-column of a tibble:
2022-06-09 22:44:32 +08:00
```{r}
chars <- tibble(json = got_chars)
chars
```
2022-09-01 21:27:21 +08:00
The `json` column contains named elements, so we'll start by widening it:
2022-06-09 22:44:32 +08:00
2022-06-07 22:18:14 +08:00
```{r}
chars |>
2022-06-09 22:44:32 +08:00
unnest_wider(json)
```
2022-09-01 21:27:21 +08:00
And selecting a few columns to make it easier to read:
2022-06-09 22:44:32 +08:00
```{r}
characters <- chars |>
unnest_wider(json) |>
select(id, name, gender, culture, born, died, alive)
characters
```
2023-01-27 01:11:55 +08:00
This dataset contains also many list-columns:
2022-06-09 22:44:32 +08:00
```{r}
chars |>
unnest_wider(json) |>
select(id, where(is.list))
```
Let's explore the `titles` column.
2022-06-20 22:48:56 +08:00
It's an unnamed list-column, so we'll unnest it into rows:
2022-06-09 22:44:32 +08:00
```{r}
chars |>
unnest_wider(json) |>
select(id, titles) |>
unnest_longer(titles)
```
2022-08-08 21:27:25 +08:00
You might expect to see this data in its own table because it would be easy to join to the characters data as needed.
2023-01-27 01:11:55 +08:00
Let's do that, which requires little cleaning: removing the rows containing empty strings and renaming `titles` to `title` since each row now only contains a single title.
2022-06-09 22:44:32 +08:00
```{r}
titles <- chars |>
unnest_wider(json) |>
2022-06-07 22:18:14 +08:00
select(id, titles) |>
unnest_longer(titles) |>
filter(titles != "") |>
rename(title = titles)
2022-06-09 22:44:32 +08:00
titles
```
2022-06-07 22:18:14 +08:00
2022-06-20 22:48:56 +08:00
You could imagine creating a table like this for each of the list-columns, then using joins to combine them with the character data as you need it.
2022-06-09 22:44:32 +08:00
2022-06-07 22:18:14 +08:00
### Deeply nested
2022-08-08 21:27:25 +08:00
We'll finish off these case studies with a list-column that's very deeply nested and requires repeated rounds of `unnest_wider()` and `unnest_longer()` to unravel: `gmaps_cities`.
2022-06-20 22:48:56 +08:00
This is a two column tibble containing five city names and the results of using Google's [geocoding API](https://developers.google.com/maps/documentation/geocoding) to determine their location:
2022-06-09 22:44:32 +08:00
```{r}
gmaps_cities
```
2022-08-08 21:27:25 +08:00
`json` is a list-column with internal names, so we start with an `unnest_wider()`:
2022-06-09 22:44:32 +08:00
```{r}
gmaps_cities |>
unnest_wider(json)
```
2022-06-20 22:48:56 +08:00
This gives us the `status` and the `results`.
2022-12-07 06:13:20 +08:00
We'll drop the status column since they're all `OK`; in a real analysis, you'd also want to capture all the rows where `status != "OK"` and figure out what went wrong.
2022-06-20 22:48:56 +08:00
`results` is an unnamed list, with either one or two elements (we'll see why shortly) so we'll unnest it into rows:
2022-06-09 22:44:32 +08:00
```{r}
gmaps_cities |>
unnest_wider(json) |>
select(-status) |>
unnest_longer(results)
```
2022-06-20 22:48:56 +08:00
Now `results` is a named list, so we'll use `unnest_wider()`:
2022-06-09 22:44:32 +08:00
```{r}
locations <- gmaps_cities |>
unnest_wider(json) |>
select(-status) |>
unnest_longer(results) |>
unnest_wider(results)
locations
```
2022-08-08 21:27:25 +08:00
Now we can see why two cities got two results: Washington matched both Washington state and Washington, DC, and Arlington matched Arlington, Virginia and Arlington, Texas.
2022-06-09 22:44:32 +08:00
There are a few different places we could go from here.
2022-06-20 22:48:56 +08:00
We might want to determine the exact location of the match, which is stored in the `geometry` list-column:
2022-06-09 22:44:32 +08:00
```{r}
locations |>
select(city, formatted_address, geometry) |>
unnest_wider(geometry)
```
2022-08-08 21:27:25 +08:00
That gives us new `bounds` (a rectangular region) and `location` (a point).
We can unnest `location` to see the latitude (`lat`) and longitude (`lng`):
2022-06-09 22:44:32 +08:00
```{r}
locations |>
select(city, formatted_address, geometry) |>
unnest_wider(geometry) |>
unnest_wider(location)
```
Extracting the bounds requires a few more steps:
2022-06-09 22:44:32 +08:00
```{r}
locations |>
select(city, formatted_address, geometry) |>
unnest_wider(geometry) |>
# focus on the variables of interest
select(!location:viewport) |>
unnest_wider(bounds)
```
2022-08-10 00:43:12 +08:00
We then rename `southwest` and `northeast` (the corners of the rectangle) so we can use `names_sep` to create short but evocative names:
2022-06-09 22:44:32 +08:00
```{r}
locations |>
select(city, formatted_address, geometry) |>
unnest_wider(geometry) |>
select(!location:viewport) |>
unnest_wider(bounds) |>
rename(ne = northeast, sw = southwest) |>
unnest_wider(c(ne, sw), names_sep = "_")
```
2022-08-08 21:27:25 +08:00
Note how we unnest two columns simultaneously by supplying a vector of variable names to `unnest_wider()`.
2022-06-09 22:44:32 +08:00
Once you've discovered the path to get to the components you're interested in, you can extract them directly using another tidyr function, `hoist()`:
2022-06-09 22:44:32 +08:00
```{r}
2023-01-27 01:11:55 +08:00
#| results: false
2022-06-09 22:44:32 +08:00
locations |>
select(city, formatted_address, geometry) |>
hoist(
geometry,
ne_lat = c("bounds", "northeast", "lat"),
sw_lat = c("bounds", "southwest", "lat"),
ne_lng = c("bounds", "northeast", "lng"),
sw_lng = c("bounds", "southwest", "lng"),
)
```
2022-06-20 22:48:56 +08:00
If these case studies have whetted your appetite for more real-life rectangling, you can see a few more examples in `vignette("rectangling", package = "tidyr")`.
2022-06-09 22:44:32 +08:00
### Exercises
2022-06-20 22:48:56 +08:00
1. Roughly estimate when `gh_repos` was created.
Why can you only roughly estimate the date?
2. The `owner` column of `gh_repo` contains a lot of duplicated information because each owner can have many repos.
Can you construct an `owners` data frame that contains one row for each owner?
2022-06-18 22:06:54 +08:00
(Hint: does `distinct()` work with `list-cols`?)
2022-06-09 22:44:32 +08:00
2023-01-27 01:11:55 +08:00
3. Follow the steps used for `titles` to create similar tables for the aliases, allegiances, books, and TV series for the Game of Thrones characters.
4. Explain the following code line-by-line.
2022-06-18 22:06:54 +08:00
Why is it interesting?
2022-08-08 21:27:25 +08:00
Why does it work for `got_chars` but might not work in general?
2022-06-09 22:44:32 +08:00
```{r}
2022-09-01 21:27:21 +08:00
#| results: false
2022-06-09 22:44:32 +08:00
tibble(json = got_chars) |>
unnest_wider(json) |>
2022-09-22 22:01:02 +08:00
select(id, where(is.list)) |>
2022-06-20 22:48:56 +08:00
pivot_longer(
where(is.list),
names_to = "name",
values_to = "value"
2022-09-22 22:01:02 +08:00
) |>
2022-06-09 22:44:32 +08:00
unnest_longer(value)
```
2023-01-27 01:11:55 +08:00
5. In `gmaps_cities`, what does `address_components` contain?
2022-06-20 22:48:56 +08:00
Why does the length vary between rows?
Unnest it appropriately to figure it out.
(Hint: `types` always appears to contain two elements. Does `unnest_wider()` make it easier to work with than `unnest_longer()`?)
.
2022-06-07 22:18:14 +08:00
## JSON
2022-09-01 21:27:21 +08:00
All of the case studies in the previous section were sourced from wild-caught JSON.
2022-08-08 21:27:25 +08:00
JSON is short for **j**ava**s**cript **o**bject **n**otation and is the way that most web APIs return data.
2022-08-11 23:29:28 +08:00
It's important to understand it because while JSON and R's data types are pretty similar, there isn't a perfect 1-to-1 mapping, so it's good to understand a bit about JSON if things go wrong.
2022-06-07 22:18:14 +08:00
2022-08-08 21:27:25 +08:00
### Data types
JSON is a simple format designed to be easily read and written by machines, not humans.
It has six key data types.
2022-08-11 23:29:28 +08:00
Four of them are scalars:
- The simplest type is a null (`null`) which plays the same role as `NA` in R. It represents the absence of data.
2022-09-01 21:27:21 +08:00
- A **string** is much like a string in R, but must always use double quotes.
2023-04-10 23:22:08 +08:00
- A **number** is similar to R's numbers: they can use integer (e.g., 123), decimal (e.g., 123.45), or scientific (e.g., 1.23e3) notation. JSON doesn't support `Inf`, `-Inf`, or `NaN`.
2022-09-01 21:27:21 +08:00
- A **boolean** is similar to R's `TRUE` and `FALSE`, but uses lowercase `true` and `false`.
2022-06-07 22:18:14 +08:00
2022-08-11 23:29:28 +08:00
JSON's strings, numbers, and booleans are pretty similar to R's character, numeric, and logical vectors.
The main difference is that JSON's scalars can only represent a single value.
2022-09-01 21:27:21 +08:00
To represent multiple values you need to use one of the two remaining types: arrays and objects.
2022-08-11 23:29:28 +08:00
Both arrays and objects are similar to lists in R; the difference is whether or not they're named.
An **array** is like an unnamed list, and is written with `[]`.
2022-08-08 21:27:25 +08:00
For example `[1, 2, 3]` is an array containing 3 numbers, and `[null, 1, "string", false]` is an array that contains a null, a number, a string, and a boolean.
2022-09-01 21:27:21 +08:00
An **object** is like a named list, and is written with `{}`.
The names (keys in JSON terminology) are strings, so must be surrounded by quotes.
2022-08-04 20:41:40 +08:00
For example, `{"x": 1, "y": 2}` is an object that maps `x` to 1 and `y` to 2.
2022-06-07 22:18:14 +08:00
2023-01-27 01:11:55 +08:00
Note that JSON doesn't have any native way to represent dates or date-times, so they're often stored as strings, and you'll need to use `readr::parse_date()` or `readr::parse_datetime()` to turn them into the correct data structure.
Similarly, JSON's rules for representing floating point numbers in JSON are a little imprecise, so you'll also sometimes find numbers stored in strings.
Apply `readr::parse_double()` as needed to get the correct variable type.
2023-01-27 01:11:55 +08:00
2022-08-04 20:41:40 +08:00
### jsonlite
2022-06-07 22:18:14 +08:00
2022-09-01 21:27:21 +08:00
To convert JSON into R data structures, we recommend the jsonlite package, by Jeroen Ooms.
2022-08-11 23:29:28 +08:00
We'll use only two jsonlite functions: `read_json()` and `parse_json()`.
In real life, you'll use `read_json()` to read a JSON file from disk.
2022-09-01 21:27:21 +08:00
For example, the repurrsive package also provides the source for `gh_user` as a JSON file and you can read it with `read_json()`:
2022-08-11 23:29:28 +08:00
```{r}
# A path to a json file inside the package:
gh_users_json()
# Read it with read_json()
gh_users2 <- read_json(gh_users_json())
# Check it's the same as the data we were using previously
identical(gh_users, gh_users2)
```
2022-12-07 06:13:20 +08:00
In this book, we'll also use `parse_json()`, since it takes a string containing JSON, which makes it good for generating simple examples.
To get started, here are three simple JSON datasets, starting with a number, then putting a few numbers in an array, then putting that array in an object:
2022-08-04 20:41:40 +08:00
```{r}
2022-08-11 23:29:28 +08:00
str(parse_json('1'))
2022-08-08 21:27:25 +08:00
str(parse_json('[1, 2, 3]'))
str(parse_json('{"x": [1, 2, 3]}'))
2022-06-07 22:18:14 +08:00
```
2022-08-11 23:29:28 +08:00
jsonlite has another important function called `fromJSON()`.
We don't use it here because it performs automatic simplification (`simplifyVector = TRUE`).
2022-08-11 23:29:28 +08:00
This often works well, particularly in simple cases, but we think you're better off doing the rectangling yourself so you know exactly what's happening and can more easily handle the most complicated nested structures.
2022-06-07 22:18:14 +08:00
2022-08-11 23:29:28 +08:00
### Starting the rectangling process
2022-08-08 21:27:25 +08:00
2023-04-10 23:22:08 +08:00
In most cases, JSON files contain a single top-level array, because they're designed to provide data about multiple "things", e.g., multiple pages, or multiple records, or multiple results.
2022-08-11 23:29:28 +08:00
In this case, you'll start your rectangling with `tibble(json)` so that each element becomes a row:
```{r}
json <- '[
{"name": "John", "age": 34},
{"name": "Susan", "age": 27}
]'
df <- tibble(json = parse_json(json))
df
2022-09-01 21:27:21 +08:00
2022-08-11 23:29:28 +08:00
df |>
unnest_wider(json)
```
2022-06-07 22:18:14 +08:00
2022-12-07 06:13:20 +08:00
In rarer cases, the JSON file consists of a single top-level JSON object, representing one "thing".
In this case, you'll need to kick off the rectangling process by wrapping it in a list, before you put it in a tibble.
2022-08-04 20:41:40 +08:00
2022-06-07 22:18:14 +08:00
```{r}
2022-08-11 23:29:28 +08:00
json <- '{
"status": "OK",
"results": [
{"name": "John", "age": 34},
{"name": "Susan", "age": 27}
]
}
'
df <- tibble(json = list(parse_json(json)))
df
2022-09-01 21:27:21 +08:00
2022-08-11 23:29:28 +08:00
df |>
unnest_wider(json) |>
unnest_longer(results) |>
unnest_wider(results)
```
Alternatively, you can reach inside the parsed JSON and start with the bit that you actually care about:
```{r}
df <- tibble(results = parse_json(json)$results)
df |>
unnest_wider(results)
2022-06-07 22:18:14 +08:00
```
2022-08-04 20:41:40 +08:00
### Exercises
2022-06-18 22:06:54 +08:00
2022-08-04 20:41:40 +08:00
1. Rectangle the `df_col` and `df_row` below.
They represent the two ways of encoding a data frame in JSON.
2022-06-18 22:06:54 +08:00
2022-08-04 20:41:40 +08:00
```{r}
json_col <- parse_json('
{
2022-08-08 21:27:25 +08:00
"x": ["a", "x", "z"],
"y": [10, null, 3]
2022-08-04 20:41:40 +08:00
}
')
json_row <- parse_json('
[
{"x": "a", "y": 10},
2022-08-08 21:27:25 +08:00
{"x": "x", "y": null},
{"x": "z", "y": 3}
2022-08-04 20:41:40 +08:00
]
')
df_col <- tibble(json = list(json_col))
2022-08-11 23:29:28 +08:00
df_row <- tibble(json = json_row)
2022-08-04 20:41:40 +08:00
```
2022-09-01 21:27:21 +08:00
## Summary
In this chapter, you learned what lists are, how you can generate them from JSON files, and how to turn them into rectangular data frames.
2022-09-01 21:27:21 +08:00
Surprisingly we only need two new functions: `unnest_longer()` to put list elements into rows and `unnest_wider()` to put list elements into columns.
It doesn't matter how deeply nested the list-column is; all you need to do is repeatedly call these two functions.
2022-09-01 21:27:21 +08:00
JSON is the most common data format returned by web APIs.
What happens if the website doesn't have an API, but you can see data you want on the website?
That's the topic of the next chapter: web scraping, extracting data from HTML webpages.