Use map() functions for functional programming
mainThe map() family of functions allows you to replace for loops with succinct, readable code for working with functions and vectors.
Key characteristics of purrr functions:
- Pipe-friendly: The first argument is always the data, making them compatible with the native R pipe
|>. - Type-stable: Functions like
map()always return lists, while type-specific versions likemap_dbl()always return double vectors (or throw an error if the type doesn't match). - Flexible inputs: Functions accept named functions, anonymous functions (lambdas), character vectors (for extraction by name), or numeric vectors (for extraction by position).
- Progress tracking: All
map()functions include a.progressargument to monitor long-running jobs. - Parallelization: All
map()functions work within_parallel()to distribute computation across multiple cores or machines.
library(purrr)
mtcars |>
split(mtcars$cyl) |> # from base R
map(\(df) lm(mpg ~ wt, data = df)) |>
map(summary) |>
map_dbl("r.squared")
#> 4 6 8
#> 0.5086326 0.4645102 0.4229655