928 lines
31 KiB
Plaintext
928 lines
31 KiB
Plaintext
# Iteration {#sec-iteration}
|
|
|
|
```{r}
|
|
#| results: "asis"
|
|
#| echo: false
|
|
source("_common.R")
|
|
status("drafting")
|
|
```
|
|
|
|
## Introduction
|
|
|
|
In this chapter, you'll learn tools for iteration, repeatedly performing the same action on different objects.
|
|
You've already learned a number of special purpose tools for iteration:
|
|
|
|
- Manipulating each element of a vector with `+`, `-`, `*`, `/`, and friends.
|
|
- Drawing one plot with for each group with `facet_wrap()` and `facet_grid()`.
|
|
- Computing a summary statistic for each subgroup with `group_by()` and `summarise()`.
|
|
- Extracting each element in a named list with `unnest_wider()` and `unnest_longer()`.
|
|
|
|
Now it's time to learn some more general tools.
|
|
Tools for iteration can quickly become very abstract, but in this chapter we'll keep things concrete by focusing on three common tasks that you might use iteration for: modifying multiple columns, reading multiple files, and saving multiple objects.
|
|
We'll finish off with a brief discussion of how you might might the same tools in other cases.
|
|
|
|
### Prerequisites
|
|
|
|
::: callout-important
|
|
This chapter relies on features only found in purrr 1.0.0, which is still in development.
|
|
If you want to live life on the edge you can get the dev version with `devtools::install_github("tidyverse/purrr")`.
|
|
:::
|
|
|
|
In this chapter, we'll focus on tools provided by dplyr and purrr, both core members of the tidyverse.
|
|
You've seen dplyr before, but purrr is new.
|
|
We're going to use just a couple of purrr functions from in this chapter, but it's a great package to explore as you improve your programming skills.
|
|
|
|
```{r}
|
|
#| label: setup
|
|
#| message: false
|
|
|
|
library(tidyverse)
|
|
```
|
|
|
|
## Modifying multiple columns {#sec-across}
|
|
|
|
Imagine you have this simple tibble and you want to count the number of observations and compute the median of every column.
|
|
|
|
```{r}
|
|
df <- tibble(
|
|
a = rnorm(10),
|
|
b = rnorm(10),
|
|
c = rnorm(10),
|
|
d = rnorm(10)
|
|
)
|
|
```
|
|
|
|
You could do it with copy-and-paste:
|
|
|
|
```{r}
|
|
df |> summarise(
|
|
n = n(),
|
|
a = median(a),
|
|
b = median(b),
|
|
c = median(c),
|
|
d = median(d),
|
|
)
|
|
```
|
|
|
|
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 variables.
|
|
Instead you can use `across()`:
|
|
|
|
```{r}
|
|
df |> summarise(
|
|
n = n(),
|
|
across(a:d, median),
|
|
)
|
|
```
|
|
|
|
`across()` has three particularly important arguments, which we'll discuss in detail in the following sections.
|
|
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.
|
|
You also the `.names` argument when you need additional control over the output names, which is particularly important when you use `across()` with `mutate()`.
|
|
We'll also discuss two important variations, `if_any()` and `if_all()`, which work with `filter()`.
|
|
|
|
### Selecting columns with `.cols`
|
|
|
|
The first argument to `across()` selects the columns to transform.
|
|
This argument uses the same specifications as `select()`, @sec-select, so you can use functions like `starts_with()` and `ends_with()` to select variables based on their name.
|
|
|
|
There are two additional selection techniques that are particularly useful for `across()`: `everything()` and `where()`.
|
|
`everything()` is straightforward: it selects every (non-grouping) column:
|
|
|
|
```{r}
|
|
df <- tibble(
|
|
grp = sample(2, 10, replace = TRUE),
|
|
a = rnorm(10),
|
|
b = rnorm(10),
|
|
c = rnorm(10),
|
|
d = rnorm(10)
|
|
)
|
|
|
|
df |>
|
|
group_by(grp) |>
|
|
summarise(across(everything(), median))
|
|
```
|
|
|
|
Note grouping columns (`grp` here) are not included in `across()` because they're automatically preserved by `summarise()`.
|
|
|
|
`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.
|
|
|
|
```{r}
|
|
df <- tibble(
|
|
x1 = 1:3,
|
|
x2 = runif(3),
|
|
y1 = sample(letters, 3),
|
|
y2 = c("banana", "apple", "egg")
|
|
)
|
|
|
|
df |>
|
|
summarise(across(where(is.numeric), mean))
|
|
|
|
df |>
|
|
summarise(across(where(is.character), str_flatten))
|
|
```
|
|
|
|
Just like other selectors, you can combine these with Boolean algebra.
|
|
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".
|
|
|
|
### Defining the action with `.fns`
|
|
|
|
The second argument to `across()` defines how each column will be transformed.
|
|
In simple cases, this will be the name of existing function, but you might want to supply additional arguments or perform multiple transformations, as described below.
|
|
|
|
Lets motivate this problem with an simple example: what happens if we have some missing values in our data?
|
|
`median()` will preserve those missing values giving us a suboptimal output:
|
|
|
|
```{r}
|
|
rnorm_na <- function(n, n_na, mean = 0, sd = 1) {
|
|
sample(c(rnorm(n - n_na, mean = mean, sd = 1), rep(NA, n_na)))
|
|
}
|
|
|
|
df <- tibble(
|
|
a = rnorm_na(5, 1),
|
|
b = rnorm_na(5, 1),
|
|
c = rnorm_na(5, 2),
|
|
d = rnorm(5)
|
|
)
|
|
df |>
|
|
summarise(
|
|
across(a:d, median),
|
|
n = n()
|
|
)
|
|
```
|
|
|
|
It'd be nice to be able to 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 correct arguments:
|
|
|
|
```{r}
|
|
df |>
|
|
summarise(
|
|
across(a:d, function(x) median(x, na.rm = TRUE)),
|
|
n = n()
|
|
)
|
|
```
|
|
|
|
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-1]: Anonymous, because didn't give it a name with `<-.`
|
|
|
|
```{r}
|
|
#| results: false
|
|
df |>
|
|
summarise(
|
|
across(a:d, \(x) median(x, na.rm = TRUE)),
|
|
n = n()
|
|
)
|
|
```
|
|
|
|
In either case, `across()` effectively expands to the following code:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
|
|
df |> summarise(
|
|
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()
|
|
)
|
|
```
|
|
|
|
When we remove the missing values from the `median()`, it would be nice to know just how many values we were removing.
|
|
We can find that out by supplying two functions to `across()`: one to compute the median and the other to count the missing values.
|
|
You supply multiple functions by using a named list:
|
|
|
|
```{r}
|
|
df |>
|
|
summarise(
|
|
across(a:d, list(
|
|
median = \(x) median(x, na.rm = TRUE),
|
|
n_miss = \(x) sum(is.na(x))
|
|
)),
|
|
n = n()
|
|
)
|
|
```
|
|
|
|
If you look carefully, you might intuit that the columns are named using 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.
|
|
That's not a coincidence!
|
|
As you'll learn in the next section, you can use `.names` argument to supply your own glue spec.
|
|
|
|
### Column names
|
|
|
|
The result of `across()` is named according to the specification provided in the `.names` variable.
|
|
We could specify our own if we wanted the name of the function to come first[^iteration-2]:
|
|
|
|
[^iteration-2]: You can't currently change the order of the columns, but you could reorder them after the fact using `relocate()` or similar.
|
|
|
|
```{r}
|
|
df |>
|
|
summarise(
|
|
across(
|
|
a:d,
|
|
list(
|
|
median = \(x) median(x, na.rm = TRUE),
|
|
n_miss = \(x) sum(is.na(x))
|
|
),
|
|
.names = "{.fn}_{.col}"
|
|
),
|
|
n = n(),
|
|
)
|
|
```
|
|
|
|
The `.names` argument is particularly important when you use `across()` with `mutate()`.
|
|
By default the output of `across()` is given the same names as the inputs.
|
|
This means that `across()` inside of `mutate()` will replace existing columns.
|
|
For example, here we use `coalesce()` to replace `NA`s with `0`:
|
|
|
|
```{r}
|
|
df |>
|
|
mutate(
|
|
across(a:d, \(x) coalesce(x, 0))
|
|
)
|
|
```
|
|
|
|
If you'd like to instead create new columns, you can use the `.names` argument give the output new names:
|
|
|
|
```{r}
|
|
df |>
|
|
mutate(
|
|
across(a:d, \(x) x * 2, .names = "{.col}_double")
|
|
)
|
|
```
|
|
|
|
### Filtering
|
|
|
|
`across()` is a great match for `summarise()` and `mutate()` but it's not such a great fit for `filter()` because you usually string together calls to multiple functions either with `|` or `&`.
|
|
So dplyr provides two variants of `across()` called `if_any()` and `if_all()`:
|
|
|
|
```{r}
|
|
df |> filter(is.na(a) | is.na(b) | is.na(c) | is.na(d))
|
|
# same as:
|
|
df |> filter(if_any(a:d, is.na))
|
|
|
|
df |> filter(is.na(a) & is.na(b) & is.na(c) & is.na(d))
|
|
# same as:
|
|
df |> filter(if_all(a:d, is.na))
|
|
```
|
|
|
|
### `across()` in functions
|
|
|
|
`across()` is particularly useful to program with because it allows you to operate on multiple variables.
|
|
For example, [Jacob Scott](https://twitter.com/_wurli/status/1571836746899283969) uses this little helper to expand all date variables into year, month, and day variables:
|
|
|
|
```{r}
|
|
expand_dates <- function(df) {
|
|
df |>
|
|
mutate(
|
|
across(
|
|
where(lubridate::is.Date),
|
|
list(year = year, month = month, day = mday)
|
|
)
|
|
)
|
|
}
|
|
```
|
|
|
|
`across()` also makes it easy to supply multiple variables in a single argument because the first argument uses tidy-select; you just need to remember to embrace that argument.
|
|
For example, this function will compute the means of numeric variables by default.
|
|
But by supplying the second argument you can choose to summarize just selected variables:
|
|
|
|
```{r}
|
|
summarise_means <- function(df, summary_vars = where(is.numeric)) {
|
|
df |>
|
|
summarise(
|
|
across({{ summary_vars }}, \(x) mean(x, na.rm = TRUE)),
|
|
n = n()
|
|
)
|
|
}
|
|
diamonds |>
|
|
group_by(clarity) |>
|
|
summarise_means()
|
|
|
|
diamonds |>
|
|
group_by(clarity) |>
|
|
summarise_means(c(carat, x:z))
|
|
```
|
|
|
|
### Vs `pivot_longer()`
|
|
|
|
Before we go on, it's worth pointing out an interesting connection between `across()` and `pivot_longer()`.
|
|
In many cases, you perform the same calculations by first pivoting the data and then performing the operations by group rather than by column.
|
|
For example, we could rewrite our multiple summary `across()` as:
|
|
|
|
```{r}
|
|
df |>
|
|
pivot_longer(a:d) |>
|
|
group_by(name) |>
|
|
summarise(
|
|
median = median(value, na.rm = TRUE),
|
|
n_miss = sum(is.na(value))
|
|
)
|
|
```
|
|
|
|
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 variables that you want to compute with simultaneously.
|
|
For example, imagine that our data frame contains both values and weights and we want to compute a weighted mean:
|
|
|
|
```{r}
|
|
df3 <- tibble(
|
|
a_val = rnorm(10),
|
|
a_w = runif(10),
|
|
b_val = rnorm(10),
|
|
b_w = runif(10),
|
|
c_val = rnorm(10),
|
|
c_w = runif(10),
|
|
d_val = rnorm(10),
|
|
d_w = runif(10)
|
|
)
|
|
```
|
|
|
|
There's currently no way to do this with `across()`[^iteration-3], but it's relatively straightforward with `pivot_longer()`:
|
|
|
|
[^iteration-3]: Maybe there will be one day, but currently we don't see how.
|
|
|
|
```{r}
|
|
df3_long <- df3 |>
|
|
pivot_longer(
|
|
everything(),
|
|
names_to = c("group", ".value"),
|
|
names_sep = "_"
|
|
)
|
|
df3_long
|
|
|
|
df3_long |>
|
|
group_by(group) |>
|
|
summarise(mean = weighted.mean(val, w))
|
|
```
|
|
|
|
If needed, you could `pivot_wider()` this back to the original form.
|
|
|
|
### Exercises
|
|
|
|
1. Compute the number of unique values in each column of `palmerpenguins::penguins`.
|
|
|
|
2. Compute the mean of every column in `mtcars`.
|
|
|
|
3. Group `diamonds` by `cut`, `clarity`, and `color` then count the number of observations and the mean of each numeric variable.
|
|
|
|
4. What happens if you use a list of functions, but don't name them?
|
|
How is the output named?
|
|
|
|
5. It is possible to use `across()` inside `filter()` where it's equivalent to `if_all()`.
|
|
Can you explain why?
|
|
|
|
6. Adjust `expand_dates()` to automatically remove the date columns after they've been expanded.
|
|
Do you need to embrace any arguments?
|
|
|
|
7. Explain what each step of the pipeline in this function does.
|
|
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 }})) |>
|
|
summarise(
|
|
across({{ summary_vars }}, \(x) sum(is.na(x))),
|
|
.groups = "drop"
|
|
) |>
|
|
select(where(\(x) any(x > 0)))
|
|
}
|
|
nycflights13::flights |> show_missing(c(year, month, day))
|
|
```
|
|
|
|
## Reading multiple files
|
|
|
|
In the previous section, you learn how to use `dplyr::across()` to repeat a transformation on multiple columns.
|
|
In this section, you'll learn how to use `purrr::map()` to do something to every file in a directory.
|
|
Let's start with a little motivation: imagine you have a directory full of excel spreadsheets[^iteration-4] you want to read.
|
|
You could do it with copy and paste:
|
|
|
|
[^iteration-4]: If you instead had a directory of csv files with the same format, you can use the technique from @sec-readr-directory.
|
|
|
|
```{r}
|
|
#| eval: false
|
|
data2019 <- readr::read_excel("data/y2019.xls")
|
|
data2020 <- readr::read_excel("data/y2020.xls")
|
|
data2021 <- readr::read_excel("data/y2021.xls")
|
|
data2022 <- readr::read_excel("data/y2022.xls")
|
|
```
|
|
|
|
And then use `dplyr::bind_rows()` to combine them all together:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
data <- bind_rows(data2019, data2020, data2021, data2022)
|
|
```
|
|
|
|
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.
|
|
There are three basic steps: use `dir()` 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.
|
|
We'll then discuss how you can handle situations of increasing heterogeneity, where you can't do exactly the same thing to every file.
|
|
|
|
### Listing files in a directory
|
|
|
|
`dir()` lists the files in a directory.
|
|
You'll almost always use three arguments:
|
|
|
|
- The first argument, `path`, is the directory to look in.
|
|
|
|
- `pattern` is a regular expression used to filter the file names.
|
|
The most common pattern is something like `\\.xlsx$` or `\\.csv$` to find all files with a specified extension.
|
|
|
|
- `full.names` determines whether or not the directory name should be included in the output.
|
|
You almost always want this to be `TRUE`.
|
|
|
|
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.
|
|
We can list them all with the appropriate call to `dir()`:
|
|
|
|
```{r}
|
|
paths <- dir("data/gapminder", pattern = "\\.xlsx$", full.names = TRUE)
|
|
paths
|
|
```
|
|
|
|
### Lists
|
|
|
|
Now that we have these 12 paths, we could call `read_excel()` 12 times to get 12 data frames.
|
|
In general, we won't know how files there are to read, so instead of saving each data frame to its own variable, we'll put them all into a list, something like this:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
list(
|
|
readxl::read_excel("data/gapminder/1952.xls"),
|
|
readxl::read_excel("data/gapminder/1957.xls"),
|
|
readxl::read_excel("data/gapminder/1962.xls"),
|
|
...,
|
|
readxl::read_excel("data/gapminder/2007.xls")
|
|
)
|
|
```
|
|
|
|
Something about `[[`
|
|
|
|
### `purrr::map()` and `list_rbind()`
|
|
|
|
Now that's just as tedious to type as before, but we can use a shortcut: `purrr::map()`.
|
|
`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:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
list(
|
|
f(x[[1]]),
|
|
f(x[[2]]),
|
|
...,
|
|
f(x[[n]])
|
|
)
|
|
```
|
|
|
|
So we can use `map()` get a list of 12 data frames:
|
|
|
|
```{r}
|
|
files <- map(paths, readxl::read_excel)
|
|
length(files)
|
|
|
|
files[[1]]
|
|
```
|
|
|
|
(This is another data structure that doesn't display particularly compactly with `str()` so you might want to load into RStudio and inspect it with `View()`).
|
|
|
|
Now we can use `purrr::list_rbind()` to combine that list of data frames into a single data frame:
|
|
|
|
```{r}
|
|
list_rbind(files)
|
|
```
|
|
|
|
Or we could do both steps at once in pipeline:
|
|
|
|
```{r}
|
|
#| results: false
|
|
paths |>
|
|
map(readxl::read_excel) |>
|
|
list_rbind()
|
|
```
|
|
|
|
What if we want to pass in extra arguments to `read_excel()`?
|
|
We use the same technique that we used with `across()`.
|
|
For example, it's often useful to peak at the first few row of the data with `n_max = 1`:
|
|
|
|
```{r}
|
|
paths |>
|
|
map(\(path) readxl::read_excel(path, n_max = 1)) |>
|
|
list_rbind()
|
|
```
|
|
|
|
This makes it clear that something is missing: there's no `year` column because that value is recorded in the path, not the individual files.
|
|
We'll tackle that problem next.
|
|
|
|
### Data in the path {#sec-data-in-the-path}
|
|
|
|
Sometimes the name of the file is itself data.
|
|
In this example, the file name contains the year, which is not otherwise recorded in the individual files.
|
|
To get that column into the final data frame, we need to do two things.
|
|
|
|
First, we name the vector of paths.
|
|
The easiest way to do this is with the `set_names()` function, which can take a function.
|
|
Here we use `basename()` to extract just the file name from the full path:
|
|
|
|
```{r}
|
|
paths <- paths |> set_names(basename)
|
|
paths
|
|
```
|
|
|
|
Those paths are automatically carried along by all the map functions, so the list of data frames will have those same names:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
paths |>
|
|
map(readxl::read_excel) |>
|
|
names()
|
|
```
|
|
|
|
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.
|
|
|
|
```{r}
|
|
paths |>
|
|
set_names(basename) |>
|
|
map(readxl::read_excel) |>
|
|
list_rbind(names_to = "year") |>
|
|
mutate(year = parse_number(year))
|
|
```
|
|
|
|
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.
|
|
|
|
```{r}
|
|
paths |>
|
|
set_names() |>
|
|
map(readxl::read_excel) |>
|
|
list_rbind(names_to = "year") |>
|
|
separate_wider_delim(year, delim = "/", names = c(NA, "dir", "file")) |>
|
|
separate_wider_delim(file, delim = ".", names = c("file", "ext"))
|
|
```
|
|
|
|
### Save your work
|
|
|
|
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:
|
|
|
|
```{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")
|
|
```
|
|
|
|
Now when you come back to this problem in the future, you can read in a single csv file.
|
|
|
|
```{r}
|
|
#| include: false
|
|
unlink("gapminder.csv")
|
|
```
|
|
|
|
If you're working in a project, we'd suggest calling the file that does this sort of data prep work something like `0-cleanup.R.` The `0` in the file name suggests that this should be run before anything else.
|
|
|
|
If your input data files change of 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 when ever one of the input files is modified.
|
|
|
|
### Many simple iterations
|
|
|
|
Here we've just loaded the data directly from disk, and were lucky enough to get a tidy dataset.
|
|
In most cases, you'll need to do some additional tidying, and you have two basic basic options: you can do one round of iteration with a complex function, or do a multiple rounds of iteration with simple functions.
|
|
In our experience most folks reach first for one complex iteration, but you're often better by doing multiple simple iterations.
|
|
|
|
For example, imagine that you want to read in a bunch of files, filter out missing values, pivot, and then combine.
|
|
One way to approach the problem is write a function that takes a file and does all those steps then call `map()` once:
|
|
|
|
```{r}
|
|
#| 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")
|
|
}
|
|
|
|
paths |>
|
|
map(process_file) |>
|
|
list_rbind()
|
|
```
|
|
|
|
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()
|
|
```
|
|
|
|
We recommend this approach because it stops you getting fixated on getting the first file right because moving on to the rest.
|
|
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:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
paths |>
|
|
map(read_csv) |>
|
|
list_rbind() |>
|
|
filter(!is.na(id)) |>
|
|
mutate(id = tolower(id)) |>
|
|
pivot_longer(jan:dec, names_to = "month")
|
|
```
|
|
|
|
### Heterogeneous data
|
|
|
|
Unfortunately it's sometime 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.
|
|
In that case, it's still useful to start by loading all of the files:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
files <- paths |>
|
|
map(readxl::read_excel)
|
|
```
|
|
|
|
Then a very useful strategy is to capture the structure of the data frames to data so that you can explore it using your data science skills.
|
|
One way to do so is with this handy `df_types` function that returns a tibble with one row for each column:
|
|
|
|
```{r}
|
|
df_types <- function(df) {
|
|
tibble(
|
|
col_name = names(df),
|
|
col_type = map_chr(df, vctrs::vec_ptype_full),
|
|
n_miss = map_int(df, \(x) sum(is.na(x)))
|
|
)
|
|
}
|
|
|
|
df_types(starwars)
|
|
df_types(nycflights13::flights)
|
|
```
|
|
|
|
You can then apply this function all of the files, and maybe do some pivoting to make it easy to see where there are differences.
|
|
For example, this makes it easy to verify that the gapminder spreadsheets that we've been working with are all quite homogeneous:
|
|
|
|
```{r}
|
|
files |>
|
|
map(df_types) |>
|
|
list_rbind(names_to = "file_name") |>
|
|
select(-n_miss) |>
|
|
pivot_wider(names_from = col_name, values_from = col_type)
|
|
```
|
|
|
|
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()`.
|
|
`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.
|
|
|
|
### Handling failures
|
|
|
|
Sometimes the structure of your data might be sufficiently wild that you can't even read all the files with a single command.
|
|
And then you'll encounter one of the downsides of map: it succeeds or fails as a whole.
|
|
`map()` will either successfully read all of the files in a directory or fail with an error, reading zero files.
|
|
This is annoying: why does one failure prevent you from accessing all the other successes?
|
|
|
|
Luckily, purrr comes with a helper to tackle this problem: `possibly()`.
|
|
`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:
|
|
|
|
```{r}
|
|
files <- paths |>
|
|
map(possibly(\(path) readxl::read_excel(path), NULL))
|
|
|
|
data <- files |> list_rbind()
|
|
```
|
|
|
|
This works particularly well here because `list_rbind()`, like many tidyverse functions, automatically ignores `NULL`s.
|
|
|
|
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 load and what do to about it.
|
|
Start by getting the paths that failed:
|
|
|
|
```{r}
|
|
failed <- map_vec(files, is.null)
|
|
paths[failed]
|
|
```
|
|
|
|
Then call the import function again for each failure and figure out what went wrong.
|
|
|
|
## Saving multiple outputs
|
|
|
|
In the last section, you learned about `map()`, which is useful for reading multiple files into a single object.
|
|
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?
|
|
We'll explore this challenge using three examples:
|
|
|
|
- Saving multiple data frames into one database.
|
|
- Saving multiple data frames into multiple csv files.
|
|
- Saving multiple plots to multiple `.png` files.
|
|
|
|
### Writing to a database {#sec-save-database}
|
|
|
|
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)`.
|
|
One approach to deal with this problem is to load your into a database so you can access just the bits you need with dbplyr.
|
|
|
|
If you're lucky, the database package will provide a handy function that will take a vector of paths and load them all into the database.
|
|
This is the case with duckdb's `duckdb_read_csv()`:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
con <- DBI::dbConnect(duckdb::duckdb())
|
|
duckdb::duckdb_read_csv(con, "gapminder", paths)
|
|
```
|
|
|
|
This would work great here, but we don't have csv files, we have excel spreadsheets.
|
|
So we're going to have to do it "by hand".
|
|
And 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.
|
|
|
|
We need to start by creating a table that will fill in with data.
|
|
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:
|
|
|
|
```{r}
|
|
template <- readxl::read_excel(paths[[1]])
|
|
template$year <- 1952
|
|
template
|
|
```
|
|
|
|
Now we can connect to the database, and use `DBI::dbCreateTable()` to turn our template into database table:
|
|
|
|
```{r}
|
|
con <- DBI::dbConnect(duckdb::duckdb())
|
|
DBI::dbCreateTable(con, "gapminder", template)
|
|
```
|
|
|
|
`dbCreateTable()` doesn't use the data in `template`, just variable names and types.
|
|
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:
|
|
|
|
```{r}
|
|
con |> tbl("gapminder")
|
|
```
|
|
|
|
Next, we need a function that takes a single file path and reads it into R, and adds it to the `gapminder` table.
|
|
We can do that by combining `read_excel()` with `DBI::dbAppendTable()`:
|
|
|
|
```{r}
|
|
append_file <- function(path) {
|
|
df <- readxl::read_excel(path)
|
|
df$year <- parse_number(basename(path))
|
|
|
|
DBI::dbAppendTable(con, "gapminder", df)
|
|
}
|
|
```
|
|
|
|
Now we need to call `append_csv()` once for `path`.
|
|
That's certainly possible with `map()`:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
paths |> map(append_file)
|
|
```
|
|
|
|
But we don't care about the output of `append_file()`, so instead of `map()` it's slightly nicer to use `walk()`.
|
|
`walk()` does exactly the same thing as `map()` but throws the output away:
|
|
|
|
```{r}
|
|
paths |> walk(append_file)
|
|
```
|
|
|
|
Now if we can see we have all the data in our table:
|
|
|
|
```{r}
|
|
con |>
|
|
tbl("gapminder") |>
|
|
count(year)
|
|
```
|
|
|
|
```{r, include = FALSE}
|
|
DBI::dbDisconnect(con, shutdown = TRUE)
|
|
```
|
|
|
|
### Writing csv files
|
|
|
|
The same basic principle applies if we want to write multiple csv files, one for each group.
|
|
Let's imagine that we want to take the `ggplot2::diamonds` data and save our one csv file for each `clarity`.
|
|
First we need to make those individual datasets.
|
|
There are many ways you could that, but there's one way we particularly like: `group_nest()`.
|
|
|
|
```{r}
|
|
by_clarity <- diamonds |>
|
|
group_nest(clarity)
|
|
|
|
by_clarity
|
|
```
|
|
|
|
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`:
|
|
|
|
```{r}
|
|
by_clarity$data[[1]]
|
|
```
|
|
|
|
While we're here, lets create a column that gives the name of output file, using `mutate()` and `str_glue()`:
|
|
|
|
```{r}
|
|
by_clarity <- by_clarity |>
|
|
mutate(path = str_glue("diamonds-{clarity}.csv"))
|
|
|
|
by_clarity
|
|
```
|
|
|
|
So if we were going to save these data frames by hand, we might write something like:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
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]])
|
|
...
|
|
write_csv(by_clarity$by_clarity[[8]], by_clarity$path[[8]])
|
|
```
|
|
|
|
This is a little different to our previous uses of `map()` because there are two arguments changing, not just one.
|
|
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)
|
|
```
|
|
|
|
```{r}
|
|
#| include: false
|
|
unlink(by_clarity$path)
|
|
```
|
|
|
|
### Saving plots
|
|
|
|
We can take the same basic approach to create many plots.
|
|
Let's first make a function that draws the plot we want:
|
|
|
|
```{r}
|
|
carat_histogram <- function(df) {
|
|
ggplot(df, aes(carat)) + geom_histogram(binwidth = 0.1)
|
|
}
|
|
|
|
carat_histogram(by_clarity$data[[1]])
|
|
```
|
|
|
|
Now we can use `map()` to create a list of many plots[^iteration-5]:
|
|
|
|
[^iteration-5]: You can print `by_clarity$plot` to get a crude animation --- you'll get one plot for each element of `plots`.
|
|
|
|
```{r}
|
|
by_clarity <- by_clarity |>
|
|
mutate(
|
|
plot = map(data, carat_histogram),
|
|
path = str_glue("clarity-{clarity}.png")
|
|
)
|
|
```
|
|
|
|
Then use `walk2()` with `ggsave()` to save each plot:
|
|
|
|
```{r}
|
|
walk2(
|
|
by_clarity$paths,
|
|
by_clarity$plots,
|
|
\(path, plot) ggsave(path, plot, width = 6, height = 6)
|
|
)
|
|
```
|
|
|
|
This is short hand for:
|
|
|
|
```{r}
|
|
#| eval: false
|
|
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)
|
|
...
|
|
ggsave(by_clarity$path[[8]], by_clarity$plot[[8]], width = 6, height = 6)
|
|
```
|
|
|
|
```{r}
|
|
#| include: false
|
|
unlink(by_clarity$paths)
|
|
```
|
|
|
|
### 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.
|
|
|
|
## Summary
|
|
|
|
In this chapter you learn iteration tools to solve three problems that come up frequently when doing data science: manipulating multiple columns, reading multiple files, and saving multiple outputs.
|
|
But in general, iteration is a super power: if you know the right iteration technique, you can easily go from fixing one problems to fixing any number of problems.
|
|
Once you've mastered the techniques in this chapter, we highly recommend learning more by reading [Functionals chapter](https://adv-r.hadley.nz/functionals.html) of *Advanced R* and consulting the [purrr website](https://purrr.tidyverse.org and the).
|
|
|
|
If you know much about iteration in other languages you might be surprised that we didn't discuss the `for` loop.
|
|
That comes up in the next chapter where we'll discuss some important base R functions.
|