map_vec: Mapping functions that automatically determine type

View source: R/map_vec.R

map_vecR Documentation

Mapping functions that automatically determine type

Description

These functions work exactly the same as typed variants of purrr::map(), purrr::map2(), purrr::pmap(), purrr::imap() and xmap() (e.g. purrr::map_chr()), but automatically determine the type.

Usage

map_vec(.x, .f, ..., .class = NULL)

map2_vec(.x, .y, .f, ..., .class = NULL)

pmap_vec(.l, .f, ..., .class = NULL)

imap_vec(.x, .f, ..., .class = NULL)

xmap_vec(.l, .f, ..., .class = NULL)

Arguments

.x

A list or atomic vector.

.f

A function, formula, or vector (not necessarily atomic).

If a function, it is used as is.

If a formula, e.g. ~ .x + 2, it is converted to a function. There are three ways to refer to the arguments:

  • For a single argument function, use .

  • For a two argument function, use .x and .y

  • For more arguments, use ..1, ..2, ..3 etc

This syntax allows you to create very compact anonymous functions.

If character vector, numeric vector, or list, it is converted to an extractor function. Character vectors index by name and numeric vectors index by position; use a list to index by position and name at different levels. If a component is not present, the value of .default will be returned.

...

Additional arguments passed on to .f

.class

If .class is specified, all

.y

A vector the same length as .x. Vectors of length 1 will be recycled.

.l

A list of vectors, such as a data frame. The length of .l determines the number of arguments that .f will be called with. List names will be used if present.

Value

Equivalent to the typed variants of purrr::map(), purrr::map2(), purrr::pmap(), purrr::imap() and xmap() with the type automatically determined.

If the output contains multiple types, the type is determined from the highest type of the components in the hierarchy raw < logical < integer < double < complex < character < list (as in c()).

If the output contains elements that cannot be coerced to vectors (e.g. lists), the output will be a list.

See Also

The original functions: purrr::map(), purrr::map2(), purrr::pmap(), purrr::imap() and xmap()

Parallelized equivalents: future_map_vec(), future_map2_vec(), future_pmap_vec(), future_imap_vec() and future_xmap_vec()

Examples

fruits   <- c("apple", "banana", "cantaloupe", "durian", "eggplant")
desserts <- c("bread", "cake", "cupcake", "muffin", "streudel")
x        <- sample(5)
y        <- sample(5)
z        <- sample(5)
names(z) <- fruits

map_vec(x, ~ . ^ 2)
map_vec(fruits, paste0, "s")

map2_vec(x, y, ~ .x + .y)
map2_vec(fruits, desserts, paste)

pmap_vec(list(x, y, z), sum)
pmap_vec(list(x, fruits, desserts), paste)

imap_vec(x, ~ .x + .y)
imap_vec(x, ~ paste0(.y, ": ", .x))
imap_vec(z, paste)

xmap_vec(list(x, y), ~ .x * .y)
xmap_vec(list(fruits, desserts), paste)

crossmap documentation built on Jan. 13, 2023, 1:13 a.m.