map2 | R Documentation |
These functions are variants of map()
that iterate over two arguments at
a time.
map2(.x, .y, .f, ..., .progress = FALSE)
map2_lgl(.x, .y, .f, ..., .progress = FALSE)
map2_int(.x, .y, .f, ..., .progress = FALSE)
map2_dbl(.x, .y, .f, ..., .progress = FALSE)
map2_chr(.x, .y, .f, ..., .progress = FALSE)
map2_vec(.x, .y, .f, ..., .ptype = NULL, .progress = FALSE)
walk2(.x, .y, .f, ..., .progress = FALSE)
.x, .y |
A pair of vectors, usually the same length. If not, a vector of length 1 will be recycled to the length of the other. |
.f |
A function, specified in one of the following ways:
|
... |
Additional arguments passed on to the mapped function. We now generally recommend against using # Instead of x |> map(f, 1, 2, collapse = ",") # do: x |> map(\(x) f(x, 1, 2, collapse = ",")) This makes it easier to understand which arguments belong to which function and will tend to yield better error messages. |
.progress |
Whether to show a progress bar. Use |
.ptype |
If |
The output length is determined by the length of the input. The output names are determined by the input names. The output type is determined by the suffix:
No suffix: a list; .f()
can return anything.
_lgl()
, _int()
, _dbl()
, _chr()
return a logical, integer, double,
or character vector respectively; .f()
must return a compatible atomic
vector of length 1.
_vec()
return an atomic or S3 vector, the same type that .f
returns.
.f
can return pretty much any type of vector, as long as its length 1.
walk()
returns the input .x
(invisibly). This makes it easy to
use in a pipe. The return value of .f()
is ignored.
Any errors thrown by .f
will be wrapped in an error with class
purrr_error_indexed.
Other map variants:
imap()
,
lmap()
,
map_depth()
,
map_if()
,
map()
,
modify()
,
pmap()
x <- list(1, 1, 1)
y <- list(10, 20, 30)
map2(x, y, \(x, y) x + y)
# Or just
map2(x, y, `+`)
# Split into pieces, fit model to each piece, then predict
by_cyl <- mtcars |> split(mtcars$cyl)
mods <- by_cyl |> map(\(df) lm(mpg ~ wt, data = df))
map2(mods, by_cyl, predict)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.