r4ds/iteration.qmd

1013 lines
32 KiB
Plaintext
Raw Normal View History

# Iteration {#sec-iteration}
```{r}
#| results: "asis"
#| echo: false
source("_common.R")
```
2016-03-01 22:29:58 +08:00
2016-07-24 22:08:24 +08:00
## Introduction
In @sec-functions, we talked about how important it is to reduce duplication in your code by creating functions instead of copying-and-pasting.
Reducing code duplication has three main benefits:
1. It's easier to see the intent of your code, because your eyes are drawn to what's different, not what stays the same.
2. It's easier to respond to changes in requirements.
As your needs change, you only need to make changes in one place, rather than remembering to change every place that you copied-and-pasted the code.
3. You're likely to have fewer bugs because each line of code is used in more places.
One tool for reducing duplication is functions, which reduce duplication by identifying repeated patterns of code and extract them out into independent pieces that can be easily reused and updated.
Another tool for reducing duplication is **iteration**, which helps you when you need to do the same thing to multiple inputs: repeating the same operation on different columns, or on different datasets.
In this chapter you'll learn about two important iteration paradigms: **imperative** and **functional**.
2022-08-30 22:00:14 +08:00
On the imperative side you have tools like `for` loops and `while` loops, which are a great place to start because they make iteration very explicit, so it's obvious what's happening.
However, `for` loops are quite verbose because they require bookkeeping code that is duplicated for every `for` loop.
Functional programming (FP) offers tools to extract out this duplicated code, so each common `for` loop pattern gets its own function.
Once you master the vocabulary of FP, you can solve many common iteration problems with less code, more ease, and fewer errors.
2016-03-24 22:09:09 +08:00
2016-07-19 21:01:50 +08:00
### Prerequisites
2022-08-30 22:00:14 +08:00
Once you've mastered the `for` loops provided by base R, you'll learn some of the powerful programming tools provided by purrr, one of the tidyverse core packages.
2016-07-19 21:01:50 +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
```
2016-03-01 22:29:58 +08:00
## For loops
2016-08-19 22:15:08 +08:00
Imagine we have this simple tibble:
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
We want to compute the median of each column.
You *could* do with copy-and-paste:
2016-03-22 21:57:52 +08:00
```{r}
median(df$a)
median(df$b)
median(df$c)
median(df$d)
```
But that breaks our rule of thumb: never copy and paste more than twice.
2022-08-30 22:00:14 +08:00
Instead, we could use a `for` loop:
2016-03-22 21:57:52 +08:00
2016-03-21 21:55:07 +08:00
```{r}
2016-03-22 21:57:52 +08:00
output <- vector("double", ncol(df)) # 1. output
for (i in seq_along(df)) { # 2. sequence
output[[i]] <- median(df[[i]]) # 3. body
2016-03-01 22:29:58 +08:00
}
2016-03-22 21:57:52 +08:00
output
2016-03-01 22:29:58 +08:00
```
2022-08-30 22:00:14 +08:00
Every `for` loop has three components:
2016-03-01 22:29:58 +08:00
1. The **output**: `output <- vector("double", length(x))`.
Before you start the loop, you must always allocate sufficient space for the output.
2022-08-30 22:00:14 +08:00
This is very important for efficiency: if you grow the `for` loop at each iteration using `c()` (for example), your `for` loop will be very slow.
A general way of creating an empty vector of given length is the `vector()` function.
It has two arguments: the type of the vector ("logical", "integer", "double", "character", etc.) and the length of the vector.
2. The **sequence**: `i in seq_along(df)`.
2022-08-30 22:00:14 +08:00
This determines what to loop over: each run of the `for` loop will assign `i` to a different value from `seq_along(df)`.
It's useful to think of `i` as a pronoun, like "it".
You might not have seen `seq_along()` before.
It's a safe version of the familiar `1:length(l)`, with an important difference: if you have a zero-length vector, `seq_along()` does the right thing:
2016-03-01 22:29:58 +08:00
2016-03-21 21:55:07 +08:00
```{r}
y <- vector("double", 0)
seq_along(y)
1:length(y)
```
You probably won't create a zero-length vector deliberately, but it's easy to create them accidentally.
If you use `1:length(x)` instead of `seq_along(x)`, you're likely to get a confusing error message.
3. The **body**: `output[[i]] <- median(df[[i]])`.
This is the code that does the work.
It's run repeatedly, each time with a different value for `i`.
The first iteration will run `output[[1]] <- median(df[[1]])`, the second will run `output[[2]] <- median(df[[2]])`, and so on.
2022-08-30 22:00:14 +08:00
That's all there is to the `for` loop!
Now is a good time to practice creating some basic (and not so basic) `for` loops using the exercises below.
Then we'll move on to some variations of the `for` loop that help you solve other problems that will crop up in practice.
2016-03-22 21:57:52 +08:00
### Exercises
2022-08-30 22:00:14 +08:00
1. Write `for` loops to:
2016-03-22 21:57:52 +08:00
a. Compute the mean of every column in `mtcars`.
b. Determine the type of each column in `nycflights13::flights`.
c. Compute the number of unique values in each column of `palmerpenguins::penguins`.
d. Generate 10 random normals from distributions with means of -10, 0, 10, and 100.
Think about the output, sequence, and body **before** you start writing the loop.
2022-08-30 22:00:14 +08:00
2. Eliminate the `for` loop in each of the following examples by taking advantage of an existing function that works with vectors:
```{r}
#| eval: false
2016-03-22 21:57:52 +08:00
out <- ""
for (x in letters) {
2016-07-19 21:01:50 +08:00
out <- stringr::str_c(out, x)
2016-03-22 21:57:52 +08:00
}
2016-03-22 21:57:52 +08:00
x <- sample(100)
sd <- 0
for (i in seq_along(x)) {
2016-03-22 21:57:52 +08:00
sd <- sd + (x[i] - mean(x)) ^ 2
}
2016-07-24 22:07:48 +08:00
sd <- sqrt(sd / (length(x) - 1))
2016-03-22 21:57:52 +08:00
x <- runif(100)
out <- vector("numeric", length(x))
out[1] <- x[1]
for (i in 2:length(x)) {
out[i] <- out[i - 1] + x[i]
}
```
2016-03-01 22:29:58 +08:00
2022-08-30 22:00:14 +08:00
3. Combine your function writing and `for` loop skills:
2022-08-30 22:00:14 +08:00
a. Write a `for` loop that `prints()` the lyrics to the children's song "Alice the camel".
b. Convert the nursery rhyme "ten in the bed" to a function. Generalise it to any number of people in any sleeping structure.
c. Convert the song "99 bottles of beer on the wall" to a function. Generalise to any number of any vessel containing any liquid on any surface.
2016-03-22 21:57:52 +08:00
2022-08-30 22:00:14 +08:00
4. It's common to see `for` loops that don't preallocate the output and instead increase the length of a vector at each step:
2016-08-19 22:15:08 +08:00
```{r}
#| eval: false
2016-03-22 21:57:52 +08:00
output <- vector("integer", 0)
for (i in seq_along(x)) {
output <- c(output, lengths(x[[i]]))
}
output
```
How does this affect performance?
Design and execute an experiment.
2016-03-22 21:57:52 +08:00
## For loop variations
2022-08-30 22:00:14 +08:00
Once you have the basic `for` loop under your belt, there are some variations that you should be aware of.
These variations are important regardless of how you do iteration, so don't forget about them once you've mastered the FP techniques you'll learn about in the next section.
2016-03-22 21:57:52 +08:00
2022-08-30 22:00:14 +08:00
There are four variations on the basic theme of the `for` loop:
2016-03-22 21:57:52 +08:00
1. Modifying an existing object, instead of creating a new object.
2. Looping over names or values, instead of indices.
3. Handling outputs of unknown length.
4. Handling sequences of unknown length.
2016-03-22 21:57:52 +08:00
### Modifying an existing object
2022-08-30 22:00:14 +08:00
Sometimes you want to use a `for` loop to modify an existing object.
2022-09-09 00:32:10 +08:00
For example, remember our challenge from @sec-functions on functions.
We wanted to rescale every column in a data frame:
2016-03-01 22:29:58 +08:00
```{r}
2016-10-04 03:10:05 +08:00
df <- tibble(
2016-03-21 21:55:07 +08:00
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
rescale01 <- function(x) {
rng <- range(x, na.rm = TRUE)
(x - rng[1]) / (rng[2] - rng[1])
}
2016-03-01 22:29:58 +08:00
df$a <- rescale01(df$a)
df$b <- rescale01(df$b)
df$c <- rescale01(df$c)
df$d <- rescale01(df$d)
```
2022-08-30 22:00:14 +08:00
To solve this with a `for` loop we again think about the three components:
2016-03-01 22:29:58 +08:00
1. **Output**: we already have the output --- it's the same as the input!
2016-03-01 22:29:58 +08:00
2. **Sequence**: we can think about a data frame as a list of columns, so we can iterate over each column with `seq_along(df)`.
2016-03-01 22:29:58 +08:00
3. **Body**: apply `rescale01()`.
2016-03-21 21:55:07 +08:00
This gives us:
```{r}
2016-03-01 22:29:58 +08:00
for (i in seq_along(df)) {
df[[i]] <- rescale01(df[[i]])
}
```
Typically you'll be modifying a list or data frame with this sort of loop, so remember to use `[[`, not `[`.
2022-08-30 22:00:14 +08:00
You might have spotted that we used `[[` in all my `for` loops: we think it's better to use `[[` even for atomic vectors because it makes it clear that you want to work with a single element.
2016-03-22 21:57:52 +08:00
### Looping patterns
There are three basic ways to loop over a vector.
2022-08-10 00:43:12 +08:00
So far we've shown you the most general: looping over the numeric indices with `for (i in seq_along(xs))`, and extracting the value with `x[[i]]`.
There are two other forms:
1. Loop over the elements: `for (x in xs)`.
This is most useful if you only care about side-effects, like plotting or saving a file, because it's difficult to save the output efficiently.
2016-03-22 21:57:52 +08:00
2. Loop over the names: `for (nm in names(xs))`.
2021-05-14 21:03:58 +08:00
This gives you a name, which you can use to access the value with `x[[nm]]`.
This is useful if you want to use the name in a plot title or a file name.
If you're creating named output, make sure to name the results vector like so:
2016-03-22 21:57:52 +08:00
```{r}
#| eval: false
2016-03-24 22:09:09 +08:00
results <- vector("list", length(x))
names(results) <- names(x)
```
2016-03-22 21:57:52 +08:00
2016-03-24 22:09:09 +08:00
Iteration over the numeric indices is the most general form, because given the position you can extract both the name and the value:
2016-03-22 21:57:52 +08:00
```{r}
#| eval: false
2016-03-22 21:57:52 +08:00
for (i in seq_along(x)) {
name <- names(x)[[i]]
value <- x[[i]]
}
```
2016-03-21 21:55:07 +08:00
### Unknown output length
2016-03-01 22:29:58 +08:00
Sometimes you might not know how long the output will be.
For example, imagine you want to simulate some random vectors of random lengths.
You might be tempted to solve this problem by progressively growing the vector:
2016-03-01 22:29:58 +08:00
2016-03-21 21:55:07 +08:00
```{r}
means <- c(0, 1, 2)
2016-03-22 21:57:52 +08:00
output <- double()
2016-03-21 21:55:07 +08:00
for (i in seq_along(means)) {
n <- sample(100, 1)
2016-03-22 21:57:52 +08:00
output <- c(output, rnorm(n, means[[i]]))
2016-03-21 21:55:07 +08:00
}
2016-03-22 21:57:52 +08:00
str(output)
2016-03-01 22:29:58 +08:00
```
But this is not very efficient because in each iteration, R has to copy all the data from the previous iterations.
In technical terms you get "quadratic" ($O(n^2)$) behavior which means that a loop with three times as many elements would take nine ($3^2$) times as long to run.
2016-03-21 21:55:07 +08:00
2016-03-24 22:09:09 +08:00
A better solution to save the results in a list, and then combine into a single vector after the loop is done:
2016-03-22 21:57:52 +08:00
2016-03-21 21:55:07 +08:00
```{r}
out <- vector("list", length(means))
for (i in seq_along(means)) {
n <- sample(100, 1)
out[[i]] <- rnorm(n, means[[i]])
}
str(out)
2016-03-22 21:57:52 +08:00
str(unlist(out))
2016-03-21 21:55:07 +08:00
```
2022-08-10 00:43:12 +08:00
Here we've used `unlist()` to flatten a list of vectors into a single vector.
2016-03-22 21:57:52 +08:00
This pattern occurs in other places too:
2016-03-21 21:55:07 +08:00
1. You might be generating a long string.
Instead of `paste()`ing together each iteration with the previous, save the output in a character vector and then combine that vector into a single string with `str_flatten()`.
2016-03-01 22:29:58 +08:00
2. You might be generating a big data frame.
Instead of sequentially `rbind()`ing in each iteration, save the output in a list, then use `dplyr::bind_rows(output)` to combine the output into a single data frame.
Watch out for this pattern.
Whenever you see it, switch to a more complex result object, and then combine in one step at the end.
2016-03-24 22:09:09 +08:00
2016-03-22 21:57:52 +08:00
### Unknown sequence length
2016-03-01 22:29:58 +08:00
Sometimes you don't even know how long the input sequence should run for.
This is common when doing simulations.
For example, you might want to loop until you get three heads in a row.
2022-08-30 22:00:14 +08:00
You can't do that sort of iteration with the `for` loop.
Instead, you can use a `while` loop.
A `while` loop is simpler than a `for` loop because it only has two components, a condition and a body:
2016-03-01 22:29:58 +08:00
```{r}
#| eval: false
2016-03-22 21:57:52 +08:00
while (condition) {
# body
}
```
2016-03-01 22:29:58 +08:00
2022-08-30 22:00:14 +08:00
A `while` loop is also more general than a `for` loop, because you can rewrite any `for` loop as a `while` loop, but you can't rewrite every `while` loop as a `for` loop:
2016-03-01 22:29:58 +08:00
```{r}
#| eval: false
2016-03-01 22:29:58 +08:00
for (i in seq_along(x)) {
2016-03-22 21:57:52 +08:00
# body
}
# Equivalent to
i <- 1
2016-08-19 22:15:08 +08:00
while (i <= length(x)) {
2016-03-22 21:57:52 +08:00
# body
i <- i + 1
2016-03-01 22:29:58 +08:00
}
```
2022-08-30 22:00:14 +08:00
Here's how we could use a `while` loop to find how many tries it takes to get three heads in a row:
2016-03-01 22:29:58 +08:00
2016-03-22 21:57:52 +08:00
```{r}
flip <- function() sample(c("T", "H"), 1)
2016-03-01 22:29:58 +08:00
2016-07-24 22:10:35 +08:00
flips <- 0
2016-03-22 21:57:52 +08:00
nheads <- 0
2016-03-01 22:29:58 +08:00
2016-03-22 21:57:52 +08:00
while (nheads < 3) {
if (flip() == "H") {
nheads <- nheads + 1
} else {
nheads <- 0
}
flips <- flips + 1
}
flips
```
2022-08-30 22:00:14 +08:00
I mention `while` loops only briefly, because we hardly ever use them.
They're most often used for simulation, which is outside the scope of this book.
However, it is good to know they exist so that you're prepared for problems where the number of iterations is not known in advance.
2016-03-22 21:57:52 +08:00
### Exercises
2016-10-05 03:21:04 +08:00
1. Imagine you have a directory full of CSV files that you want to read in.
You have their paths in a vector, `files <- dir("data/", pattern = "\\.csv$", full.names = TRUE)`, and now want to read each one with `read_csv()`.
2022-08-30 22:00:14 +08:00
Write the `for` loop that will load them into a single data frame.
2. What happens if you use `for (nm in names(x))` and `x` has no names?
What if only some of the elements are named?
What if the names are not unique?
3. Write a function that prints the mean of each numeric column in a data frame, along with its name.
2021-02-22 01:12:13 +08:00
For example, `show_mean(mpg)` would print:
```{r}
#| eval: false
2021-02-22 01:12:13 +08:00
show_mean(mpg)
#> displ: 3.47
2022-08-10 00:43:12 +08:00
#> year: 2004
2021-02-22 01:12:13 +08:00
#> cyl: 5.89
#> cty: 16.86
2016-03-01 22:29:58 +08:00
```
2022-08-10 00:43:12 +08:00
(Extra challenge: what function did we use to make sure that the numbers lined up nicely, even though the variable names had different lengths?)
4. What does this code do?
How does it work?
2016-03-01 22:29:58 +08:00
```{r}
#| eval: false
2016-03-24 22:09:09 +08:00
trans <- list(
2016-03-22 21:57:52 +08:00
disp = function(x) x * 0.0163871,
am = function(x) {
2016-07-23 00:22:53 +08:00
factor(x, labels = c("auto", "manual"))
2016-03-22 21:57:52 +08:00
}
)
for (var in names(trans)) {
mtcars[[var]] <- trans[[var]](mtcars[[var]])
}
```
2016-05-24 07:35:41 +08:00
## For loops vs. functionals
2022-08-30 22:00:14 +08:00
`For` loops are not as important in R as they are in other languages because R is a functional programming language.
This means that it's possible to wrap up `for` loops in a function, and call that function instead of using the `for` loop directly.
2016-03-24 22:09:09 +08:00
To see why this is important, consider (again) this simple data frame:
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-24 22:09:09 +08:00
```
2016-03-01 22:29:58 +08:00
Imagine you want to compute the mean of every column.
2022-08-30 22:00:14 +08:00
You could do that with a `for` loop:
2016-03-24 22:09:09 +08:00
```{r}
2016-08-19 22:15:08 +08:00
output <- vector("double", length(df))
2016-03-01 22:29:58 +08:00
for (i in seq_along(df)) {
2016-03-24 22:09:09 +08:00
output[[i]] <- mean(df[[i]])
2016-03-01 22:29:58 +08:00
}
2016-03-22 21:57:52 +08:00
output
2016-03-01 22:29:58 +08:00
```
You realise that you're going to want to compute the means of every column pretty frequently, so you extract it out into a function:
```{r}
col_mean <- function(df) {
2016-08-19 22:15:08 +08:00
output <- vector("double", length(df))
2016-03-01 22:29:58 +08:00
for (i in seq_along(df)) {
2016-03-22 21:57:52 +08:00
output[i] <- mean(df[[i]])
2016-03-01 22:29:58 +08:00
}
2016-03-22 21:57:52 +08:00
output
2016-03-01 22:29:58 +08:00
}
```
2016-03-24 22:09:09 +08:00
But then you think it'd also be helpful to be able to compute the median, and the standard deviation, so you copy and paste your `col_mean()` function and replace the `mean()` with `median()` and `sd()`:
2016-03-01 22:29:58 +08:00
```{r}
col_median <- function(df) {
2016-08-19 22:15:08 +08:00
output <- vector("double", length(df))
2016-03-01 22:29:58 +08:00
for (i in seq_along(df)) {
2016-03-22 21:57:52 +08:00
output[i] <- median(df[[i]])
2016-03-01 22:29:58 +08:00
}
2016-03-22 21:57:52 +08:00
output
2016-03-01 22:29:58 +08:00
}
col_sd <- function(df) {
2016-08-19 22:15:08 +08:00
output <- vector("double", length(df))
2016-03-01 22:29:58 +08:00
for (i in seq_along(df)) {
2016-03-22 21:57:52 +08:00
output[i] <- sd(df[[i]])
2016-03-01 22:29:58 +08:00
}
2016-03-22 21:57:52 +08:00
output
2016-03-01 22:29:58 +08:00
}
```
Uh oh!
You've copied-and-pasted this code twice, so it's time to think about how to generalize it.
2022-08-30 22:00:14 +08:00
Notice that most of this code is `for` loop boilerplate and it's hard to see the one thing (`mean()`, `median()`, `sd()`) that is different between the functions.
2016-03-01 22:29:58 +08:00
What would you do if you saw a set of functions like this:
```{r}
f1 <- function(x) abs(x - mean(x)) ^ 1
f2 <- function(x) abs(x - mean(x)) ^ 2
f3 <- function(x) abs(x - mean(x)) ^ 3
```
Hopefully, you'd notice that there's a lot of duplication, and extract it out into an additional argument:
```{r}
f <- function(x, i) abs(x - mean(x)) ^ i
```
You've reduced the chance of bugs (because you now have 1/3 of the original code), and made it easy to generalize to new situations.
2016-03-24 22:09:09 +08:00
2016-08-19 22:15:08 +08:00
We can do exactly the same thing with `col_mean()`, `col_median()` and `col_sd()` by adding an argument that supplies the function to apply to each column:
2016-03-01 22:29:58 +08:00
```{r}
col_summary <- function(df, fun) {
2016-08-19 22:15:08 +08:00
out <- vector("double", length(df))
2016-03-01 22:29:58 +08:00
for (i in seq_along(df)) {
out[i] <- fun(df[[i]])
}
out
}
col_summary(df, median)
2016-03-24 22:09:09 +08:00
col_summary(df, mean)
2016-03-01 22:29:58 +08:00
```
The idea of passing a function to another function is an extremely powerful idea, and it's one of the behaviors that makes R a functional programming language.
It might take you a while to wrap your head around the idea, but it's worth the investment.
2022-08-30 22:00:14 +08:00
In the rest of the chapter, you'll learn about and use the **purrr** package, which provides functions that eliminate the need for many common `for` loops.
The apply family of functions in base R (`apply()`, `lapply()`, `tapply()`, etc) solve a similar problem, but purrr is more consistent and thus is easier to learn.
2016-03-01 22:29:58 +08:00
2022-08-30 22:00:14 +08:00
The goal of using purrr functions instead of `for` loops is to allow you to break common list manipulation challenges into independent pieces:
2016-08-15 21:18:51 +08:00
1. How can you solve the problem for a single element of the list?
Once you've solved that problem, purrr takes care of generalising your solution to every element in the list.
2016-08-15 21:18:51 +08:00
2. If you're solving a complex problem, how can you break it down into bite-sized pieces that allow you to advance one small step towards a solution?
With purrr, you get lots of small pieces that you can compose together with the pipe.
2016-08-15 21:18:51 +08:00
This structure makes it easier to solve new problems.
It also makes it easier to understand your solutions to old problems when you re-read your old code.
2016-08-15 21:18:51 +08:00
2016-03-01 22:29:58 +08:00
### Exercises
1. Read the documentation for `apply()`.
2022-08-30 22:00:14 +08:00
In the 2d case, what two `for` loops does it generalise?
2016-03-01 22:29:58 +08:00
2022-01-05 10:07:35 +08:00
2. Adapt `col_summary()` so that it only applies to numeric columns You might want to start with an `is_numeric()` function that returns a logical vector that has a `TRUE` corresponding to each numeric column.
2016-03-01 22:29:58 +08:00
## The map functions
The pattern of looping over a vector, doing something to each element and saving the results is so common that the purrr package provides a family of functions to do it for you.
There is one function for each type of output:
2016-03-01 22:29:58 +08:00
- `map()` makes a list.
- `map_lgl()` makes a logical vector.
- `map_int()` makes an integer vector.
- `map_dbl()` makes a double vector.
- `map_chr()` makes a character vector.
2016-03-24 22:09:09 +08:00
Each function takes a vector as input, applies a function to each piece, and then returns a new vector that's the same length (and has the same names) as the input.
The type of the vector is determined by the suffix to the map function.
2016-03-01 22:29:58 +08:00
Once you master these functions, you'll find it takes much less time to solve iteration problems.
2022-08-30 22:00:14 +08:00
But you should never feel bad about using a `for` loop instead of a map function.
The map functions are a step up a tower of abstraction, and it can take a long time to get your head around how they work.
The important thing is that you solve the problem that you're working on, not write the most concise and elegant code (although that's definitely something you want to strive towards!).
2016-03-01 22:29:58 +08:00
2022-08-30 22:00:14 +08:00
Some people will tell you to avoid `for` loops because they are slow.
They're wrong!
2022-08-30 22:00:14 +08:00
(Well at least they're rather out of date, as `for` loops haven't been slow for many years.) The chief benefits of using functions like `map()` is not speed, but clarity: they make your code easier to write and to read.
2016-08-15 21:18:51 +08:00
2022-08-30 22:00:14 +08:00
We can use these functions to perform the same computations as the last `for` loop.
Those summary functions returned doubles, so we need to use `map_dbl()`:
2016-03-01 22:29:58 +08:00
```{r}
map_dbl(df, mean)
map_dbl(df, median)
2016-03-21 21:55:07 +08:00
map_dbl(df, sd)
2016-03-01 22:29:58 +08:00
```
2022-08-30 22:00:14 +08:00
Compared to using a `for` loop, focus is on the operation being performed (i.e. `mean()`, `median()`, `sd()`), not the bookkeeping required to loop over every element and store the output.
This is even more apparent if we use the pipe:
2016-03-01 22:29:58 +08:00
2016-03-24 22:09:09 +08:00
```{r}
2022-02-24 03:15:52 +08:00
df |> map_dbl(mean)
df |> map_dbl(median)
df |> map_dbl(sd)
2016-03-24 22:09:09 +08:00
```
There are a few differences between `map_*()` and `col_summary()`:
2016-03-01 22:29:58 +08:00
- All purrr functions are implemented in C.
This makes them a little faster at the expense of readability.
- The second argument, `.f`, the function to apply, can be a formula, a character vector, or an integer vector.
You'll learn about those handy shortcuts in the next section.
2022-02-24 03:15:52 +08:00
- `map_*()` uses ... (\[dot dot dot\]) to pass along additional arguments to `.f` each time it's called:
2016-03-01 22:29:58 +08:00
```{r}
map_dbl(df, mean, trim = 0.5)
```
- The map functions also preserve names:
2016-03-01 22:29:58 +08:00
```{r}
z <- list(x = 1:3, y = 4:5)
map_int(z, length)
```
### Shortcuts
There are a few shortcuts that you can use with `.f` in order to save a little typing.
Imagine you want to fit a linear model to each group in a dataset.
The following toy example splits up the `mtcars` dataset into three pieces (one for each value of cylinder) and fits the same linear model to each piece:
2016-03-01 22:29:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
models <- mtcars |>
split(mtcars$cyl) |>
2022-09-09 00:32:10 +08:00
map(\(df) lm(mpg ~ wt, data = df))
2016-03-01 22:29:58 +08:00
```
2022-08-30 22:00:14 +08:00
Here we've used `.x` as a pronoun: it refers to the current list element (in the same way that `i` referred to the current index in the `for` loop).
`.x` in a one-sided formula corresponds to an argument in an anonymous function.
2016-03-01 22:29:58 +08:00
When you're looking at many models, you might want to extract a summary statistic like the $R^2$.
To do that we need to first run `summary()` and then extract the component called `r.squared`.
We could do that using the shorthand for anonymous functions:
2016-03-01 22:29:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
models |>
map(summary) |>
2022-09-09 00:32:10 +08:00
map_dbl(\(x) x$r.squared)
2016-03-01 22:29:58 +08:00
```
But extracting named components is a common operation, so purrr provides an even shorter shortcut: you can use a string.
```{r}
2022-02-24 03:15:52 +08:00
models |>
map(summary) |>
2016-03-01 22:29:58 +08:00
map_dbl("r.squared")
```
### Base R
2016-03-01 22:29:58 +08:00
If you're familiar with the apply family of functions in base R, you might have noticed some similarities with the purrr functions:
- `lapply()` is basically identical to `map()`, except that `map()` is consistent with all the other functions in purrr, and you can use the shortcuts for `.f`.
- Base `sapply()` is a wrapper around `lapply()` that automatically simplifies the output.
This is useful for interactive work but is problematic in a function because you never know what sort of output you'll get:
2016-03-01 22:29:58 +08:00
```{r}
x1 <- list(
c(0.27, 0.37, 0.57, 0.91, 0.20),
c(0.90, 0.94, 0.66, 0.63, 0.06),
c(0.21, 0.18, 0.69, 0.38, 0.77)
)
x2 <- list(
c(0.50, 0.72, 0.99, 0.38, 0.78),
c(0.93, 0.21, 0.65, 0.13, 0.27),
c(0.39, 0.01, 0.38, 0.87, 0.34)
)
2016-03-01 22:29:58 +08:00
threshold <- function(x, cutoff = 0.8) x[x > cutoff]
2022-02-24 03:15:52 +08:00
x1 |> sapply(threshold) |> str()
x2 |> sapply(threshold) |> str()
2016-03-01 22:29:58 +08:00
```
- `vapply()` is a safe alternative to `sapply()` because you supply an additional argument that defines the type.
The only problem with `vapply()` is that it's a lot of typing: `vapply(df, is.numeric, logical(1))` is equivalent to `map_lgl(df, is.numeric)`.
One advantage of `vapply()` over purrr's map functions is that it can also produce matrices --- the map functions only ever produce vectors.
2016-03-01 22:29:58 +08:00
2022-08-10 00:43:12 +08:00
We focus on purrr functions here because they have more consistent names and arguments, helpful shortcuts, and in the future will provide easy parallelism and progress bars.
2016-03-01 22:29:58 +08:00
### Exercises
2016-08-19 22:15:08 +08:00
1. Write code that uses one of the map functions to:
a. Compute the mean of every column in `mtcars`.
b. Determine the type of each column in `nycflights13::flights`.
c. Compute the number of unique values in each column of `palmerpenguins::penguins`.
d. Generate 10 random normals from distributions with means of -10, 0, 10, and 100.
2. How can you create a single vector that for each column in a data frame indicates whether or not it's a factor?
2016-08-19 22:15:08 +08:00
3. What happens when you use the map functions on vectors that aren't lists?
What does `map(1:5, runif)` do?
Why?
2016-03-01 22:29:58 +08:00
4. What does `map(-2:2, rnorm, n = 5)` do?
Why?
What does `map_dbl(-2:2, rnorm, n = 5)` do?
Why?
2016-03-01 22:29:58 +08:00
5. Rewrite `map(x, function(df) lm(mpg ~ wt, data = df))` to eliminate the anonymous function.
2016-03-01 22:29:58 +08:00
## Dealing with failure
When you use the map functions to repeat many operations, the chances are much higher that one of those operations will fail.
When this happens, you'll get an error message, and no output.
This is annoying: why does one failure prevent you from accessing all the other successes?
How do you ensure that one bad apple doesn't ruin the whole barrel?
2016-03-01 22:29:58 +08:00
In this section you'll learn how to deal with this situation with a new function: `safely()`.
`safely()` is an adverb: it takes a function (a verb) and returns a modified version.
In this case, the modified function will never throw an error.
Instead, it always returns a list with two elements:
2016-03-01 22:29:58 +08:00
1. `result` is the original result.
If there was an error, this will be `NULL`.
2016-03-01 22:29:58 +08:00
2. `error` is an error object.
If the operation was successful, this will be `NULL`.
2016-03-01 22:29:58 +08:00
(You might be familiar with the `try()` function in base R.
It's similar, but because it sometimes returns the original result and it sometimes returns an error object it's more difficult to work with.)
2016-03-01 22:29:58 +08:00
Let's illustrate this with a simple example: `log()`:
```{r}
safe_log <- safely(log)
str(safe_log(10))
str(safe_log("a"))
```
When the function succeeds, the `result` element contains the result and the `error` element is `NULL`.
When the function fails, the `result` element is `NULL` and the `error` element contains an error object.
2016-03-01 22:29:58 +08:00
`safely()` is designed to work with `map()`:
2016-03-01 22:29:58 +08:00
```{r}
x <- list(1, 10, "a")
2022-02-24 03:15:52 +08:00
y <- x |> map(safely(log))
2016-03-01 22:29:58 +08:00
str(y)
```
This would be easier to work with if we had two lists: one of all the errors and one of all the output.
That's easy to get with `purrr::transpose()`:
2016-03-01 22:29:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
y <- y |> transpose()
2016-03-01 22:29:58 +08:00
str(y)
```
2016-03-25 20:59:05 +08:00
It's up to you how to deal with the errors, but typically you'll either look at the values of `x` where `y` is an error, or work with the values of `y` that are ok:
2016-03-01 22:29:58 +08:00
```{r}
2022-02-24 03:15:52 +08:00
is_ok <- y$error |> map_lgl(is_null)
2016-03-01 22:29:58 +08:00
x[!is_ok]
2022-02-24 03:15:52 +08:00
y$result[is_ok] |> flatten_dbl()
2016-03-01 22:29:58 +08:00
```
Purrr provides two other useful adverbs:
- Like `safely()`, `possibly()` always succeeds.
It's simpler than `safely()`, because you give it a default value to return when there is an error.
2016-03-01 22:29:58 +08:00
```{r}
x <- list(1, 10, "a")
2022-02-24 03:15:52 +08:00
x |> map_dbl(possibly(log, NA_real_))
2016-03-01 22:29:58 +08:00
```
- `quietly()` performs a similar role to `safely()`, but instead of capturing errors, it captures printed output, messages, and warnings:
2016-03-01 22:29:58 +08:00
```{r}
x <- list(1, -1)
2022-02-24 03:15:52 +08:00
x |> map(quietly(log)) |> str()
2016-03-01 22:29:58 +08:00
```
2016-03-25 20:59:05 +08:00
## Mapping over multiple arguments
2016-03-01 22:29:58 +08:00
So far we've mapped along a single input.
2021-04-14 23:50:55 +08:00
But often you have multiple related inputs that you need to iterate along in parallel.
That's the job of the `map2()` and `pmap()` functions.
For example, imagine you want to simulate some random normals with different means.
You know how to do that with `map()`:
2016-03-01 22:29:58 +08:00
```{r}
mu <- list(5, 10, -3)
2022-02-24 03:15:52 +08:00
mu |>
map(rnorm, n = 5) |>
2016-08-15 21:18:51 +08:00
str()
2016-03-01 22:29:58 +08:00
```
What if you also want to vary the standard deviation?
One way to do that would be to iterate over the indices and index into vectors of means and sds:
2016-03-25 20:59:05 +08:00
2016-03-01 22:29:58 +08:00
```{r}
sigma <- list(1, 5, 10)
2022-02-24 03:15:52 +08:00
seq_along(mu) |>
2022-09-09 00:32:10 +08:00
map(\(i) rnorm(5, mu[[i]], sigma[[i]])) |>
2016-08-15 21:18:51 +08:00
str()
2016-03-25 20:59:05 +08:00
```
But that obfuscates the intent of the code.
Instead we could use `map2()` which iterates over two vectors in parallel:
2016-03-25 20:59:05 +08:00
```{r}
2022-02-24 03:15:52 +08:00
map2(mu, sigma, rnorm, n = 5) |> str()
2016-03-01 22:29:58 +08:00
```
`map2()` generates this series of function calls:
```{r}
#| echo: false
2016-03-01 22:29:58 +08:00
knitr::include_graphics("diagrams/lists-map2.png")
```
Note that the arguments that vary for each call come *before* the function; arguments that are the same for every call come *after*.
2016-03-01 22:29:58 +08:00
2022-08-30 22:00:14 +08:00
Like `map()`, `map2()` is just a wrapper around a `for` loop:
2016-03-01 22:29:58 +08:00
```{r}
map2 <- function(x, y, f, ...) {
out <- vector("list", length(x))
for (i in seq_along(x)) {
out[[i]] <- f(x[[i]], y[[i]], ...)
}
out
}
```
You could also imagine `map3()`, `map4()`, `map5()`, `map6()` etc, but that would get tedious quickly.
Instead, purrr provides `pmap()` which takes a list of arguments.
You might use that if you wanted to vary the mean, standard deviation, and number of samples:
2016-03-01 22:29:58 +08:00
```{r}
n <- list(1, 3, 5)
args1 <- list(n, mu, sigma)
2022-02-24 03:15:52 +08:00
args1 |>
pmap(rnorm) |>
2016-08-15 21:18:51 +08:00
str()
2016-03-01 22:29:58 +08:00
```
That looks like:
```{r}
#| echo: false
2016-03-01 22:29:58 +08:00
knitr::include_graphics("diagrams/lists-pmap-unnamed.png")
```
If you don't name the list's elements, `pmap()` will use positional matching when calling the function.
That's a little fragile, and makes the code harder to read, so it's better to name the arguments:
2016-03-01 22:29:58 +08:00
```{r}
#| eval: false
2016-03-01 22:29:58 +08:00
args2 <- list(mean = mu, sd = sigma, n = n)
2022-02-24 03:15:52 +08:00
args2 |>
pmap(rnorm) |>
2016-08-15 21:18:51 +08:00
str()
2016-03-01 22:29:58 +08:00
```
That generates longer, but safer, calls:
```{r}
#| echo: false
2016-03-01 22:29:58 +08:00
knitr::include_graphics("diagrams/lists-pmap-named.png")
```
Since the arguments are all the same length, it makes sense to store them in a data frame:
```{r}
2016-10-04 03:10:05 +08:00
params <- tribble(
2016-08-19 22:15:08 +08:00
~mean, ~sd, ~n,
5, 1, 1,
10, 5, 3,
-3, 10, 5
2016-08-15 21:18:51 +08:00
)
2022-02-24 03:15:52 +08:00
params |>
2016-08-15 21:18:51 +08:00
pmap(rnorm)
2016-03-01 22:29:58 +08:00
```
2022-08-10 00:43:12 +08:00
As soon as your code gets complicated, we think a data frame is a good approach because it ensures that each column has a name and is the same length as all the other columns.
2016-03-01 22:29:58 +08:00
## Walk {#sec-walk}
2016-03-01 22:29:58 +08:00
Walk is an alternative to map that you use when you want to call a function for its side effects, rather than for its return value.
You typically do this because you want to render output to the screen or save files to disk --- the important thing is the action, not the return value.
Here's a very simple example:
2016-03-01 22:29:58 +08:00
```{r}
x <- list(1, "a", 3)
2022-02-24 03:15:52 +08:00
x |>
2016-03-01 22:29:58 +08:00
walk(print)
```
`walk()` is generally not that useful compared to `walk2()` or `pwalk()`.
2022-08-30 21:55:08 +08:00
For example, if you had a list of plots and a vector of file names, you could use `walk2()` to save each file to the corresponding location on disk:
2016-03-01 22:29:58 +08:00
```{r}
#| eval: false
2022-08-30 21:55:08 +08:00
library(tidyverse)
2022-02-24 03:15:52 +08:00
plots <- mtcars |>
2022-08-30 21:55:08 +08:00
split(mtcars$cyl) |>
2022-09-09 00:32:10 +08:00
map(\(df) ggplot(df, aes(mpg, wt)) + geom_point())
2022-08-30 21:55:08 +08:00
paths <- str_c(names(plots), ".pdf")
2016-03-01 22:29:58 +08:00
2022-08-30 21:55:08 +08:00
walk2(paths, plots, ggsave, path = tempdir())
2016-03-01 22:29:58 +08:00
```
`walk()`, `walk2()` and `pwalk()` all invisibly return `.`, the first argument.
This makes them suitable for use in the middle of pipelines.
2016-03-25 20:59:05 +08:00
## Other patterns of for loops
2022-09-09 00:32:10 +08:00
purrr provides a number of other functions that abstract over other types of `for` loops.
You'll use them less frequently than the map functions, but they're useful to know about.
The goal here is to briefly illustrate each function, so hopefully it will come to mind if you see a similar problem in the future.
Then you can go look up the documentation for more details.
2016-03-25 20:59:05 +08:00
### Predicate functions
A number of functions work with **predicate** functions that return either a single `TRUE` or `FALSE`.
2016-03-25 20:59:05 +08:00
`keep()` and `discard()` keep elements of the input where the predicate is `TRUE` or `FALSE` respectively:
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
keep(is.factor) |>
2016-08-19 22:15:08 +08:00
str()
2022-02-24 03:15:52 +08:00
gss_cat |>
discard(is.factor) |>
2016-08-19 22:15:08 +08:00
str()
```
`some()` and `every()` determine if the predicate is true for any or for all of the elements.
2016-03-25 20:59:05 +08:00
```{r}
x <- list(1:5, letters, list(10))
2016-08-19 22:15:08 +08:00
2022-02-24 03:15:52 +08:00
x |>
2016-08-19 22:15:08 +08:00
some(is_character)
2022-02-24 03:15:52 +08:00
x |>
2016-08-19 22:15:08 +08:00
every(is_vector)
2016-03-25 20:59:05 +08:00
```
`detect()` finds the first element where the predicate is true; `detect_index()` returns its position.
```{r}
x <- sample(10)
x
2022-02-24 03:15:52 +08:00
x |>
2022-09-09 00:32:10 +08:00
detect(\(x) x > 5)
2016-08-19 22:15:08 +08:00
2022-02-24 03:15:52 +08:00
x |>
2022-09-09 00:32:10 +08:00
detect_index(\(x) x > 5)
2016-03-25 20:59:05 +08:00
```
2016-03-25 20:59:05 +08:00
`head_while()` and `tail_while()` take elements from the start or end of a vector while a predicate is true:
```{r}
2022-02-24 03:15:52 +08:00
x |>
2022-09-09 00:32:10 +08:00
head_while(\(x) x > 5)
2016-08-19 22:15:08 +08:00
2022-02-24 03:15:52 +08:00
x |>
2022-09-09 00:32:10 +08:00
tail_while(\(x) x > 5)
2016-03-25 20:59:05 +08:00
```
### Reduce and accumulate
Sometimes you have a complex list that you want to reduce to a simple list by repeatedly applying a function that reduces a pair to a singleton.
This is useful if you want to apply a two-table dplyr verb to multiple tables.
For example, you might have a list of data frames, and you want to reduce to a single data frame by joining the elements together:
2016-03-25 20:59:05 +08:00
```{r}
dfs <- list(
2016-10-04 03:10:05 +08:00
age = tibble(name = "John", age = 30),
sex = tibble(name = c("John", "Mary"), sex = c("M", "F")),
trt = tibble(name = "Mary", treatment = "A")
2016-03-25 20:59:05 +08:00
)
2022-02-24 03:15:52 +08:00
dfs |> reduce(full_join)
```
2016-08-19 22:15:08 +08:00
Or maybe you have a list of vectors, and want to find the intersection:
```{r}
vs <- list(
c(1, 3, 5, 6, 10),
c(1, 2, 3, 7, 8, 10),
c(1, 2, 3, 4, 8, 9, 10)
)
2022-02-24 03:15:52 +08:00
vs |> reduce(intersect)
2016-08-19 22:15:08 +08:00
```
2020-10-05 05:08:10 +08:00
`reduce()` takes a "binary" function (i.e. a function with two primary inputs), and applies it repeatedly to a list until there is only a single element left.
`accumulate()` is similar but it keeps all the interim results.
You could use it to implement a cumulative sum:
2016-03-25 20:59:05 +08:00
```{r}
x <- sample(10)
x
2022-02-24 03:15:52 +08:00
x |> accumulate(`+`)
2016-03-25 20:59:05 +08:00
```
### Exercises
2022-08-30 22:00:14 +08:00
1. Implement your own version of `every()` using a `for` loop.
Compare it with `purrr::every()`.
What does purrr's version do that your version doesn't?
2016-03-25 20:59:05 +08:00
2. Create an enhanced `col_summary()` that applies a summary function to every numeric column in a data frame.
2016-03-25 20:59:05 +08:00
3. A possible base R equivalent of `col_summary()` is:
```{r}
col_sum3 <- function(df, f) {
is_num <- sapply(df, is.numeric)
df_num <- df[, is_num]
sapply(df_num, f)
}
```
But it has a number of bugs as illustrated with the following inputs:
```{r}
#| eval: false
2016-10-04 03:10:05 +08:00
df <- tibble(
2016-08-18 22:38:33 +08:00
x = 1:3,
y = 3:1,
z = c("a", "b", "c")
)
# OK
col_sum3(df, mean)
# Has problems: don't always return numeric vector
col_sum3(df[1:2], mean)
col_sum3(df[1], mean)
col_sum3(df[0], mean)
```
What causes the bugs?
2021-02-22 21:00:06 +08:00
## Case study
<!--# Case study on web scraping from multiple pages -->