library(tidyverse)
library(nycflights13)
library(palmerpenguins)Iteration in the Tidyverse
Loops, functions, across() and map()
Why iterate?
Iteration means doing the same thing many times: to every column, every file, every group or every value. A useful rule of thumb in programming is:
If you’ve copied and pasted the same code three times, write a loop or a function instead.
Repeated code is tedious to write, but the real problem is that it’s easy to get wrong. If you change one copy and forget another, your results silently disagree. Writing the code once means there’s only one place to fix it.
In base R, the classic tool for iteration is the for loop. The tidyverse offers tools that often do the same job in one line: vectorized functions, across() and map(). This page shows when to use each.
A loop from the regex lesson
In the regex lesson we turned the year, month and day columns of the flights data into text, so we could glue them into dates. Instead of writing as.character() three times, we wrote a loop:
df <- flights |> distinct(year, month, day)
for (cn in names(df)) {
print(cn)
df <- mutate(df, {{cn}} := as.character(get(cn)))
}[1] "year"
[1] "month"
[1] "day"
glimpse(df)Rows: 365
Columns: 3
$ year <chr> "2013", "2013", "2013", "2013", "2013", "2013", "2013", "2013", …
$ month <chr> "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",…
$ day <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "…
What each piece does
names(df)is a character vector of the column names:"year","month","day".for (cn in names(df))runs the body once for each name. The first time through,cnis"year"; the second time,"month"; then"day". Note thatcnholds the column’s name (a string), not the column itself.get(cn)turns the string"year"into the columnyear, soas.character(get(cn))converts that column to text.{{cn}} :=is the unusual part. Normally you writemutate(df, year = ...), with the new column’s name typed directly. Here the name is stored in a variable, and R won’t let you put a variable on the left of=. The:=operator allows it, and{{cn}}tells dplyr to use the variable’s value ("year") as the column name, not the wordcn.df <- ...saves the result each time, so the next pass through the loop starts from the updated data.print(cn)shows progress, which is handy for checking a loop while you write it.
A clearer way to write the same loop
The same loop is easier to read with two modern dplyr tools:
.data[[cn]]looks up a column whose name is stored in a string. It’s safer thanget(), which searches everywhere, not just in the data frame."{cn}" :=names the new column with the value ofcn. The quotes and braces fill in the variable, as instr_glue().
df <- flights |> distinct(year, month, day)
for (cn in names(df)) {
df <- mutate(df, "{cn}" := as.character(.data[[cn]]))
}
glimpse(df)Rows: 365
Columns: 3
$ year <chr> "2013", "2013", "2013", "2013", "2013", "2013", "2013", "2013", …
$ month <chr> "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",…
$ day <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "…
The tidyverse way: no loop at all
Doing the same thing to several columns is so common that dplyr has a function for it: across(). It applies a function to every column you choose, in one line.
df <- flights |>
distinct(year, month, day) |>
mutate(across(everything(), as.character))
glimpse(df)Rows: 365
Columns: 3
$ year <chr> "2013", "2013", "2013", "2013", "2013", "2013", "2013", "2013", …
$ month <chr> "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",…
$ day <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "…
across(everything(), as.character) reads as “across every column, apply as.character”. No loop variable, no get(), no :=. When you find yourself looping over columns, across() is usually the better tool.
Vectorization: often you don’t need a loop
Most R functions are vectorized: they work on a whole vector at once. A beginner might write a loop to add 1 to every element:
x <- c(3, 7, 10)
result <- numeric(length(x)) # an empty vector to fill
for (i in seq_along(x)) { # i = 1, 2, 3
result[i] <- x[i] + 1
}
result[1] 4 8 11
But x + 1 does the same thing:
x + 1[1] 4 8 11
The same goes for str_c(), str_detect(), round(), ymd() and almost everything else we’ve used: give them a column and they handle every row. That’s why mutate() rarely needs a loop.
Two habits from the loop above are worth knowing for the times you do write one:
seq_along(x)gives1, 2, 3, ...up to the length ofx. It’s safer than1:length(x), which gives1, 0whenxis empty.- Make the output first, with
numeric(length(x))orvector("list", length(x)), then fill it in. Growing a vector one element at a time withc()gets slow for long loops.
Writing your own functions
A function packages code so you can reuse it with different inputs. The general form is:
name <- function(input1, input2) {
# do something with the inputs
# the last value is what the function returns
}A simple function
rescale01() stretches any numeric vector to run from 0 to 1. Writing it as a function means the formula lives in one place:
rescale01 <- function(x) {
rng <- range(x, na.rm = TRUE)
(x - rng[1]) / (rng[2] - rng[1])
}
rescale01(c(2, 4, 6, 10))[1] 0.00 0.25 0.50 1.00
Because it’s vectorized, it works inside mutate(), and with across() on many columns at once:
penguins |>
select(species, bill_length_mm, flipper_length_mm, body_mass_g) |>
mutate(across(where(is.numeric), rescale01)) |>
head()# A tibble: 6 × 4
species bill_length_mm flipper_length_mm body_mass_g
<fct> <dbl> <dbl> <dbl>
1 Adelie 0.255 0.153 0.292
2 Adelie 0.269 0.237 0.306
3 Adelie 0.298 0.390 0.153
4 Adelie NA NA NA
5 Adelie 0.167 0.356 0.208
6 Adelie 0.262 0.305 0.264
where(is.numeric) selects every numeric column, so the function is applied to all three measurements and species is left alone.
Functions that use column names
Suppose we keep writing the same summary for different columns:
penguins |> group_by(species) |> summarize(mean = mean(bill_length_mm, na.rm = TRUE), n = n())
penguins |> group_by(species) |> summarize(mean = mean(body_mass_g, na.rm = TRUE), n = n())
penguins |> group_by(species) |> summarize(mean = mean(flipper_length_mm, na.rm = TRUE), n = n())That’s three copies, so it’s time for a function. But a plain function argument doesn’t work with dplyr: inside the function, dplyr would look for a column literally named var. Embracing the argument with {{ }} tells dplyr to use the column the caller named:
summarize_by_species <- function(data, var) {
data |>
group_by(species) |>
summarize(
mean = mean({{ var }}, na.rm = TRUE),
sd = sd({{ var }}, na.rm = TRUE),
n = n()
)
}
summarize_by_species(penguins, body_mass_g)# A tibble: 3 × 4
species mean sd n
<fct> <dbl> <dbl> <int>
1 Adelie 3701. 459. 152
2 Chinstrap 3733. 384. 68
3 Gentoo 5076. 504. 124
summarize_by_species(penguins, flipper_length_mm)# A tibble: 3 × 4
species mean sd n
<fct> <dbl> <dbl> <int>
1 Adelie 190. 6.54 152
2 Chinstrap 196. 7.13 68
3 Gentoo 217. 6.48 124
This is the same {{ }} that appeared in the regex loop. Its job is always the same: use the thing this variable refers to, not the variable’s own name.
There are two ways to pass a column to a function, and you’ll see both:
| you pass | example call | inside the function |
|---|---|---|
| the bare column name | summarize_by_species(penguins, body_mass_g) |
{{ var }} |
| the name as a string | summarize_by_species(penguins, "body_mass_g") |
.data[[var]] |
Strings are what you get from names(), from loops, and from Shiny inputs: that’s why our Shiny apps used .data[[input$xvar]].
More across()
across() also works in summarize(), and can apply several functions at once. Give the functions as a named list; the .names argument controls how the new columns are named ({.col} is the column, {.fn} the function’s name).
penguins |>
group_by(species) |>
summarize(across(
c(bill_length_mm, body_mass_g),
list(mean = \(x) mean(x, na.rm = TRUE), sd = \(x) sd(x, na.rm = TRUE)),
.names = "{.col}_{.fn}"
))# A tibble: 3 × 5
species bill_length_mm_mean bill_length_mm_sd body_mass_g_mean body_mass_g_sd
<fct> <dbl> <dbl> <dbl> <dbl>
1 Adelie 38.8 2.66 3701. 459.
2 Chinstr… 48.8 3.34 3733. 384.
3 Gentoo 47.5 3.08 5076. 504.
\(x) mean(x, na.rm = TRUE) is a short anonymous function: a function with no name, written right where it’s used. \(x) is shorthand for function(x).
map(): iterating over anything
across() iterates over the columns of a data frame. The purrr package’s map() functions iterate over the elements of any vector or list, applying a function to each one.
map(1:3, \(i) i^2)[[1]]
[1] 1
[[2]]
[1] 4
[[3]]
[1] 9
map() always returns a list. Its variants return a vector of a specific type, which is usually what you want:
| function | returns |
|---|---|
map() |
a list |
map_dbl() |
a numeric vector |
map_int() |
an integer vector |
map_chr() |
a character vector |
map_lgl() |
a logical (TRUE/FALSE) vector |
map2_*() |
the same, but iterating over two inputs side by side |
map_dbl(1:3, \(i) i^2)[1] 1 4 9
Example: one value per column
How many missing values does each penguin column have? map_int() applies a function to every column (a data frame is a list of columns):
penguins |> map_int(\(col) sum(is.na(col))) species island bill_length_mm bill_depth_mm
0 0 2 2
flipper_length_mm body_mass_g sex year
2 2 11 0
The Netflix notes used the same idea to count the titles matching each theme: map_int(pattern, \(p) sum(str_detect(...))) ran the count once for every regex pattern.
Example: a function of two columns with map2()
map2_chr() walks along two vectors at once, calling a function on the first element of each, then the second, and so on. It’s the tool for a function that isn’t vectorized, applied row by row to two columns.
describe <- function(species, mass) {
if (is.na(mass)) return(str_c(species, ": mass unknown"))
size <- if (mass > 4500) "large" else "small"
str_c("a ", size, " ", species)
}
set.seed(309) # so the random sample is the same every time
penguins |>
slice_sample(n = 5) |>
mutate(label = map2_chr(species, body_mass_g, describe)) |>
select(species, body_mass_g, label)# A tibble: 5 × 3
species body_mass_g label
<fct> <int> <chr>
1 Adelie 4000 a small Adelie
2 Adelie 4200 a small Adelie
3 Chinstrap 3950 a small Chinstrap
4 Adelie 4400 a small Adelie
5 Adelie 3475 a small Adelie
if only works on one value at a time, so describe() can’t take a whole column. map2_chr() calls it once per row.
Example: one model per group
group_split() splits a data frame into a list of smaller data frames, one per group. map() then fits a model to each, and broom::glance() summarizes them.
penguins |>
drop_na(flipper_length_mm, body_mass_g) |>
group_split(species) |>
set_names(c("Adelie", "Chinstrap", "Gentoo")) |>
map(\(d) lm(body_mass_g ~ flipper_length_mm, data = d)) |>
map(broom::glance) |>
list_rbind(names_to = "species") |>
select(species, r.squared, sigma)# A tibble: 3 × 3
species r.squared sigma
<chr> <dbl> <dbl>
1 Adelie 0.219 407.
2 Chinstrap 0.412 297.
3 Gentoo 0.494 360.
Flipper length explains body mass best for Gentoos (R² ≈ 0.49) and worst for Adelies (R² ≈ 0.22). One pipeline, three models, no copying.
When a for loop is still the right tool
Loops are still the clearest choice when each step does something rather than returns something: saving files, printing, or running a simulation where each step depends on the last.
# save one plot per species
for (sp in unique(penguins$species)) {
p <- penguins |>
filter(species == sp) |>
ggplot(aes(flipper_length_mm, body_mass_g)) +
geom_point() +
labs(title = sp)
ggsave(str_c("plot_", sp, ".png"), p, width = 5, height = 4)
}purrr’s walk() does the same, for functions you call for their side effects rather than their output.
Which tool when?
| task | tool |
|---|---|
| same calculation on every row | a vectorized function in mutate() |
| same function on several columns | across() |
| same code with different inputs | your own function() |
| same function on every element of a list or vector | map_*() |
| same function on pairs of values, row by row | map2_*() |
| repeated actions with side effects (saving, printing) | a for loop or walk() |
Try it yourself
- Use
across()to round every numeric column ofpenguinsto 0 decimal places. - Write a function
count_na(data)that returns the number of missing values in each column. (Hint: usemap_int()inside it.) - Rewrite
summarize_by_species()so it takes the grouping column as an argument too, and use it to summarizebody_mass_gbyisland. - Use
map_dbl()to compute the mean of every numeric column ofmtcars. Then do the same withsummarize(across(...)). Which do you prefer?