---
title: "Functional Programming with purrr: 20 Examples"
---

```{r}
#| label: setup
#| include: false
knitr::opts_chunk$set(
  echo = TRUE,
  message = FALSE,
  warning = FALSE,
  fig.width = 6,
  fig.height = 3.6,
  fig.align = "center",
  dpi = 120,
  fig.path = "_figs/purrr-practice/"
)
library(tidyverse)
```

Apply the same operation to each piece: a vector, a list, the columns of a data frame, a group, or several inputs side by side.

Datasets: `iris`, `mtcars`, `airquality`, `ToothGrowth`, `ChickWeight`.

Run the worked example. Then write Your turn before you read the solution. Some exercises use different columns from the worked example. Examples 11–20 continue the same pattern, and each solution stays closed until you expand it.

```{r}
#| label: libraries
set.seed(612)
library(tidyverse)
```

```{r}
#| label: check-claims
#| include: false
mpg_by_cyl <- split(mtcars$mpg, mtcars$cyl)
stopifnot(is.list(map(mpg_by_cyl, mean)))
stopifnot(is.double(map_dbl(mpg_by_cyl, mean)))
stopifnot(all.equal(unlist(map(mpg_by_cyl, mean)), map_dbl(mpg_by_cyl, mean)))
shipping_cost <- pmap_dbl(
  list(c(3, 4, 5), c(2, 5, 8), c(1.5, 2, 2.5)),
  \(base_fee, weight, rate) base_fee + weight * rate
)
stopifnot(all.equal(shipping_cost, c(6, 14, 25)))
```

---

## 1. A list and `map()`

`mtcars`. Split a column, then apply one function to each piece.

### Worked example

```{r}
#| label: ex1-worked
mpg_by_cyl <- split(mtcars$mpg, mtcars$cyl)
str(mpg_by_cyl)
map(mpg_by_cyl, mean)
map_dbl(mpg_by_cyl, mean)
```

`map()` applies `mean` to the 4-, 6-, and 8-cylinder groups. Pass `mean` without parentheses.

### Your turn

Split `mtcars$hp` by `mtcars$gear`. Map `max`. Repeat with `map_dbl()`. What changes?

### Solution

```{r}
#| label: ex1-solution
hp_by_gear <- split(mtcars$hp, mtcars$gear)
map(hp_by_gear, max)
map_dbl(hp_by_gear, max)
```

`map()` returns a list. `map_dbl()` returns a double vector. Each group must produce one numeric value.

---

## 2. `map()` on data-frame columns

`iris`. A data frame is a list of columns, so `map()` walks the columns.

### Worked example

```{r}
#| label: ex2-worked
map(iris, class)
iris |>
  select(where(is.numeric)) |>
  map_dbl(sd)
```

`Species` is a factor. Select the numeric columns before `sd()`.

### Your turn

Median of every numeric `iris` column, as one named numeric vector. Class of each column, as a character vector. Why does `map_chr(iris, class)` work here?

### Solution

```{r}
#| label: ex2-solution
iris |>
  select(where(is.numeric)) |>
  map_dbl(median)
map_chr(iris, class)
```

`class()` produces one string per column here. `map_chr()` requires exactly one character value per element.

---

## 3. Missing values and a lambda

`airquality`. `\(x)` is short for `function(x)`, from R 4.1.

### Worked example

```{r}
#| label: ex3-worked
map_lgl(airquality, \(x) any(is.na(x)))
map_int(airquality, \(x) sum(is.na(x)))
```

The first call is logical. The second is an integer count.

### Your turn

Proportion missing in every column, with `map_dbl()`. Names of the columns that have any missing value. Mean of `Ozone`, ignoring missing values.

### Solution

```{r}
#| label: ex3-solution
missing_proportion <- map_dbl(airquality, \(x) mean(is.na(x)))
missing_proportion
missing_any <- map_lgl(airquality, \(x) any(is.na(x)))
names(missing_any)[missing_any]
mean(airquality$Ozone, na.rm = TRUE)
map_dbl(airquality["Ozone"], \(x) mean(x, na.rm = TRUE))
```

`mean(is.na(x))` is the fraction of `TRUE`, because `TRUE` is 1 and `FALSE` is 0.

---

## 4. `across()`

`iris`. `across()` inside `summarise()` keeps one row per species. `map()` on a data frame does not keep the grouping column.

### Worked example

```{r}
#| label: ex4-worked
iris |>
  group_by(Species) |>
  summarise(
    across(
      ends_with("Length"),
      list(mean = mean, sd = sd),
      .names = "{.col}_{.fn}"
    ),
    .groups = "drop"
  )
```

### Your turn

For each species, the median and the IQR of `Sepal.Width` and `Petal.Width`. Names such as `Sepal.Width_median` and `Sepal.Width_IQR`.

### Solution

```{r}
#| label: ex4-solution
iris |>
  group_by(Species) |>
  summarise(
    across(
      c(Sepal.Width, Petal.Width),
      list(median = median, IQR = IQR),
      .names = "{.col}_{.fn}"
    ),
    .groups = "drop"
  )
```

One row for each of the three species.

---

## 5. One function, many groups

`ToothGrowth`. A named function can return a one-row data frame. `map()` then returns a list of those data frames.

`map_dfr()` and `map_dfc()` still run and purrr marks them superseded; collect data frames with `map(...) |> list_rbind()` or `list_cbind()`.

### Worked example

```{r}
#| label: ex5-worked
mean_sd <- function(x) {
  tibble(mean = mean(x, na.rm = TRUE), sd = sd(x, na.rm = TRUE))
}
length_by_supp <- split(ToothGrowth$len, ToothGrowth$supp)
results <- map(length_by_supp, mean_sd)
results
bind_rows(results, .id = "supp")
```

`.id` puts the list names `OJ` and `VC` into `supp`.

### Your turn

Write `five_number()` so it returns a one-row tibble with the minimum, the median, and the maximum. Apply it to `ToothGrowth$len` split by `dose`. Combine the rows and keep a `dose` column.

### Solution

```{r}
#| label: ex5-solution
five_number <- function(x) {
  tibble(minimum = min(x), median = median(x), maximum = max(x))
}
ToothGrowth$len |>
  split(ToothGrowth$dose) |>
  map(five_number) |>
  bind_rows(.id = "dose")
```

`dose` is character because it was a list name. Use `as.numeric(dose)` when you need a number.

---

## 6. `map2()`

`mtcars`. Two vectors, paired by position.

### Worked example

```{r}
#| label: ex6-worked
mpg <- mtcars$mpg[1:5]
distance <- c(100, 150, 80, 120, 200)
price_per_gallon <- 3.50
cost <- map2_dbl(distance, mpg, \(d, m) (d / m) * price_per_gallon)
tibble(car = rownames(mtcars)[1:5], distance, mpg, cost)
```

### Your turn

The first five cars. Distances `c(50, 75, 100, 125, 150)`. Four dollars a gallon. `map2_dbl()` for the fuel cost. A tibble with the car name and the fuel cost.

### Solution

```{r}
#| label: ex6-solution
d <- c(50, 75, 100, 125, 150)
m <- mtcars$mpg[1:5]
fuel_cost <- map2_dbl(d, m, \(distance, mpg) distance / mpg * 4)
tibble(car = rownames(mtcars)[1:5], fuel_cost)
```

---

## 7. `pmap()`

`mtcars`. Three inputs, still paired by position.

### Worked example

```{r}
#| label: ex7-worked
trips <- tibble(
  car = rownames(mtcars)[1:4],
  distance = c(50, 100, 150, 200),
  mpg = mtcars$mpg[1:4],
  price = c(3.25, 3.50, 3.75, 4.00)
)
trips |>
  mutate(
    cost = pmap_dbl(
      list(distance, mpg, price),
      \(distance, mpg, price) distance / mpg * price
    )
  )
```

### Your turn

A shipping tibble: `weight = c(2, 5, 8)`, `rate = c(1.5, 2, 2.5)`, `base_fee = c(3, 4, 5)`. `pmap_dbl()` for `base_fee + weight * rate`.

### Solution

```{r}
#| label: ex7-solution
shipping <- tibble(
  weight = c(2, 5, 8),
  rate = c(1.5, 2, 2.5),
  base_fee = c(3, 4, 5)
)
shipping |>
  mutate(
    cost = pmap_dbl(
      list(base_fee, weight, rate),
      \(base_fee, weight, rate) base_fee + weight * rate
    )
  )
```

The costs are 6, 14, and 25.

---

## 8. `group_map()` and `group_modify()`

`ChickWeight`. `data` is the group's rows. `key` is the group id. `group_map()` returns a list. `group_modify()` binds the data frames and keeps the group column.

### Worked example

```{r}
#| label: ex8-worked
fit_slope <- function(data) {
  fit <- lm(weight ~ Time, data = data)
  tibble(slope = unname(coef(fit)["Time"]))
}
ChickWeight |>
  group_by(Diet) |>
  group_map(\(data, key) fit_slope(data))
ChickWeight |>
  group_by(Diet) |>
  group_modify(\(data, key) fit_slope(data)) |>
  ungroup()
```

### Your turn

`mtcars`. Fit `mpg ~ wt` inside each `cyl` group. One row per cylinder group, with the slope on `wt`. Which group has the most negative slope?

### Solution

```{r}
#| label: ex8-solution
model_slopes <- mtcars |>
  group_by(cyl) |>
  group_modify(\(data, key) {
    model <- lm(mpg ~ wt, data = data)
    tibble(wt_slope = unname(coef(model)["wt"]))
  }) |>
  ungroup()
model_slopes
model_slopes |>
  slice_min(wt_slope, n = 1)
```

A more negative slope means fitted MPG falls faster as weight rises inside that cylinder group. That is an association, not a cause.

---

## 9. `imap()`

`iris`. `imap()` passes the element and its name.

### Worked example

```{r}
#| label: ex9-worked
numeric_iris <- iris |>
  select(where(is.numeric))
column_reports <- imap_chr(
  numeric_iris,
  \(values, column_name) paste0(column_name, ": mean = ", round(mean(values), 2))
)
column_reports
```

### Your turn

`imap_chr()` on the numeric columns of `mtcars`. Strings like `mpg: min = 10.4`.

### Solution

```{r}
#| label: ex9-solution
mtcars |>
  select(where(is.numeric)) |>
  imap_chr(\(values, column_name) paste0(column_name, ": min = ", min(values)))
```

---

## 10. `walk()` for a side effect

`iris`. `walk()` is for a file or a plot. It returns the input invisibly. The files below are written under `tempdir()`, not in the project folder.

### Worked example

```{r}
#| label: ex10-worked
plot_dir <- file.path(tempdir(), "data612_iris_plots")
unlink(plot_dir, recursive = TRUE)
dir.create(plot_dir)
plot_vars <- c("Sepal.Length", "Sepal.Width", "Petal.Length")
walk(plot_vars, \(var) {
  p <- ggplot(iris, aes(x = .data[[var]])) +
    geom_histogram(bins = 15)
  ggsave(
    filename = file.path(plot_dir, paste0(var, ".png")),
    plot = p,
    width = 5,
    height = 3.5,
    units = "in"
  )
})
list.files(plot_dir)
```

### Your turn

Four histogram PNGs, one per numeric `iris` column, in a different temporary directory. Check that four PNG files are there.

### Solution

```{r}
#| label: ex10-solution
out_dir <- file.path(tempdir(), "data612_iris_numeric")
unlink(out_dir, recursive = TRUE)
dir.create(out_dir)
numeric_cols <- names(iris)[map_lgl(iris, is.numeric)]
walk(numeric_cols, \(var) {
  p <- ggplot(iris, aes(x = .data[[var]])) +
    geom_histogram(bins = 15)
  ggsave(
    filename = file.path(out_dir, paste0(var, ".png")),
    plot = p,
    width = 5,
    height = 3.5,
    units = "in"
  )
})
saved_files <- list.files(out_dir)
saved_files
length(saved_files)
```

---

## Quick reference

| Goal | Function | Output |
|---|---|---|
| Apply one function to each element | `map()` | List |
| Return one number per element | `map_dbl()` | Double vector |
| Return one integer per element | `map_int()` | Integer vector |
| Return one string per element | `map_chr()` | Character vector |
| Return one `TRUE`/`FALSE` per element | `map_lgl()` | Logical vector |
| Apply functions across selected columns | `across()` | Depends on `mutate()` / `summarise()` |
| Iterate over two inputs | `map2()` / `map2_dbl()` | List / double vector |
| Iterate over many inputs | `pmap()` / `pmap_dbl()` | List / double vector |
| Work with elements and their names | `imap()` / `imap_chr()` | List / character vector |
| Return a list of grouped results | `group_map()` | List |
| Combine data frames from groups | `group_modify()` | Data frame |
| Write files or generate plots | `walk()` | The input, invisibly |

---

## Concept check

Why is `map_dbl()` often preferable to `map()` when every iteration must produce a single number?

Why is `walk()` more appropriate than `map()` when saving images?

---

## Examples 11–20

These are **10 additional examples** that build on examples 1–10. Each example has (i) a question to discuss, (ii) a guided demonstration, (iii) an exercise, and (iv) a solution you can expand after trying the exercise. The examples use only datasets distributed with R: `mtcars`, `iris`, `airquality`, and `ToothGrowth`.

**Key idea:** The first argument of `split(x, f)` is **what you want to divide**. If `x` is a vector, you get a list of vectors; if `x` is a data frame, you get a list of data frames. The second argument `f` determines the groups.

## Example 11 — Split a vector by month, then calculate summaries

**Dataset:** `airquality` (daily air-quality measurements in New York).

**Goal:** Distinguish *grouping values* from *calculating within each group*.

### Worked example

```{r}
#| label: ex11-worked
# Split the temperature vector into groups defined by Month.
temp_by_month <- split(airquality$Temp, airquality$Month)

names(temp_by_month)  # Group labels
lengths(temp_by_month) # Days in each month
str(temp_by_month)    # A list of numeric vectors

map(temp_by_month, max)       # List output
map_dbl(temp_by_month, max)   # Named double vector
map_dbl(temp_by_month, mean)  # Average temperature by month
```

**Discuss:** `split()` has not computed any averages. It has only organized values into separate vectors. The calculation happens in `map()`.

### Your turn

1. Split **wind speed** by month.
2. Find the minimum wind speed for each month with `map_dbl()`.
3. Find the difference between the maximum and minimum wind speed in each month. Use a lambda function.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 11</summary>
```

```{r}
#| label: ex11-solution
wind_by_month <- split(airquality$Wind, airquality$Month)
map_dbl(wind_by_month, min)
map_dbl(wind_by_month, \(x) max(x) - min(x))
```

**Takeaway:** A lambda such as `\(x) max(x) - min(x)` is helpful when the operation is more complicated than a single existing function.

```{=html}
</details>
```

## Example 12 — Split a complete data frame and keep all its columns

**Dataset:** `iris`.

**Goal:** See why `split(iris, iris$Species)` is different from `split(iris$Sepal.Length, iris$Species)`.

### Worked example

```{r}
#| label: ex12-worked
iris_groups <- split(iris, iris$Species)

class(iris_groups)             # list
map_int(iris_groups, nrow)     # rows per species
map_int(iris_groups, ncol)     # columns per species
names(iris_groups)            # species labels

# Each element is a complete data frame, so we can use multiple columns.
map_dbl(iris_groups, \(d) cor(d$Sepal.Length, d$Petal.Length))
```

**Discuss:** Splitting the complete `iris` object preserves all five columns in each group. Splitting `iris$Sepal.Length` preserves only that numerical variable.

### Your turn

1. Split the **entire** `mtcars` data frame by `cyl`.
2. Find the number of cars per cylinder group.
3. Find the mean `mpg` within each group, using `map_dbl()`.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 12</summary>
```

```{r}
#| label: ex12-solution
cars_by_cyl <- split(mtcars, mtcars$cyl)
map_int(cars_by_cyl, nrow)
map_dbl(cars_by_cyl, \(d) mean(d$mpg))
```

**Takeaway:** When a list element is a data frame, the anonymous function receives a data frame (`d`) rather than a single number.

```{=html}
</details>
```

## Example 13 — Handle missing values inside mapping functions

**Dataset:** `airquality`.

**Goal:** Learn why `na.rm = TRUE` matters when summarizing columns.

### Worked example

```{r}
#| label: ex13-worked
# Airquality has missing values in some columns.
map_int(airquality, \(x) sum(is.na(x)))

# Without na.rm, the Ozone average is missing.
mean(airquality$Ozone)
mean(airquality$Ozone, na.rm = TRUE)

# Compute means for every column safely.
map_dbl(airquality, \(x) mean(x, na.rm = TRUE))
```

**Discuss:** `map_dbl()` expects **one number per column**, but that number can be `NA_real_` if the chosen function produces a missing result. It does not automatically remove missing observations.

### Your turn

1. Calculate the **median** of every column in `airquality`, ignoring missing observations.
2. Calculate the 90th percentile of each column, ignoring missing observations.
3. Why would `map_dbl(airquality, quantile)` fail with default arguments?

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 13</summary>
```

```{r}
#| label: ex13-solution
map_dbl(airquality, \(x) median(x, na.rm = TRUE))
map_dbl(airquality, \(x) unname(quantile(x, probs = 0.90, na.rm = TRUE)))
```

`quantile(x)` usually returns **five values** (0%, 25%, 50%, 75%, 100%), not one. `map_dbl()` requires a single double value for each column; the default `quantile()` call may also encounter missing values.

```{=html}
</details>
```

## Example 14 — Use `map_lgl()` to check properties of each column

**Dataset:** `iris`.

**Goal:** Write functions that return `TRUE` or `FALSE` for each column.

### Worked example

```{r}
#| label: ex14-worked
map_lgl(iris, is.numeric)               # Which columns are numeric?
map_lgl(iris, is.factor)                # Which columns are factors?
map_lgl(iris, \(x) any(is.na(x)))       # Any missing values?
map_lgl(iris, \(x) length(unique(x)) > 10) # More than 10 distinct values?
```

**Discuss:** `map_lgl()` does not keep a list of TRUE/FALSE values; it returns a named logical vector.

### Your turn

For `mtcars`, use `map_lgl()` to find which columns have (a) at least 10 distinct values and (b) any value greater than 200.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 14</summary>
```

```{r}
#| label: ex14-solution
map_lgl(mtcars, \(x) length(unique(x)) >= 10)
map_lgl(mtcars, \(x) any(x > 200))
```

**Takeaway:** A predicate function answers a yes/no question, making `map_lgl()` a natural choice.

```{=html}
</details>
```

## Example 15 — Use `imap()` when you need column names as well as values

**Dataset:** `iris`.

**Goal:** Understand how `imap()` differs from `map()`.

### Worked example

```{r}
#| label: ex15-worked
# imap() passes both the column itself (x) and its name (nm).
column_messages <- imap_chr(
  iris,
  \(x, nm) paste(nm, "contains", length(unique(x)), "distinct values")
)
column_messages
```

**Discuss:** `map()` gets each column; `imap()` gets the column **and** its name (or position if the input has no names).

### Your turn

Use `imap_chr()` on the numeric columns of `mtcars` to generate text such as `mpg: mean = 20.09` with the mean rounded to two decimal places.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 15</summary>
```

```{r}
#| label: ex15-solution
map_messages <- imap_chr(
  mtcars,
  \(x, nm) paste0(nm, ": mean = ", sprintf("%.2f", mean(x)))
)
map_messages
```

**Takeaway:** This is useful for automatic reports, validation messages, and readable summaries.

```{=html}
</details>
```

## Example 16 — Use `map_if()` to change only appropriate list elements

**Dataset:** `iris`.

**Goal:** Selectively modify elements while preserving others.

### Worked example

```{r}
#| label: ex16-worked
# Center only numeric columns; leave the Species factor unchanged.
centered <- map_if(
  iris,
  is.numeric,
  \(x) x - mean(x)
)

class(centered)         # list
map_chr(centered, \(x) class(x)[1])
map_dbl(centered[1:4], mean)  # Approximately zero

# Convert the list back to a data frame if needed.
centered_df <- as_tibble(centered)
```

**Discuss:** `map_if()` is a conditional mapping tool. For typical data-frame column transformations, `mutate(across(where(is.numeric), ...))` is also a good approach.

### Your turn

Create a data frame in which every numeric column of `iris` is divided by its standard deviation, but `Species` is left untouched. Verify that the result still contains 150 rows and five columns.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 16</summary>
```

```{r}
#| label: ex16-solution
scaled_columns <- map_if(iris, is.numeric, \(x) x / sd(x))
result <- as_tibble(scaled_columns)
dim(result)
class(result$Species)

# An equivalent dplyr approach:
result_dplyr <- iris %>%
  mutate(across(where(is.numeric), \(x) x / sd(x)))
```

**Takeaway:** `map_if()` selects elements according to a predicate and applies the function only to those elements.

```{=html}
</details>
```

## Example 17 — Use `map2()` for different rules for different groups

**Dataset:** `mtcars`.

**Goal:** Use one list of values together with a second vector of thresholds.

### Worked example

```{r}
#| label: ex17-worked
hp_by_gear <- split(mtcars$hp, mtcars$gear)

# A different horsepower cutoff for each gear group.
cutoffs <- c(`3` = 150, `4` = 100, `5` = 200)

# Match cutoffs to the order of the list's group names.
cutoffs <- cutoffs[names(hp_by_gear)]

map2_int(
  hp_by_gear,
  cutoffs,
  \(horsepower, limit) sum(horsepower > limit)
)
```

**Discuss:** `map()` supplies one varying input, while `map2()` supplies two corresponding inputs. The first horsepower vector uses the first cutoff, and so on.

### Your turn

For each gear group, compute the **fraction** of cars above its cutoff using `map2_dbl()`. Confirm the outputs are between 0 and 1.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 17</summary>
```

```{r}
#| label: ex17-solution
fractions <- map2_dbl(
  hp_by_gear,
  cutoffs,
  \(horsepower, limit) mean(horsepower > limit)
)
fractions
all(fractions >= 0 & fractions <= 1)
```

**Takeaway:** A logical expression is converted to a fraction by `mean()` because `TRUE` counts as 1 and `FALSE` as 0.

```{=html}
</details>
```

## Example 18 — Use `pmap()` when a function needs several inputs

**Dataset:** `mtcars`.

**Goal:** Feed multiple columns into a function one row at a time.

### Worked example

```{r}
#| label: ex18-worked
# Fit a model to the built-in mtcars dataset.
fit <- lm(mpg ~ wt + hp, data = mtcars)

# Use three observations as a demonstration.
new_cars <- mtcars[1:3, c("wt", "hp")]

# Each iteration receives wt and hp from one row.
predictions <- pmap_dbl(
  new_cars,
  \(wt, hp) {
    new_observation <- data.frame(wt = wt, hp = hp)
    as.numeric(predict(fit, newdata = new_observation))
  }
)
predictions

# Check against the usual vectorized prediction call.
predict(fit, newdata = new_cars)
```

**Discuss:** We normally prefer the vectorized `predict()` call for this specific task. `pmap()` is useful here to **illustrate** how to iterate across multiple inputs, especially when each row requires a more complicated custom operation.

### Your turn

Use `pmap_dbl()` to predict `mpg` for the first **five** cars in `mtcars`, using the same model. Check that your results match `predict(fit, ...)`.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 18</summary>
```

```{r}
#| label: ex18-solution
five_cars <- mtcars[1:5, c("wt", "hp")]

five_predictions <- pmap_dbl(
  five_cars,
  \(wt, hp) as.numeric(predict(
    fit,
    newdata = data.frame(wt = wt, hp = hp)
  ))
)

five_predictions
all.equal(unname(five_predictions), unname(predict(fit, newdata = five_cars)))
```

**Takeaway:** `pmap()` generalizes `map2()` to an arbitrary collection of input arguments.

```{=html}
</details>
```

## Example 19 — Fit a separate regression for each group

**Dataset:** `mtcars`.

**Goal:** Connect the earlier ideas of splitting and mapping to grouped statistical modeling.

### Worked example

```{r}
#| label: ex19-worked
# Method A: split + map()
cars_by_cyl <- split(mtcars, mtcars$cyl)
models <- map(cars_by_cyl, \(d) lm(mpg ~ wt, data = d))
map_dbl(models, \(model) unname(coef(model)["wt"]))

# Method B: group_modify() returns a combined data frame.
slopes <- mtcars %>%
  group_by(cyl) %>%
  group_modify(\(d, key) {
    fit_group <- lm(mpg ~ wt, data = d)
    tibble(slope = unname(coef(fit_group)["wt"]))
  })
slopes
```

**Discuss:** `group_modify()` passes the group's data as its first argument and its grouping key as its second; it combines the group-specific output data frames automatically.

### Your turn

For every cylinder group, fit `lm(mpg ~ hp)` and return a combined data frame containing the cylinder count and the slope for `hp`.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 19</summary>
```

```{r}
#| label: ex19-solution
mtcars %>%
  group_by(cyl) %>%
  group_modify(\(d, key) {
    group_fit <- lm(mpg ~ hp, data = d)
    tibble(hp_slope = unname(coef(group_fit)["hp"]))
  })
```

**Takeaway:** This is useful when the same statistical model must be fitted independently to multiple groups.

```{=html}
</details>
```

## Example 20 — Use `walk()` for actions such as writing files

**Dataset:** `iris`.

**Goal:** Distinguish calculating a value from producing a side effect.

### Worked example

```{r}
#| label: ex20-worked
# Create a temporary directory, rather than cluttering the project folder.
output_dir <- file.path(tempdir(), "data612_species")
dir.create(output_dir, showWarnings = FALSE)

species_data <- split(iris, iris$Species)

# walk2() pairs each group name with its corresponding data frame.
walk2(
  names(species_data),
  species_data,
  \(nm, d) write.csv(
    d,
    file = file.path(output_dir, paste0(nm, ".csv")),
    row.names = FALSE
  )
)

list.files(output_dir)
```

**Discuss:** `walk2()` is for **doing something** for each pair of inputs. The desired result is the written CSV files, not a list of computed values. `walk()` is the one-input version.

### Your turn

Split `mtcars` by `gear`. Create one CSV file for each gear count in a new temporary folder, with file names `gear_3.csv`, `gear_4.csv`, and `gear_5.csv`. Check that all three files exist.

```{=html}
<details class="lecture-solution">
<summary>Solution — Example 20</summary>
```

```{r}
#| label: ex20-solution
gear_dir <- file.path(tempdir(), "data612_gears")
dir.create(gear_dir, showWarnings = FALSE)

cars_by_gear <- split(mtcars, mtcars$gear)
walk2(
  names(cars_by_gear),
  cars_by_gear,
  \(gear_name, group_data) write.csv(
    group_data,
    file.path(gear_dir, paste0("gear_", gear_name, ".csv")),
    row.names = FALSE
  )
)

list.files(gear_dir)
length(list.files(gear_dir)) == 3
```

**Takeaway:** Choose `walk()` or `walk2()` when the primary purpose is saving files, printing reports, or other side effects.

```{=html}
</details>
```

## End-of-class concept check

Try to answer these without running R first:

1. What is the difference between `split(mtcars$hp, mtcars$gear)` and `split(mtcars, mtcars$gear)`?
2. Why does `map_dbl(x, quantile)` usually fail if `x` contains numeric vectors?
3. What two inputs does the function inside `imap()` receive?
4. How is `map2()` different from `pmap()`?
5. What is the difference between `map()` and `walk()`?
6. When should you use `group_modify()` rather than `group_map()`?

```{=html}
<details class="lecture-solution">
<summary>Instructor answer key</summary>
```

1. The first splits just horsepower into numeric vectors. The second splits every row and column of the data frame into data frames by gear.
2. With default probabilities, `quantile()` returns five numbers, but `map_dbl()` requires one double value from each element (and missing values can also cause an error).
3. The element and its name (or position, when unnamed).
4. `map2()` iterates over two varying inputs; `pmap()` can use many varying inputs.
5. `map()` collects outputs in a list; `walk()` is intended primarily for side effects and invisibly returns its input.
6. Use `group_modify()` when each group produces a data frame and you want those group results combined into one data frame.

```{=html}
</details>
```

## Functions practiced in examples 11–20

`split()`, `map()`, `map_dbl()`, `map_int()`, `map_chr()`, `map_lgl()`, `map_if()`, `imap_chr()`, `map2_int()`, `map2_dbl()`, `pmap_dbl()`, `group_modify()`, and `walk2()`.

**Installation (only if needed):** `install.packages("tidyverse")`.
