map2() and pmap() for Multiple Inputs
Iterate over two or more lists simultaneously with map2() and pmap().
Iterating Over Multiple Inputs
map() iterates over one input at a time. But many functions need two or more parallel inputs. purrr's map2() handles two inputs; pmap() handles any number. Both maintain the same type-safe return value guarantee.
library(purrr)
# Simulate: add corresponding elements from two vectors
x <- c(1, 2, 3, 4)
y <- c(10, 20, 30, 40)
# map2 applies fn(x[i], y[i]) for each i
result <- map2(x, y, function(a, b) a + b)
print(result)map2() — Two Parallel Inputs
map2(.x, .y, .f) applies .f(x_i, y_i) to corresponding elements of .x and .y. Both vectors must have the same length (or one has length 1 and is recycled). Returns a list.
library(purrr)
names_vec <- c('Alice','Bob','Carol')
scores_vec <- c(85, 92, 78)
# Build a personalized message for each student
map2_chr(names_vec, scores_vec,
~paste(.x, 'scored', .y, 'points'))All lessons in this course
- map() and Typed Variants
- map2() and pmap() for Multiple Inputs
- reduce(), accumulate(), and walk()
- keep(), discard(), and List Filtering