purrr
map() calls a function once per element of a list or vector and returns the results in a
list of the same length. The typed variants, map_dbl(), map_chr(), and the rest, return a
vector and fail loudly when a result has the wrong type. The examples use gene sets, per gene
tests, and one result file per contrast.
Quick reference
Section titled “Quick reference”| Function | Returns | Purpose |
|---|---|---|
map() |
list | Apply a function to each element |
map_dbl(), map_int(), map_lgl(), map_chr() |
vector | Same, with a typed result |
map2(), pmap() |
list | Two inputs, or many |
imap() |
list | Value and name |
pluck() |
element | Dig into a nested list |
keep(), discard() |
list | Filter a list |
reduce() |
value | Fold a list with a two argument function |
walk(), walk2() |
input, invisibly | Side effects such as writing files |
list_rbind(), list_cbind() |
data frame | Bind a list of tables by row or column |
possibly(), safely() |
function | Handle errors inside a map |
library(purrr)library(dplyr)library(tidyr)library(readr)
# Match the printed width on this page.options(width = 80)set.seed(42)
gene_sets <- list( apoptosis = c("TP53", "BAX", "BCL2", "CASP3", "CASP9"), cell_cycle = c("CDK1", "CDK2", "CCNB1", "TP53", "RB1"), dna_repair = c("BRCA1", "BRCA2", "ATM", "TP53"))Map over one input
Section titled “Map over one input”map() always returns a list, with the names of the input. Write the function inline with \(x),
the short form of function(x) since R 4.1. The purrr formula ~ .x still works in older
code.
map(gene_sets, \(genes) head(genes, 2))$apoptosis[1] "TP53" "BAX"
$cell_cycle[1] "CDK1" "CDK2"
$dna_repair[1] "BRCA1" "BRCA2"map_int(), map_dbl(), map_lgl(), map_chr()
Section titled “map_int(), map_dbl(), map_lgl(), map_chr()”The suffix names the type of the result, and the result is a named vector.
map_int(gene_sets, length) apoptosis cell_cycle dna_repair 5 5 4expression <- list( TP53 = c(10.2, 11.5, 9.8, 10.1), BRCA1 = c(5.3, 6.1, 4.9, 5.5), EGFR = c(15.0, 14.2, 16.1, 15.5))map_dbl(expression, mean) TP53 BRCA1 EGFR10.40 5.45 15.20map_lgl(gene_sets, \(genes) "BRCA1" %in% genes) apoptosis cell_cycle dna_repair FALSE FALSE TRUEmap_chr(gene_sets, \(genes) paste(genes, collapse = ",")) apoptosis cell_cycle"TP53,BAX,BCL2,CASP3,CASP9" "CDK1,CDK2,CCNB1,TP53,RB1" dna_repair "BRCA1,BRCA2,ATM,TP53"purrr 1.2 stopped map_chr() from turning numbers into strings, so map_chr(gene_sets, length) from an older tutorial now fails. Use map_int(), or convert inside the function.
The error names the element where the map stopped.
tryCatch( map_chr(gene_sets, length), error = \(e) cat(conditionMessage(e), sep = "\n"))ℹ In index: 1.ℹ With name: apoptosis.Caused by error:! Can't coerce from an integer to a string.Extract by name or position
Section titled “Extract by name or position”A string in place of a function extracts that element from each item. pluck() digs into
one item.
gene_info <- list( list(symbol = "TP53", biotype = "protein_coding", chrom = "chr17"), list(symbol = "MALAT1", biotype = "lncRNA", chrom = "chr11"), list(symbol = "MIR21", biotype = "miRNA", chrom = "chr17"))map_chr(gene_info, "symbol")pluck(gene_info, 2, "biotype")[1] "TP53" "MALAT1" "MIR21"[1] "lncRNA"Map over two or more inputs
Section titled “Map over two or more inputs”map2()
Section titled “map2()”map2() walks two lists in parallel. Here it counts the overlap of matching up and down
sets from two experiments.
set_a <- list(up = c("TP53", "MYC", "EGFR"), down = c("PTEN", "RB1"))set_b <- list(up = c("TP53", "EGFR", "KRAS"), down = c("RB1", "APC", "PTEN"))map2_int(set_a, set_b, \(a, b) length(intersect(a, b))) up down 2 2pmap()
Section titled “pmap()”pmap() takes a list or a data frame and matches its names to the arguments of the
function. Each row here is one call to rnorm().
sim_params <- tibble(n = c(3, 2), mean = c(10, 50), sd = c(1, 5))pmap(sim_params, rnorm)[[1]][1] 11.370958 9.435302 10.363128
[[2]][1] 53.16431 52.02134imap()
Section titled “imap()”imap() passes each value and its name.
padj <- c(TP53 = 3.1e-08, MYC = 0.0042, EGFR = 0.31)imap_chr(padj, \(p, gene) sprintf("%s: %.2g", gene, p)) TP53 MYC EGFR"TP53: 3.1e-08" "MYC: 0.0042" "EGFR: 0.31"Filter and fold a list
Section titled “Filter and fold a list”keep() and discard()
Section titled “keep() and discard()”keep() returns the elements where the function is TRUE. discard() returns the others.
keep(gene_sets, \(genes) length(genes) >= 5) |> names()[1] "apoptosis" "cell_cycle"reduce()
Section titled “reduce()”reduce() applies a two argument function across the list, left to right. With
intersect() it returns the genes found in every replicate.
deg_lists <- list( rep1 = c("TP53", "MYC", "EGFR", "KRAS"), rep2 = c("TP53", "EGFR", "KRAS", "PTEN"), rep3 = c("EGFR", "TP53", "KRAS", "RB1"))reduce(deg_lists, intersect)reduce(deg_lists, union)[1] "TP53" "EGFR" "KRAS"[1] "TP53" "MYC" "EGFR" "KRAS" "PTEN" "RB1"One model per group
Section titled “One model per group”nest() and map() in mutate()
Section titled “nest() and map() in mutate()”Nest the rows of each gene, fit a test per gene, and pull numbers out of the fits with
map_dbl(). For thousands of genes, limma or DESeq2 is the right tool. This pattern suits a
handful of genes or any per group model.
expr_long <- tibble( gene = rep(c("TP53", "MYC", "EGFR"), each = 6), group = rep(rep(c("ctrl", "trt"), each = 3), times = 3), log_expr = round(c( rnorm(3, 10, 0.3), rnorm(3, 11.5, 0.3), rnorm(3, 12, 0.4), rnorm(3, 12.1, 0.4), rnorm(3, 8, 0.2), rnorm(3, 6.9, 0.2) ), 2))expr_long |> nest(.by = gene) |> mutate( fit = map(data, \(d) t.test(log_expr ~ group, data = d)), diff = map_dbl(fit, \(f) unname(diff(f$estimate))), p_value = map_dbl(fit, \(f) f$p.value) ) |> select(gene, diff, p_value)# A tibble: 3 × 3 gene diff p_value <chr> <dbl> <dbl>1 TP53 1.70 0.002432 MYC 0.0500 0.9203 EGFR -0.997 0.0451walk2() to write one file per table
Section titled “walk2() to write one file per table”walk() and walk2() call a function for its side effect, such as writing a file, and
return their input invisibly.
out_dir <- file.path(tempdir(), "deg")dir.create(out_dir)deg_tables <- list( trt_vs_ctrl = tibble(gene = c("TP53", "MYC"), log2fc = c(1.12, 1.94)), kd_vs_ctrl = tibble(gene = c("TP53", "MYC"), log2fc = c(-0.41, 0.22)))paths <- file.path(out_dir, paste0(names(deg_tables), ".csv"))walk2(deg_tables, paths, \(tbl, path) write_csv(tbl, path))list.files(out_dir)[1] "kd_vs_ctrl.csv" "trt_vs_ctrl.csv"Read them back with map() and list_rbind()
Section titled “Read them back with map() and list_rbind()”Name the paths, read each file, and stack the tables. names_to turns the names into a
column. map_dfr() did this in one call and is superseded by map() plus list_rbind().
list.files(out_dir, full.names = TRUE) |> set_names(\(p) tools::file_path_sans_ext(basename(p))) |> map(\(p) read_csv(p, show_col_types = FALSE)) |> list_rbind(names_to = "contrast")# A tibble: 4 × 3 contrast gene log2fc <chr> <chr> <dbl>1 kd_vs_ctrl TP53 -0.412 kd_vs_ctrl MYC 0.223 trt_vs_ctrl TP53 1.124 trt_vs_ctrl MYC 1.94When every file has the same columns and needs no cleanup of its own,
read_csv(paths, id = "file") does the same in one call. The
tibble & readr cheatsheet shows it.
Errors
Section titled “Errors”possibly()
Section titled “possibly()”possibly() wraps a function so that an error returns a default value instead of stopping
the loop. log(-5) is not an error, so it returns NaN with a warning.
log_or_na <- possibly(log, otherwise = NA_real_)map_dbl(list(10, -5, "text", 0.01), log_or_na)[1] 2.302585 NaN NA -4.605170safely()
Section titled “safely()”safely() returns a list with result and error for every call, so you can see which
input failed and why.
log_safely <- safely(log)results <- map(list(10, "text"), log_safely)map_lgl(results, \(r) is.null(r$error))conditionMessage(results[[2]]$error)[1] TRUE FALSE[1] "non-numeric argument to mathematical function"purrr and base R
Section titled “purrr and base R”| purrr | Base R |
|---|---|
map(x, f) |
lapply(x, f) |
map_dbl(x, f) |
vapply(x, f, numeric(1)) |
map2(x, y, f) |
Map(f, x, y) |
keep(x, f) |
Filter(f, x) |
reduce(x, f) |
Reduce(f, x) |
walk(x, f) |
a for loop |
See also
Section titled “See also”- Functions covers writing the functions you pass to
map(), with roxygen documentation. - Control Flow shows the
forloop that amap()call replaces, and when a vectorized function beats both. - Alternatives to Loops runs
map(),map_dbl(), andmap2_dbl()besidevapply()andMap()on one count matrix. - The tidyr cheatsheet covers
nest()andunnest(), the shape that per group models start from.
Scientific references
Section titled “Scientific references”The purrr package by Wickham and Henry supplies functional programming tools.
Further reading
Section titled “Further reading”-
The original examples show how possibly() substitutes a result after an error. Compare its behavior with warnings in the logarithm example.