Learn R Programming

purrr (version 0.1.0)

map2: Map over multiple inputs simultaneously.

Description

These functions are designed in such a way that arguments to be vectorised over come before the function name, and arguments that should be supplied to every call come after the function name.

Usage

map2(.x, .y, .f, ...)

map3(.x, .y, .z, .f, ...)

map_n(.l, .f, ...)

walk2(.x, .y, .f, ...)

walk3(.x, .y, .z, .f, ...)

walk_n(.l, .f, ...)

Arguments

.x,.y,.z
Lists of the same length or of length 1. Only lists of length 1 are recycled.
.f
A function of two (for map2 and walk2) or three (map3 and walk3) arguments. For map_n and walk_n, the number of arguments must correspond to the number of elements of .l
...
Additional arguments passed on to .f.
.l
A list of lists to be mapped on simultaneously.

Details

map_n() and walk_n() take a single list .l and map over all its elements simultaneously. map2() and map3() return a data frame when .x is a data frame.

Examples

Run this code
x <- list(1, 10, 100)
y <- list(1, 2, 3)
map2(x, y, ~ .x + .y)
# Or just
map2(x, y, `+`)

z <- list(15, 20, 25)
map3(x, y, z, ~ .x ^ .y + .z)

# Split into pieces, fit model to each piece, then predict
by_cyl <- mtcars %>% split(.$cyl)
mods <- by_cyl %>% map(~ lm(mpg ~ wt, data = .))
map2(mods, by_cyl, predict)

Run the code above in your browser using DataLab