2022-05-14 04:46:49 +08:00
# Iteration {#sec-iteration}
```{r}
#| echo: false
2023-05-10 04:46:39 +08:00
2022-05-14 04:46:49 +08:00
source("_common.R")
```
2016-03-01 22:29:58 +08:00
2016-07-24 22:08:24 +08:00
## Introduction
2022-11-08 22:09:55 +08:00
In this chapter, you'll learn tools for iteration, repeatedly performing the same action on different objects.
2022-11-11 22:00:44 +08:00
Iteration in R generally tends to look rather different from other programming languages because so much of it is implicit and we get it for free.
For example, if you want to double a numeric vector `x` in R, you can just write `2 * x`.
2022-12-11 03:38:07 +08:00
In most other languages, you'd need to explicitly double each element of `x` using some sort of for loop.
2022-09-10 21:38:20 +08:00
2022-11-11 22:00:44 +08:00
This book has already given you a small but powerful number of tools that perform the same action for multiple "things":
2022-09-16 03:56:12 +08:00
2022-11-11 22:00:44 +08:00
- `facet_wrap()` and `facet_grid()` draws a plot for each subset.
2023-05-10 04:46:39 +08:00
- `group_by()` plus `summarize()` computes summary statistics for each subset.
2022-11-11 22:00:44 +08:00
- `unnest_wider()` and `unnest_longer()` create new rows and columns for each element of a list-column.
Now it's time to learn some more general tools, often called **functional programming** tools because they are built around functions that take other functions as inputs.
Learning functional programming can easily veer into the abstract, but in this chapter we'll keep things concrete by focusing on three common tasks: modifying multiple columns, reading multiple files, and saving multiple objects.
2022-09-16 04:28:54 +08:00
2016-07-19 21:01:50 +08:00
### Prerequisites
2022-09-22 23:43:21 +08:00
In this chapter, we'll focus on tools provided by dplyr and purrr, both core members of the tidyverse.
2022-11-11 22:00:44 +08:00
You've seen dplyr before, but [purrr](http://purrr.tidyverse.org/) is new.
2022-12-11 03:38:07 +08:00
We're just going to use a couple of purrr functions in this chapter, but it's a great package to explore as you improve your programming skills.
2016-07-19 21:01:50 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| label: setup
#| message: false
2016-10-04 01:30:24 +08:00
library(tidyverse)
2016-07-19 21:01:50 +08:00
```
2022-09-19 05:18:45 +08:00
## Modifying multiple columns {#sec-across}
2016-03-01 22:29:58 +08:00
2022-11-08 22:09:55 +08:00
Imagine you have this simple tibble and you want to count the number of observations and compute the median of every column.
2016-03-01 22:29:58 +08:00
```{r}
2016-10-04 03:10:05 +08:00
df <- tibble(
2016-03-01 22:29:58 +08:00
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
2016-03-21 21:55:07 +08:00
```
2016-03-01 22:29:58 +08:00
2022-09-10 21:38:20 +08:00
You could do it with copy-and-paste:
2016-03-22 21:57:52 +08:00
```{r}
2022-11-19 06:07:54 +08:00
df |> summarize(
2022-11-08 22:09:55 +08:00
n = n(),
2022-09-10 21:38:20 +08:00
a = median(a),
b = median(b),
c = median(c),
d = median(d),
)
2016-03-22 21:57:52 +08:00
```
2022-11-11 22:00:44 +08:00
That breaks our rule of thumb to never copy and paste more than twice, and you can imagine that this will get very tedious if you have tens or even hundreds of columns.
2022-12-11 03:38:07 +08:00
Instead, you can use `across()`:
2016-03-22 21:57:52 +08:00
2016-03-21 21:55:07 +08:00
```{r}
2022-11-19 06:07:54 +08:00
df |> summarize(
2022-11-08 22:09:55 +08:00
n = n(),
2022-09-20 22:13:51 +08:00
across(a:d, median),
2022-09-10 21:38:20 +08:00
)
2016-03-01 22:29:58 +08:00
```
2022-09-22 23:43:21 +08:00
`across()` has three particularly important arguments, which we'll discuss in detail in the following sections.
2022-11-08 22:09:55 +08:00
You'll use the first two every time you use `across()`: the first argument, `.cols`, specifies which columns you want to iterate over, and the second argument, `.fns`, specifies what to do with each column.
2022-11-11 22:00:44 +08:00
You can use the `.names` argument when you need additional control over the names of output columns, which is particularly important when you use `across()` with `mutate()`.
2022-09-22 23:43:21 +08:00
We'll also discuss two important variations, `if_any()` and `if_all()`, which work with `filter()`.
2022-09-16 03:56:12 +08:00
2022-09-20 22:13:51 +08:00
### Selecting columns with `.cols`
2021-02-21 23:40:40 +08:00
2022-11-11 22:00:44 +08:00
The first argument to `across()`, `.cols`, selects the columns to transform.
This uses the same specifications as `select()`, @sec-select, so you can use functions like `starts_with()` and `ends_with()` to select columns based on their name.
2022-09-20 22:13:51 +08:00
2022-09-22 23:43:21 +08:00
There are two additional selection techniques that are particularly useful for `across()`: `everything()` and `where()`.
`everything()` is straightforward: it selects every (non-grouping) column:
2022-09-16 03:56:12 +08:00
```{r}
df <- tibble(
grp = sample(2, 10, replace = TRUE),
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
2022-09-22 23:43:21 +08:00
df |>
2022-09-16 03:56:12 +08:00
group_by(grp) |>
2022-11-19 06:07:54 +08:00
summarize(across(everything(), median))
2022-09-16 03:56:12 +08:00
```
2022-11-19 06:07:54 +08:00
Note grouping columns (`grp` here) are not included in `across()`, because they're automatically preserved by `summarize()`.
2022-11-08 22:09:55 +08:00
2022-09-16 03:56:12 +08:00
`where()` allows you to select columns based on their type:
- `where(is.numeric)` selects all numeric columns.
- `where(is.character)` selects all string columns.
- `where(is.Date)` selects all date columns.
- `where(is.POSIXct)` selects all date-time columns.
- `where(is.logical)` selects all logical columns.
2021-02-21 23:40:40 +08:00
2022-09-22 23:43:21 +08:00
Just like other selectors, you can combine these with Boolean algebra.
2022-12-11 03:38:07 +08:00
For example, `!where(is.numeric)` selects all non-numeric columns, and `starts_with("a") & where(is.logical)` selects all logical columns whose name starts with "a".
2022-05-14 04:46:49 +08:00
2022-11-11 22:00:44 +08:00
### Calling a single function
2021-02-21 23:40:40 +08:00
2022-09-22 23:43:21 +08:00
The second argument to `across()` defines how each column will be transformed.
2022-11-11 22:00:44 +08:00
In simple cases, as above, this will be a single existing function.
This is a pretty special feature of R: we're passing one function (`median`, `mean`, `str_flatten`, ...) to another function (`across`).
2022-12-11 03:38:07 +08:00
This is one of the features that makes R a functional programming language.
2022-11-11 22:00:44 +08:00
2023-03-23 03:43:41 +08:00
It's important to note that we're passing this function to `across()`, so `across()` can call it; we're not calling it ourselves.
2022-11-11 22:00:44 +08:00
That means the function name should never be followed by `()`.
If you forget, you'll get an error:
```{r}
#| error: true
df |>
group_by(grp) |>
2022-11-19 06:07:54 +08:00
summarize(across(everything(), median()))
2022-11-11 22:00:44 +08:00
```
This error arises because you're calling the function with no input, e.g.:
```{r}
#| error: true
median()
```
2022-11-11 23:41:59 +08:00
### Calling multiple functions
2022-09-16 03:56:12 +08:00
2022-11-11 22:00:44 +08:00
In more complex cases, you might want to supply additional arguments or perform multiple transformations.
2022-12-11 03:38:07 +08:00
Let's motivate this problem with a simple example: what happens if we have some missing values in our data?
2022-11-11 22:00:44 +08:00
`median()` propagates those missing values, giving us a suboptimal output:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-16 03:56:12 +08:00
rnorm_na <- function(n, n_na, mean = 0, sd = 1) {
2023-03-01 21:45:54 +08:00
sample(c(rnorm(n - n_na, mean = mean, sd = sd), rep(NA, n_na)))
2022-09-16 03:56:12 +08:00
}
2022-11-11 22:00:44 +08:00
df_miss <- tibble(
2022-09-22 23:43:21 +08:00
a = rnorm_na(5, 1),
b = rnorm_na(5, 1),
c = rnorm_na(5, 2),
d = rnorm(5)
2016-03-21 21:55:07 +08:00
)
2022-11-11 22:00:44 +08:00
df_miss |>
2022-11-19 06:07:54 +08:00
summarize(
2022-09-20 22:13:51 +08:00
across(a:d, median),
n = n()
)
2016-03-01 22:29:58 +08:00
```
2022-11-11 22:00:44 +08:00
It would be nice if we could pass along `na.rm = TRUE` to `median()` to remove these missing values.
To do so, instead of calling `median()` directly, we need to create a new function that calls `median()` with the desired arguments:
2022-09-22 23:43:21 +08:00
```{r}
2022-11-11 22:00:44 +08:00
df_miss |>
2022-11-19 06:07:54 +08:00
summarize(
2022-09-22 23:43:21 +08:00
across(a:d, function(x) median(x, na.rm = TRUE)),
n = n()
)
```
2022-11-11 22:00:44 +08:00
This is a little verbose, so R comes with a handy shortcut: for this sort of throw away, or **anonymous**[^iteration-1], function you can replace `function` with `\`[^iteration-2]:
2022-09-22 23:43:21 +08:00
2022-11-11 22:00:44 +08:00
[^iteration-1]: Anonymous, because we never explicitly gave it a name with `<-`.
Another term programmers use for this is "lambda function".
[^iteration-2]: In older code you might see syntax that looks like `~ .x + 1`.
This is another way to write anonymous functions but it only works inside tidyverse functions and always uses the variable name `.x`.
We now recommend the base syntax, `\(x) x + 1`.
2016-03-21 21:55:07 +08:00
```{r}
2022-09-22 23:43:21 +08:00
#| results: false
2022-11-11 22:00:44 +08:00
df_miss |>
2022-11-19 06:07:54 +08:00
summarize(
2022-09-20 22:13:51 +08:00
across(a:d, \(x) median(x, na.rm = TRUE)),
n = n()
)
```
2022-09-22 23:43:21 +08:00
In either case, `across()` effectively expands to the following code:
2022-09-20 22:13:51 +08:00
```{r}
#| eval: false
2022-11-11 22:00:44 +08:00
df_miss |>
2022-11-19 06:07:54 +08:00
summarize(
2022-11-11 22:00:44 +08:00
a = median(a, na.rm = TRUE),
b = median(b, na.rm = TRUE),
c = median(c, na.rm = TRUE),
d = median(d, na.rm = TRUE),
n = n()
)
2016-03-01 22:29:58 +08:00
```
2022-12-11 03:38:07 +08:00
When we remove the missing values from the `median()`, it would be nice to know just how many values were removed.
2022-11-08 22:09:55 +08:00
We can find that out by supplying two functions to `across()`: one to compute the median and the other to count the missing values.
2022-11-11 22:00:44 +08:00
You supply multiple functions by using a named list to `.fns`:
2022-09-16 03:56:12 +08:00
```{r}
2022-11-11 22:00:44 +08:00
df_miss |>
2022-11-19 06:07:54 +08:00
summarize(
2022-09-20 22:13:51 +08:00
across(a:d, list(
median = \(x) median(x, na.rm = TRUE),
n_miss = \(x) sum(is.na(x))
)),
n = n()
)
2022-09-16 03:56:12 +08:00
```
2023-05-25 02:17:55 +08:00
If you look carefully, you might intuit that the columns are named using a glue specification (@sec-glue) like `{.col}_{.fn}` where `.col` is the name of the original column and `.fn` is the name of the function.
2022-09-22 23:43:21 +08:00
That's not a coincidence!
As you'll learn in the next section, you can use `.names` argument to supply your own glue spec.
2022-09-16 03:56:12 +08:00
### Column names
2016-03-01 22:29:58 +08:00
2022-11-11 22:00:44 +08:00
The result of `across()` is named according to the specification provided in the `.names` argument.
We could specify our own if we wanted the name of the function to come first[^iteration-3]:
2022-09-20 22:13:51 +08:00
2022-11-11 22:00:44 +08:00
[^iteration-3]: You can't currently change the order of the columns, but you could reorder them after the fact using `relocate()` or similar.
2016-03-01 22:29:58 +08:00
2016-03-21 21:55:07 +08:00
```{r}
2022-11-11 22:00:44 +08:00
df_miss |>
2022-11-19 06:07:54 +08:00
summarize(
2022-09-20 22:13:51 +08:00
across(
2022-11-11 22:00:44 +08:00
a:d,
2022-09-20 22:13:51 +08:00
list(
median = \(x) median(x, na.rm = TRUE),
n_miss = \(x) sum(is.na(x))
2022-11-11 22:00:44 +08:00
),
2022-09-20 22:13:51 +08:00
.names = "{.fn}_{.col}"
),
n = n(),
)
2016-03-01 22:29:58 +08:00
```
2022-09-16 03:56:12 +08:00
The `.names` argument is particularly important when you use `across()` with `mutate()`.
2022-12-11 03:38:07 +08:00
By default, the output of `across()` is given the same names as the inputs.
2022-11-08 22:09:55 +08:00
This means that `across()` inside of `mutate()` will replace existing columns.
For example, here we use `coalesce()` to replace `NA`s with `0`:
2016-03-22 21:57:52 +08:00
2016-03-21 21:55:07 +08:00
```{r}
2022-11-11 22:00:44 +08:00
df_miss |>
2022-09-20 22:13:51 +08:00
mutate(
2022-09-22 23:43:21 +08:00
across(a:d, \(x) coalesce(x, 0))
2022-09-20 22:13:51 +08:00
)
2016-03-21 21:55:07 +08:00
```
2022-11-11 22:00:44 +08:00
If you'd like to instead create new columns, you can use the `.names` argument to give the output new names:
2016-03-01 22:29:58 +08:00
2022-05-14 04:46:49 +08:00
```{r}
2022-11-11 22:00:44 +08:00
df_miss |>
2022-09-20 22:13:51 +08:00
mutate(
2023-11-09 11:11:21 +08:00
across(a:d, \(x) coalesce(x, 0), .names = "{.col}_na_zero")
2022-09-20 22:13:51 +08:00
)
2016-03-22 21:57:52 +08:00
```
2016-03-01 22:29:58 +08:00
2022-09-10 21:38:20 +08:00
### Filtering
2016-03-01 22:29:58 +08:00
2022-11-19 06:07:54 +08:00
`across()` is a great match for `summarize()` and `mutate()` but it's more awkward to use with `filter()`, because you usually combine multiple conditions with either `|` or `&`.
2022-11-11 22:00:44 +08:00
It's clear that `across()` can help to create multiple logical columns, but then what?
2022-09-16 03:56:12 +08:00
So dplyr provides two variants of `across()` called `if_any()` and `if_all()`:
2022-05-14 04:46:49 +08:00
```{r}
2023-02-08 05:48:02 +08:00
# same as df_miss |> filter(is.na(a) | is.na(b) | is.na(c) | is.na(d))
2022-11-11 22:00:44 +08:00
df_miss |> filter(if_any(a:d, is.na))
2022-09-16 03:56:12 +08:00
2023-02-08 05:48:02 +08:00
# same as df_miss |> filter(is.na(a) & is.na(b) & is.na(c) & is.na(d))
2022-11-11 22:00:44 +08:00
df_miss |> filter(if_all(a:d, is.na))
2016-03-01 22:29:58 +08:00
```
2022-09-20 22:13:51 +08:00
### `across()` in functions
2022-11-11 22:00:44 +08:00
`across()` is particularly useful to program with because it allows you to operate on multiple columns.
2023-05-10 04:46:39 +08:00
For example, [Jacob Scott](https://twitter.com/_wurli/status/1571836746899283969) uses this little helper which wraps a bunch of lubridate functions to expand all date columns into year, month, and day columns:
2022-09-20 22:13:51 +08:00
```{r}
expand_dates <- function(df) {
df |>
mutate(
2022-11-11 22:00:44 +08:00
across(where(is.Date), list(year = year, month = month, day = mday))
2022-09-20 22:13:51 +08:00
)
}
2022-11-11 22:00:44 +08:00
df_date <- tibble(
name = c("Amy", "Bob"),
date = ymd(c("2009-08-03", "2010-01-16"))
)
df_date |>
expand_dates()
2022-09-20 22:13:51 +08:00
```
2022-11-11 22:00:44 +08:00
`across()` also makes it easy to supply multiple columns in a single argument because the first argument uses tidy-select; you just need to remember to embrace that argument, as we discussed in @sec-embracing.
For example, this function will compute the means of numeric columns by default.
But by supplying the second argument you can choose to summarize just selected columns:
2022-09-20 22:13:51 +08:00
```{r}
2022-11-19 06:07:54 +08:00
summarize_means <- function(df, summary_vars = where(is.numeric)) {
2022-09-22 23:43:21 +08:00
df |>
2022-11-19 06:07:54 +08:00
summarize(
2022-09-20 22:13:51 +08:00
across({{ summary_vars }}, \(x) mean(x, na.rm = TRUE)),
2023-11-09 11:06:09 +08:00
n = n(),
.groups = "drop"
2022-09-20 22:13:51 +08:00
)
}
diamonds |>
2023-02-08 05:48:02 +08:00
group_by(cut) |>
2022-11-19 06:07:54 +08:00
summarize_means()
2022-09-20 22:13:51 +08:00
diamonds |>
2023-02-08 05:48:02 +08:00
group_by(cut) |>
2022-11-19 06:07:54 +08:00
summarize_means(c(carat, x:z))
2022-09-20 22:13:51 +08:00
```
2022-09-10 21:38:20 +08:00
### Vs `pivot_longer()`
2022-11-11 22:00:44 +08:00
Before we go on, it's worth pointing out an interesting connection between `across()` and `pivot_longer()` (@sec-pivoting).
2022-09-10 21:38:20 +08:00
In many cases, you perform the same calculations by first pivoting the data and then performing the operations by group rather than by column.
2022-11-11 22:00:44 +08:00
For example, take this multi-function summary:
2016-03-01 22:29:58 +08:00
2016-03-22 21:57:52 +08:00
```{r}
2022-09-10 21:38:20 +08:00
df |>
2022-11-19 06:07:54 +08:00
summarize(across(a:d, list(median = median, mean = mean)))
2022-11-11 22:00:44 +08:00
```
We could compute the same values by pivoting longer and then summarizing:
```{r}
long <- df |>
2022-09-10 21:38:20 +08:00
pivot_longer(a:d) |>
group_by(name) |>
2022-11-19 06:07:54 +08:00
summarize(
2022-11-11 22:00:44 +08:00
median = median(value),
mean = mean(value)
)
long
```
And if you wanted the same structure as `across()` you could pivot again:
```{r}
long |>
pivot_wider(
names_from = name,
values_from = c(median, mean),
names_vary = "slowest",
names_glue = "{name}_{.value}"
2022-09-10 21:38:20 +08:00
)
2016-03-22 21:57:52 +08:00
```
2022-11-11 22:00:44 +08:00
This is a useful technique to know about because sometimes you'll hit a problem that's not currently possible to solve with `across()`: when you have groups of columns that you want to compute with simultaneously.
2022-09-16 03:56:12 +08:00
For example, imagine that our data frame contains both values and weights and we want to compute a weighted mean:
2016-03-22 21:57:52 +08:00
2022-09-10 21:38:20 +08:00
```{r}
2022-11-11 22:00:44 +08:00
df_paired <- tibble(
2022-09-10 21:38:20 +08:00
a_val = rnorm(10),
2022-11-11 22:00:44 +08:00
a_wts = runif(10),
2022-09-10 21:38:20 +08:00
b_val = rnorm(10),
2022-11-11 22:00:44 +08:00
b_wts = runif(10),
2022-09-10 21:38:20 +08:00
c_val = rnorm(10),
2022-11-11 22:00:44 +08:00
c_wts = runif(10),
2022-09-10 21:38:20 +08:00
d_val = rnorm(10),
2022-11-11 22:00:44 +08:00
d_wts = runif(10)
2022-09-10 21:38:20 +08:00
)
2022-09-16 03:56:12 +08:00
```
2021-02-21 23:40:40 +08:00
2022-11-11 22:00:44 +08:00
There's currently no way to do this with `across()`[^iteration-4], but it's relatively straightforward with `pivot_longer()`:
2022-09-16 03:56:12 +08:00
2022-11-11 22:00:44 +08:00
[^iteration-4]: Maybe there will be one day, but currently we don't see how.
2022-09-16 03:56:12 +08:00
```{r}
2022-11-11 22:00:44 +08:00
df_long <- df_paired |>
2022-09-10 21:38:20 +08:00
pivot_longer(
everything(),
names_to = c("group", ".value"),
names_sep = "_"
2022-09-16 03:56:12 +08:00
)
2022-11-11 22:00:44 +08:00
df_long
2022-09-16 03:56:12 +08:00
2022-11-11 22:00:44 +08:00
df_long |>
2022-09-10 21:38:20 +08:00
group_by(group) |>
2022-11-19 06:07:54 +08:00
summarize(mean = weighted.mean(val, wts))
2022-09-10 21:38:20 +08:00
```
2021-02-21 23:40:40 +08:00
2022-09-16 03:56:12 +08:00
If needed, you could `pivot_wider()` this back to the original form.
2022-05-14 04:46:49 +08:00
2022-09-10 21:38:20 +08:00
### Exercises
2016-03-01 22:29:58 +08:00
2023-03-01 21:45:54 +08:00
1. Practice your `across()` skills by:
2022-09-22 23:43:21 +08:00
2023-03-01 21:45:54 +08:00
1. Computing the number of unique values in each column of `palmerpenguins::penguins`.
2022-09-22 23:43:21 +08:00
2023-03-01 21:45:54 +08:00
2. Computing the mean of every column in `mtcars`.
2022-09-22 23:43:21 +08:00
2023-03-01 21:45:54 +08:00
3. Grouping `diamonds` by `cut`, `clarity`, and `color` then counting the number of observations and computing the mean of each numeric column.
2022-09-22 23:43:21 +08:00
2023-03-01 21:45:54 +08:00
2. What happens if you use a list of functions in `across()`, but don't name them?
How is the output named?
2022-09-22 23:43:21 +08:00
2023-03-01 21:45:54 +08:00
3. Adjust `expand_dates()` to automatically remove the date columns after they've been expanded.
2022-09-22 23:43:21 +08:00
Do you need to embrace any arguments?
2023-03-01 21:45:54 +08:00
4. Explain what each step of the pipeline in this function does.
2022-09-22 23:43:21 +08:00
What special feature of `where()` are we taking advantage of?
```{r}
#| results: false
show_missing <- function(df, group_vars, summary_vars = everything()) {
df |>
group_by(pick({{ group_vars }})) |>
2022-11-19 06:07:54 +08:00
summarize(
2022-09-22 23:43:21 +08:00
across({{ summary_vars }}, \(x) sum(is.na(x))),
.groups = "drop"
) |>
select(where(\(x) any(x > 0)))
}
nycflights13::flights |> show_missing(c(year, month, day))
```
2021-02-21 23:40:40 +08:00
2022-09-16 04:28:54 +08:00
## Reading multiple files
2016-03-01 22:29:58 +08:00
2022-11-11 22:00:44 +08:00
In the previous section, you learned how to use `dplyr::across()` to repeat a transformation on multiple columns.
2022-11-09 05:29:57 +08:00
In this section, you'll learn how to use `purrr::map()` to do something to every file in a directory.
2022-11-11 22:00:44 +08:00
Let's start with a little motivation: imagine you have a directory full of excel spreadsheets[^iteration-5] you want to read.
2022-09-16 03:56:12 +08:00
You could do it with copy and paste:
2022-11-11 22:00:44 +08:00
[^iteration-5]: If you instead had a directory of csv files with the same format, you can use the technique from @sec-readr-directory.
2022-09-16 03:56:12 +08:00
```{r}
#| eval: false
2022-11-11 22:00:44 +08:00
data2019 <- readxl::read_excel("data/y2019.xlsx")
data2020 <- readxl::read_excel("data/y2020.xlsx")
data2021 <- readxl::read_excel("data/y2021.xlsx")
data2022 <- readxl::read_excel("data/y2022.xlsx")
2022-09-16 03:56:12 +08:00
```
And then use `dplyr::bind_rows()` to combine them all together:
```{r}
#| eval: false
data <- bind_rows(data2019, data2020, data2021, data2022)
```
2022-11-09 05:29:57 +08:00
You can imagine that this would get tedious quickly, especially if you had hundreds of files, not just four.
The following sections show you how to automate this sort of task.
2022-11-11 22:00:44 +08:00
There are three basic steps: use `list.files()` to list all the files in a directory, then use `purrr::map()` to read each of them into a list, then use `purrr::list_rbind()` to combine them into a single data frame.
2022-09-22 23:43:21 +08:00
We'll then discuss how you can handle situations of increasing heterogeneity, where you can't do exactly the same thing to every file.
2022-09-16 03:56:12 +08:00
### Listing files in a directory
2022-05-14 04:46:49 +08:00
2022-11-11 22:00:44 +08:00
As the name suggests, `list.files()` lists the files in a directory.
2022-09-20 22:13:51 +08:00
You'll almost always use three arguments:
2022-11-09 05:29:57 +08:00
- The first argument, `path`, is the directory to look in.
2022-09-20 22:13:51 +08:00
2022-11-09 05:29:57 +08:00
- `pattern` is a regular expression used to filter the file names.
2022-11-11 22:00:44 +08:00
The most common pattern is something like `[.]xlsx$` or `[.]csv$` to find all files with a specified extension.
2016-03-10 22:46:06 +08:00
2022-09-20 22:13:51 +08:00
- `full.names` determines whether or not the directory name should be included in the output.
You almost always want this to be `TRUE`.
2022-11-09 05:29:57 +08:00
To make our motivating example concrete, this book contains a folder with 12 excel spreadsheets containing data from the gapminder package.
Each file contains one year's worth of data for 142 countries.
2022-11-11 22:00:44 +08:00
We can list them all with the appropriate call to `list.files()`:
2022-09-17 23:58:18 +08:00
2022-09-16 03:56:12 +08:00
```{r}
2022-11-11 22:00:44 +08:00
paths <- list.files("data/gapminder", pattern = "[.]xlsx$", full.names = TRUE)
2022-09-17 23:58:18 +08:00
paths
2022-09-16 03:56:12 +08:00
```
2016-03-10 22:46:06 +08:00
2022-11-09 05:29:57 +08:00
### Lists
2016-03-10 22:46:06 +08:00
2022-11-09 06:19:14 +08:00
Now that we have these 12 paths, we could call `read_excel()` 12 times to get 12 data frames:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-10 21:38:20 +08:00
#| eval: false
2022-11-09 06:19:14 +08:00
gapminder_1952 <- readxl::read_excel("data/gapminder/1952.xlsx")
gapminder_1957 <- readxl::read_excel("data/gapminder/1957.xlsx")
gapminder_1962 <- readxl::read_excel("data/gapminder/1962.xlsx")
2022-11-11 22:00:44 +08:00
...,
2022-11-09 06:19:14 +08:00
gapminder_2007 <- readxl::read_excel("data/gapminder/2007.xlsx")
```
2022-11-11 22:00:44 +08:00
But putting each sheet into its own variable is going to make it hard to work with them a few steps down the road.
2022-11-09 06:19:14 +08:00
Instead, they'll be easier to work with if we put them into a single object.
A list is the perfect tool for this job:
```{r}
#| eval: false
files <- list(
readxl::read_excel("data/gapminder/1952.xlsx"),
readxl::read_excel("data/gapminder/1957.xlsx"),
readxl::read_excel("data/gapminder/1962.xlsx"),
2022-09-17 23:58:18 +08:00
...,
2022-11-09 06:19:14 +08:00
readxl::read_excel("data/gapminder/2007.xlsx")
2022-09-17 23:58:18 +08:00
)
```
2022-11-09 06:19:14 +08:00
```{r}
#| include: false
files <- map(paths, readxl::read_excel)
```
Now that you have these data frames in a list, how do you get one out?
2023-05-26 11:27:15 +08:00
You can use `files[[i]]` to extract the i<sup>th</sup> element:
2022-11-09 06:19:14 +08:00
```{r}
files[[3]]
```
We'll come back to `[[` in more detail in @sec-subset-one.
2022-11-09 05:29:57 +08:00
### `purrr::map()` and `list_rbind()`
2022-11-11 22:00:44 +08:00
The code to collect those data frames in a list "by hand" is basically just as tedious to type as code that reads the files one-by-one.
Happily, we can use `purrr::map()` to make even better use of our `paths` vector.
`map()` is similar to`across()`, but instead of doing something to each column in a data frame, it does something to each element of a vector.`map(x, f)` is shorthand for:
2022-09-17 23:58:18 +08:00
```{r}
#| eval: false
list(
f(x[[1]]),
f(x[[2]]),
...,
f(x[[n]])
)
```
2023-03-25 00:11:55 +08:00
So we can use `map()` to get a list of 12 data frames:
2022-09-17 23:58:18 +08:00
```{r}
files <- map(paths, readxl::read_excel)
length(files)
files[[1]]
```
2022-12-11 03:38:07 +08:00
(This is another data structure that doesn't display particularly compactly with `str()` so you might want to load it into RStudio and inspect it with `View()`).
2022-09-17 23:58:18 +08:00
2022-09-20 22:13:51 +08:00
Now we can use `purrr::list_rbind()` to combine that list of data frames into a single data frame:
2022-09-17 23:58:18 +08:00
```{r}
list_rbind(files)
```
2022-12-11 03:38:07 +08:00
Or we could do both steps at once in a pipeline:
2022-09-17 23:58:18 +08:00
```{r}
#| results: false
2022-09-10 21:38:20 +08:00
paths |>
2022-09-17 23:58:18 +08:00
map(readxl::read_excel) |>
2022-09-10 21:38:20 +08:00
list_rbind()
2016-03-01 22:29:58 +08:00
```
2022-09-17 23:58:18 +08:00
What if we want to pass in extra arguments to `read_excel()`?
2022-09-22 23:43:21 +08:00
We use the same technique that we used with `across()`.
2022-12-11 03:38:07 +08:00
For example, it's often useful to peak at the first few rows of the data with `n_max = 1`:
2022-09-17 23:58:18 +08:00
```{r}
paths |>
map(\(path) readxl::read_excel(path, n_max = 1)) |>
list_rbind()
```
2023-04-17 21:13:07 +08:00
This makes it clear that something is missing: there's no `year` column because that value is recorded in the path, not in the individual files.
2022-09-20 22:13:51 +08:00
We'll tackle that problem next.
2022-09-17 23:58:18 +08:00
2022-09-25 22:26:22 +08:00
### Data in the path {#sec-data-in-the-path}
2016-03-01 22:29:58 +08:00
2022-12-11 03:38:07 +08:00
Sometimes the name of the file is data itself.
2022-09-22 23:43:21 +08:00
In this example, the file name contains the year, which is not otherwise recorded in the individual files.
2022-12-11 03:38:07 +08:00
To get that column into the final data frame, we need to do two things:
2022-09-22 23:43:21 +08:00
2022-11-09 05:29:57 +08:00
First, we name the vector of paths.
2022-09-20 22:13:51 +08:00
The easiest way to do this is with the `set_names()` function, which can take a function.
2022-09-22 23:43:21 +08:00
Here we use `basename()` to extract just the file name from the full path:
2022-09-17 23:58:18 +08:00
```{r}
2022-11-09 06:19:14 +08:00
paths |> set_names(basename)
2022-09-17 23:58:18 +08:00
```
2022-11-11 22:00:44 +08:00
Those names are automatically carried along by all the map functions, so the list of data frames will have those same names:
2016-03-01 22:29:58 +08:00
2022-11-09 06:19:14 +08:00
```{r}
files <- paths |>
set_names(basename) |>
map(readxl::read_excel)
```
That makes this call to `map()` shorthand for:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-10 21:38:20 +08:00
#| eval: false
2022-11-09 06:19:14 +08:00
files <- list(
"1952.xlsx" = readxl::read_excel("data/gapminder/1952.xlsx"),
"1957.xlsx" = readxl::read_excel("data/gapminder/1957.xlsx"),
"1962.xlsx" = readxl::read_excel("data/gapminder/1962.xlsx"),
...,
"2007.xlsx" = readxl::read_excel("data/gapminder/2007.xlsx")
)
```
You can also use `[[` to extract elements by name:
```{r}
files[["1962.xlsx"]]
2022-09-17 23:58:18 +08:00
```
2022-11-09 05:29:57 +08:00
Then we use the `names_to` argument to `list_rbind()` to tell it to save the names into a new column called `year` then use `readr::parse_number()` to extract the number from the string.
2022-09-17 23:58:18 +08:00
```{r}
2022-09-10 21:38:20 +08:00
paths |>
2022-09-16 03:56:12 +08:00
set_names(basename) |>
2022-09-17 23:58:18 +08:00
map(readxl::read_excel) |>
list_rbind(names_to = "year") |>
mutate(year = parse_number(year))
2016-03-01 22:29:58 +08:00
```
2022-11-09 05:29:57 +08:00
In more complicated cases, there might be other variables stored in the directory name, or maybe the file name contains multiple bits of data.
In that case, use `set_names()` (without any arguments) to record the full path, and then use `tidyr::separate_wider_delim()` and friends to turn them into useful columns.
2016-03-01 22:29:58 +08:00
2022-09-17 23:58:18 +08:00
```{r}
paths |>
set_names() |>
map(readxl::read_excel) |>
list_rbind(names_to = "year") |>
2022-11-09 05:29:57 +08:00
separate_wider_delim(year, delim = "/", names = c(NA, "dir", "file")) |>
separate_wider_delim(file, delim = ".", names = c("file", "ext"))
2022-09-17 23:58:18 +08:00
```
2016-03-01 22:29:58 +08:00
2022-09-20 22:13:51 +08:00
### Save your work
2016-03-01 22:29:58 +08:00
2022-09-22 23:43:21 +08:00
Now that you've done all this hard work to get to a nice tidy data frame, it's a great time to save your work:
2016-03-01 22:29:58 +08:00
2022-09-22 23:43:21 +08:00
```{r}
gapminder <- paths |>
set_names(basename) |>
map(readxl::read_excel) |>
list_rbind(names_to = "year") |>
mutate(year = parse_number(year))
write_csv(gapminder, "gapminder.csv")
```
2022-11-09 05:29:57 +08:00
Now when you come back to this problem in the future, you can read in a single csv file.
2023-03-01 21:45:54 +08:00
For large and richer datasets, using parquet might be a better choice than `.csv`, as discussed in @sec-parquet.
2022-11-09 05:29:57 +08:00
2022-09-22 23:43:21 +08:00
```{r}
#| include: false
unlink("gapminder.csv")
```
2023-05-26 11:27:15 +08:00
If you're working in a project, we suggest calling the file that does this sort of data prep work something like `0-cleanup.R`.
2023-01-23 21:48:36 +08:00
The `0` in the file name suggests that this should be run before anything else.
2022-09-22 23:43:21 +08:00
2022-11-11 22:00:44 +08:00
If your input data files change over time, you might consider learning a tool like [targets](https://docs.ropensci.org/targets/) to set up your data cleaning code to automatically re-run whenever one of the input files is modified.
2022-09-20 22:13:51 +08:00
### Many simple iterations
2022-09-22 23:43:21 +08:00
Here we've just loaded the data directly from disk, and were lucky enough to get a tidy dataset.
2022-12-11 03:38:07 +08:00
In most cases, you'll need to do some additional tidying, and you have two basic options: you can do one round of iteration with a complex function, or do multiple rounds of iteration with simple functions.
2022-09-22 23:43:21 +08:00
In our experience most folks reach first for one complex iteration, but you're often better by doing multiple simple iterations.
2022-09-20 22:13:51 +08:00
2022-09-22 23:43:21 +08:00
For example, imagine that you want to read in a bunch of files, filter out missing values, pivot, and then combine.
2022-12-11 03:38:07 +08:00
One way to approach the problem is to write a function that takes a file and does all those steps then call `map()` once:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-10 21:38:20 +08:00
#| eval: false
process_file <- function(path) {
df <- read_csv(path)
df |>
filter(!is.na(id)) |>
mutate(id = tolower(id)) |>
pivot_longer(jan:dec, names_to = "month")
2016-03-01 22:29:58 +08:00
}
2016-08-15 21:18:51 +08:00
2022-09-22 23:43:21 +08:00
paths |>
2022-09-10 21:38:20 +08:00
map(process_file) |>
list_rbind()
2016-03-01 22:29:58 +08:00
```
2022-11-09 05:29:57 +08:00
Alternatively, you could perform each step of `process_file()` to every file:
```{r}
#| eval: false
paths |>
map(read_csv) |>
map(\(df) df |> filter(!is.na(id))) |>
map(\(df) df |> mutate(id = tolower(id))) |>
map(\(df) df |> pivot_longer(jan:dec, names_to = "month")) |>
list_rbind()
```
2022-12-11 03:38:07 +08:00
We recommend this approach because it stops you getting fixated on getting the first file right before moving on to the rest.
2022-11-09 05:29:57 +08:00
By considering all of the data when doing tidying and cleaning, you're more likely to think holistically and end up with a higher quality result.
In this particular example, there's another optimization you could make, by binding all the data frames together earlier.
Then you can rely on regular dplyr behavior:
2016-03-01 22:29:58 +08:00
2016-03-24 22:09:09 +08:00
```{r}
2022-09-10 21:38:20 +08:00
#| eval: false
2022-09-22 23:43:21 +08:00
paths |>
2022-09-10 21:38:20 +08:00
map(read_csv) |>
2022-09-22 23:43:21 +08:00
list_rbind() |>
2022-09-10 21:38:20 +08:00
filter(!is.na(id)) |>
mutate(id = tolower(id)) |>
pivot_longer(jan:dec, names_to = "month")
2016-03-01 22:29:58 +08:00
```
2022-09-16 03:56:12 +08:00
### Heterogeneous data
2016-03-01 22:29:58 +08:00
2022-12-11 03:38:07 +08:00
Unfortunately, sometimes it's not possible to go from `map()` straight to `list_rbind()` because the data frames are so heterogeneous that `list_rbind()` either fails or yields a data frame that's not very useful.
2022-09-22 23:43:21 +08:00
In that case, it's still useful to start by loading all of the files:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-10 21:38:20 +08:00
#| eval: false
2022-09-22 23:43:21 +08:00
files <- paths |>
map(readxl::read_excel)
2016-03-01 22:29:58 +08:00
```
2022-12-11 03:38:07 +08:00
Then a very useful strategy is to capture the structure of the data frames so that you can explore it using your data science skills.
2023-03-01 21:45:54 +08:00
One way to do so is with this handy `df_types` function[^iteration-6] that returns a tibble with one row for each column:
2023-04-17 21:13:07 +08:00
[^iteration-6]: We're not going to explain how it works, but if you look at the docs for the functions used, you should be able to puzzle it out.
2021-02-21 23:40:40 +08:00
2022-09-20 22:13:51 +08:00
```{r}
df_types <- function(df) {
tibble(
col_name = names(df),
2022-09-22 23:43:21 +08:00
col_type = map_chr(df, vctrs::vec_ptype_full),
n_miss = map_int(df, \(x) sum(is.na(x)))
2022-09-20 22:13:51 +08:00
)
}
2016-03-01 22:29:58 +08:00
2023-03-01 21:45:54 +08:00
df_types(gapminder)
2022-09-20 22:13:51 +08:00
```
2021-02-21 23:40:40 +08:00
2022-12-11 03:38:07 +08:00
You can then apply this function to all of the files, and maybe do some pivoting to make it easier to see where the differences are.
2022-11-09 05:29:57 +08:00
For example, this makes it easy to verify that the gapminder spreadsheets that we've been working with are all quite homogeneous:
2016-03-01 22:29:58 +08:00
2022-09-10 21:38:20 +08:00
```{r}
2022-09-20 22:13:51 +08:00
files |>
map(df_types) |>
list_rbind(names_to = "file_name") |>
2022-09-22 23:43:21 +08:00
select(-n_miss) |>
2022-09-20 22:13:51 +08:00
pivot_wider(names_from = col_name, values_from = col_type)
2022-09-10 21:38:20 +08:00
```
2016-03-01 22:29:58 +08:00
2022-12-11 03:38:07 +08:00
If the files have heterogeneous formats, you might need to do more processing before you can successfully merge them.
Unfortunately, we're now going to leave you to figure that out on your own, but you might want to read about `map_if()` and `map_at()`.
2022-09-22 23:43:21 +08:00
`map_if()` allows you to selectively modify elements of a list based on their values; `map_at()` allows you to selectively modify elements based on their names.
2016-03-01 22:29:58 +08:00
2022-09-10 21:38:20 +08:00
### Handling failures
2016-03-01 22:29:58 +08:00
2022-09-20 22:13:51 +08:00
Sometimes the structure of your data might be sufficiently wild that you can't even read all the files with a single command.
2023-05-26 11:27:15 +08:00
And then you'll encounter one of the downsides of `map()`: it succeeds or fails as a whole.
2022-11-09 05:29:57 +08:00
`map()` will either successfully read all of the files in a directory or fail with an error, reading zero files.
2021-02-21 23:40:40 +08:00
This is annoying: why does one failure prevent you from accessing all the other successes?
2016-03-01 22:29:58 +08:00
2022-09-22 23:43:21 +08:00
Luckily, purrr comes with a helper to tackle this problem: `possibly()`.
2022-11-09 05:29:57 +08:00
`possibly()` is what's known as a function operator: it takes a function and returns a function with modified behavior.
In particular, `possibly()` changes a function from erroring to returning a value that you specify:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-20 22:13:51 +08:00
files <- paths |>
map(possibly(\(path) readxl::read_excel(path), NULL))
2016-03-01 22:29:58 +08:00
2022-09-20 22:13:51 +08:00
data <- files |> list_rbind()
2022-09-10 21:38:20 +08:00
```
2022-11-09 05:29:57 +08:00
This works particularly well here because `list_rbind()`, like many tidyverse functions, automatically ignores `NULL`s.
2023-05-25 02:17:55 +08:00
Now you have all the data that can be read easily, and it's time to tackle the hard part of figuring out why some files failed to load and what to do about it.
2022-09-20 22:13:51 +08:00
Start by getting the paths that failed:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-20 22:13:51 +08:00
failed <- map_vec(files, is.null)
paths[failed]
2016-03-01 22:29:58 +08:00
```
2022-09-22 23:43:21 +08:00
Then call the import function again for each failure and figure out what went wrong.
2016-03-01 22:29:58 +08:00
2022-09-24 06:02:53 +08:00
## Saving multiple outputs
2016-03-01 22:29:58 +08:00
2022-09-24 06:02:53 +08:00
In the last section, you learned about `map()`, which is useful for reading multiple files into a single object.
2022-11-09 05:29:57 +08:00
In this section, we'll now explore sort of the opposite problem: how can you take one or more R objects and save it to one or more files?
2022-09-24 06:02:53 +08:00
We'll explore this challenge using three examples:
2022-09-16 04:28:54 +08:00
2022-09-24 06:02:53 +08:00
- Saving multiple data frames into one database.
2022-12-11 03:38:07 +08:00
- Saving multiple data frames into multiple `.csv` files.
2022-09-24 06:02:53 +08:00
- Saving multiple plots to multiple `.png` files.
2021-02-21 23:40:40 +08:00
2022-09-20 22:13:51 +08:00
### Writing to a database {#sec-save-database}
2021-02-21 23:40:40 +08:00
2022-11-09 05:29:57 +08:00
Sometimes when working with many files at once, it's not possible to fit all your data into memory at once, and you can't do `map(files, read_csv)`.
2022-12-11 03:38:07 +08:00
One approach to deal with this problem is to load your data into a database so you can access just the bits you need with dbplyr.
2022-09-16 04:28:54 +08:00
2022-11-11 22:00:44 +08:00
If you're lucky, the database package you're using will provide a handy function that takes a vector of paths and loads them all into the database.
2022-09-16 04:28:54 +08:00
This is the case with duckdb's `duckdb_read_csv()`:
2016-03-01 22:29:58 +08:00
```{r}
2022-09-10 21:38:20 +08:00
#| eval: false
2022-09-20 22:13:51 +08:00
con <- DBI::dbConnect(duckdb::duckdb())
duckdb::duckdb_read_csv(con, "gapminder", paths)
2016-03-01 22:29:58 +08:00
```
2022-11-11 22:00:44 +08:00
This would work well here, but we don't have csv files, instead we have excel spreadsheets.
2022-09-20 22:13:51 +08:00
So we're going to have to do it "by hand".
2022-11-11 22:00:44 +08:00
Learning to do it by hand will also help you when you have a bunch of csvs and the database that you're working with doesn't have one function that will load them all in.
2022-09-20 22:13:51 +08:00
2022-09-24 06:02:53 +08:00
We need to start by creating a table that will fill in with data.
2022-11-09 05:29:57 +08:00
The easiest way to do this is by creating a template, a dummy data frame that contains all the columns we want, but only a sampling of the data.
For the gapminder data, we can make that template by reading a single file and adding the year to it:
2016-03-01 22:29:58 +08:00
2022-05-14 04:46:49 +08:00
```{r}
2022-11-09 05:29:57 +08:00
template <- readxl::read_excel(paths[[1]])
2022-09-20 22:13:51 +08:00
template$year <- 1952
2022-09-24 06:02:53 +08:00
template
```
2022-09-20 22:13:51 +08:00
2022-12-11 03:38:07 +08:00
Now we can connect to the database, and use `DBI::dbCreateTable()` to turn our template into a database table:
2022-09-24 06:02:53 +08:00
```{r}
con <- DBI::dbConnect(duckdb::duckdb())
2022-09-20 22:13:51 +08:00
DBI::dbCreateTable(con, "gapminder", template)
2022-09-16 04:28:54 +08:00
```
2022-11-11 22:00:44 +08:00
`dbCreateTable()` doesn't use the data in `template`, just the variable names and types.
2022-11-09 05:29:57 +08:00
So if we inspect the `gapminder` table now you'll see that it's empty but it has the variables we need with the types we expect:
2022-09-16 04:28:54 +08:00
```{r}
2022-09-20 22:13:51 +08:00
con |> tbl("gapminder")
```
2022-11-11 22:00:44 +08:00
Next, we need a function that takes a single file path, reads it into R, and adds the result to the `gapminder` table.
2022-11-09 05:29:57 +08:00
We can do that by combining `read_excel()` with `DBI::dbAppendTable()`:
2022-09-16 04:28:54 +08:00
2022-09-20 22:13:51 +08:00
```{r}
append_file <- function(path) {
df <- readxl::read_excel(path)
df$year <- parse_number(basename(path))
DBI::dbAppendTable(con, "gapminder", df)
}
2022-09-16 04:28:54 +08:00
```
2023-01-20 21:55:08 +08:00
Now we need to call `append_file()` once for each element of `paths`.
2022-09-24 06:02:53 +08:00
That's certainly possible with `map()`:
2016-03-01 22:29:58 +08:00
2022-09-16 04:28:54 +08:00
```{r}
#| eval: false
2022-09-20 22:13:51 +08:00
paths |> map(append_file)
2022-09-16 04:28:54 +08:00
```
2022-11-09 05:29:57 +08:00
But we don't care about the output of `append_file()`, so instead of `map()` it's slightly nicer to use `walk()`.
2022-09-24 06:02:53 +08:00
`walk()` does exactly the same thing as `map()` but throws the output away:
2022-09-16 04:28:54 +08:00
```{r}
2022-09-20 22:13:51 +08:00
paths |> walk(append_file)
```
2022-11-11 22:00:44 +08:00
Now we can see if we have all the data in our table:
2022-09-20 22:13:51 +08:00
```{r}
2022-09-24 06:02:53 +08:00
con |>
tbl("gapminder") |>
count(year)
2022-09-20 22:13:51 +08:00
```
2022-11-11 22:00:44 +08:00
```{r}
#| include: false
2022-09-20 22:13:51 +08:00
DBI::dbDisconnect(con, shutdown = TRUE)
2016-03-01 22:29:58 +08:00
```
2022-09-16 04:28:54 +08:00
### Writing csv files
2022-09-24 06:02:53 +08:00
The same basic principle applies if we want to write multiple csv files, one for each group.
2022-11-11 22:00:44 +08:00
Let's imagine that we want to take the `ggplot2::diamonds` data and save one csv file for each `clarity`.
2022-09-16 04:28:54 +08:00
First we need to make those individual datasets.
2022-11-11 22:00:44 +08:00
There are many ways you could do that, but there's one way we particularly like: `group_nest()`.
2022-09-16 04:28:54 +08:00
```{r}
by_clarity <- diamonds |>
2022-11-08 00:05:05 +08:00
group_nest(clarity)
by_clarity
2022-09-16 04:28:54 +08:00
```
2022-11-08 00:05:05 +08:00
This gives us a new tibble with eight rows and two columns.
`clarity` is our grouping variable and `data` is a list-column containing one tibble for each unique value of `clarity`:
2022-09-16 04:28:54 +08:00
```{r}
2022-11-08 00:05:05 +08:00
by_clarity$data[[1]]
2022-09-16 04:28:54 +08:00
```
2022-12-11 03:38:07 +08:00
While we're here, let's create a column that gives the name of output file, using `mutate()` and `str_glue()`:
2022-09-16 04:28:54 +08:00
```{r}
2022-11-08 00:05:05 +08:00
by_clarity <- by_clarity |>
mutate(path = str_glue("diamonds-{clarity}.csv"))
2022-09-16 04:28:54 +08:00
2022-11-08 00:05:05 +08:00
by_clarity
2022-09-16 04:28:54 +08:00
```
2022-11-09 05:29:57 +08:00
So if we were going to save these data frames by hand, we might write something like:
2022-09-16 04:28:54 +08:00
2022-09-24 06:02:53 +08:00
```{r}
#| eval: false
2022-11-08 00:05:05 +08:00
write_csv(by_clarity$data[[1]], by_clarity$path[[1]])
write_csv(by_clarity$data[[2]], by_clarity$path[[2]])
write_csv(by_clarity$data[[3]], by_clarity$path[[3]])
2022-09-24 06:02:53 +08:00
...
2022-11-08 00:05:05 +08:00
write_csv(by_clarity$by_clarity[[8]], by_clarity$path[[8]])
2022-09-24 06:02:53 +08:00
```
2022-09-16 03:56:12 +08:00
2022-11-11 22:00:44 +08:00
This is a little different to our previous uses of `map()` because there are two arguments that are changing, not just one.
2022-11-09 05:29:57 +08:00
That means we need a new function: `map2()`, which varies both the first and second arguments.
And because we again don't care about the output, we want `walk2()` rather than `map2()`.
That gives us:
```{r}
walk2(by_clarity$data, by_clarity$path, write_csv)
```
2022-09-16 04:28:54 +08:00
```{r}
2022-09-24 06:02:53 +08:00
#| include: false
2022-11-08 00:05:05 +08:00
unlink(by_clarity$path)
2022-09-16 04:28:54 +08:00
```
2022-09-24 06:02:53 +08:00
### Saving plots
We can take the same basic approach to create many plots.
2022-11-08 00:05:05 +08:00
Let's first make a function that draws the plot we want:
2016-03-01 22:29:58 +08:00
2022-05-14 04:46:49 +08:00
```{r}
2023-05-26 23:23:14 +08:00
#| fig-alt: |
#| Histogram of carats of diamonds from the by_clarity dataset, ranging from
#| 0 to 5 carats. The distribution is unimodal and right skewed with a peak
#| around 1 carat.
2022-11-08 00:05:05 +08:00
carat_histogram <- function(df) {
2022-12-05 16:12:12 +08:00
ggplot(df, aes(x = carat)) + geom_histogram(binwidth = 0.1)
2022-11-08 00:05:05 +08:00
}
carat_histogram(by_clarity$data[[1]])
2022-09-16 03:56:12 +08:00
```
2023-03-01 21:45:54 +08:00
Now we can use `map()` to create a list of many plots[^iteration-7] and their eventual file paths:
2022-09-16 04:28:54 +08:00
2023-03-01 21:45:54 +08:00
[^iteration-7]: You can print `by_clarity$plot` to get a crude animation --- you'll get one plot for each element of `plots`.
2022-11-11 22:00:44 +08:00
NOTE: this didn't happen for me.
2022-09-16 03:56:12 +08:00
```{r}
2022-11-08 00:05:05 +08:00
by_clarity <- by_clarity |>
mutate(
plot = map(data, carat_histogram),
path = str_glue("clarity-{clarity}.png")
)
2022-09-16 04:28:54 +08:00
```
Then use `walk2()` with `ggsave()` to save each plot:
2016-03-01 22:29:58 +08:00
2022-09-16 04:28:54 +08:00
```{r}
2022-11-08 00:05:05 +08:00
walk2(
2022-11-11 22:00:44 +08:00
by_clarity$path,
by_clarity$plot,
2022-11-08 00:05:05 +08:00
\(path, plot) ggsave(path, plot, width = 6, height = 6)
)
2016-03-01 22:29:58 +08:00
```
2022-11-11 22:00:44 +08:00
This is shorthand for:
2022-09-16 04:28:54 +08:00
```{r}
#| eval: false
2022-11-08 00:05:05 +08:00
ggsave(by_clarity$path[[1]], by_clarity$plot[[1]], width = 6, height = 6)
ggsave(by_clarity$path[[2]], by_clarity$plot[[2]], width = 6, height = 6)
ggsave(by_clarity$path[[3]], by_clarity$plot[[3]], width = 6, height = 6)
2022-09-24 06:02:53 +08:00
...
2022-11-08 00:05:05 +08:00
ggsave(by_clarity$path[[8]], by_clarity$plot[[8]], width = 6, height = 6)
2022-09-16 04:28:54 +08:00
```
2022-09-24 06:02:53 +08:00
```{r}
#| include: false
2022-11-11 22:00:44 +08:00
unlink(by_clarity$path)
2022-09-24 06:02:53 +08:00
```
2022-09-16 04:28:54 +08:00
2022-11-11 22:00:44 +08:00
```{=html}
<!--
2022-09-16 04:28:54 +08:00
### Exercises
1. Imagine you have a table of student data containing (amongst other variables) `school_name` and `student_id`. Sketch out what code you'd write if you want to save all the information for each student in file called `{student_id}.csv` in the `{school}` directory.
2022-11-11 22:00:44 +08:00
-->
```
2022-09-22 23:43:21 +08:00
## Summary
2022-12-11 03:38:07 +08:00
In this chapter, you've seen how to use explicit iteration to solve three problems that come up frequently when doing data science: manipulating multiple columns, reading multiple files, and saving multiple outputs.
2022-11-11 22:00:44 +08:00
But in general, iteration is a super power: if you know the right iteration technique, you can easily go from fixing one problem to fixing all the problems.
Once you've mastered the techniques in this chapter, we highly recommend learning more by reading the [Functionals chapter](https://adv-r.hadley.nz/functionals.html) of *Advanced R* and consulting the [purrr website](https://purrr.tidyverse.org).
2022-09-24 06:02:53 +08:00
2022-12-11 03:38:07 +08:00
If you know much about iteration in other languages, you might be surprised that we didn't discuss the `for` loop.
2022-11-11 22:00:44 +08:00
That's because R's orientation towards data analysis changes how we iterate: in most cases you can rely on an existing idiom to do something to each columns or each group.
And when you can't, you can often use a functional programming tool like `map()` that does something to each element of a list.
However, you will see `for` loops in wild-caught code, so you'll learn about them in the next chapter where we'll discuss some important base R tools.