Learn R Programming

purrr (version 0.1.0)

flatmap: Map a function and flatten the result by one-level

Description

flatmap() is equivalent to map() followed by flatten(). You can also provide .type to check the resulting type conforms to you expectations.

Usage

flatmap(.x, .f, ..., .type)

Arguments

.x
A list or vector.
.f
A function, formula or string.

If a function, it is used as is.

If a formula, e.g. ~ .x + 2, it is converted to a function with a three arguments, .x or ., .y, .z. This allows you

...
Additional arguments passed on to .f.
.type
A string indicating which type you expect the results of .f should be. This can be any of the types returned by typeof(), or "numeric" as a shorthand for either "double" or "integer".

Details

Compared to map_lgl(), map_chr(), etc, flatmap() is adapted to functions returning a variable number of elements.

See Also

map_lgl(), map_chr(), map_dbl(), map_int()

Examples

Run this code
# Sample a variable number of elements from each column and
# concatenate the results
var_select <- function(x) sample(x, size = rdunif(1, 5))
c(mtcars) %>% flatmap(var_select)

# You can also check that the results are of expected type
c(mtcars) %>% flatmap(var_select, .type = "character")
c(mtcars) %>% flatmap(var_select, .type = "numeric")

Run the code above in your browser using DataLab