Learn R Programming

purrr

Overview

purrr enhances R’s functional programming (FP) toolkit by providing a complete and consistent set of tools for working with functions and vectors. If you’ve never heard of FP before, the best place to start is the family of map() functions which allow you to replace many for loops with code that is both more succinct and easier to read. The best place to learn about the map() functions is the iteration chapter in R for Data Science.

Installation

# The easiest way to get purrr is to install the whole tidyverse:
install.packages("tidyverse")

# Alternatively, install just purrr:
install.packages("purrr")

# Or the the development version from GitHub:
# install.packages("pak")
pak::pak("tidyverse/purrr")

Cheatsheet

Usage

The following example uses purrr to solve a fairly realistic problem: split a data frame into pieces, fit a model to each piece, compute the summary, then extract the R2.

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

This example illustrates some of the advantages of purrr functions over the equivalents in base R:

  • The first argument is always the data, so purrr works naturally with the pipe.

  • All purrr functions are type-stable. They always return the advertised output type (map() returns lists; map_dbl() returns double vectors), or they throw an error.

  • All map() functions accept functions (named, anonymous, and lambda), character vector (used to extract components by name), or numeric vectors (used to extract by position).

Copy Link

Version

Install

install.packages('purrr')

Monthly Downloads

982,701

Version

1.0.4

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Hadley Wickham

Last Published

February 5th, 2025

Functions in purrr (1.0.4)

get-attr

Infix attribute accessor
head_while

Find head/tail that all satisfies a predicate.
has_element

Does a list contain an object?
detect

Find the value or position of the first match
imap

Apply a function to each element of a vector, and its index
every

Do every, some, or none of the elements of a list satisfy a predicate?
flatten

Flatten a list of lists into a simple vector
cross

Produce all combinations of list elements
faq-adverbs-export

Best practices for exporting adverb-wrapped functions
insistently

Transform a function to wait then retry after an error
invoke

Invoke functions.
keep

Keep/discard elements based on their values
list_c

Combine list elements into a single data structure
list_assign

Modify a list
lmap

Apply a function to list-elements of a list
list_transpose

Transpose a list
keep_at

Keep/discard elements based on their name/position
lift

Lift the domain of a function
list_flatten

Flatten a list
list_simplify

Simplify a list to an atomic or S3 vector
map

Apply a function to each element of a vector
map_if

Apply a function to each element of a vector conditionally
map2

Map over two inputs
modify

Modify elements selectively
map_depth

Map/modify elements at given depth
map_raw

Functions that return raw vectors
map_dfr

Functions that return data frames
modify_tree

Recursively modify a list
modify_in

Modify a pluck location
prepend

Prepend a vector
pluck

Safely get or set an element deep within a nested data structure
partial

Partially apply a function, filling in some arguments
pluck_depth

Compute the depth of a vector
negate

Negate a predicate function so it selects what it previously rejected
pmap

Map over multiple input simultaneously (in "parallel")
possibly

Wrap a function to return a value instead of an error
purrr-package

purrr: Functional Programming Tools
purrr_error_indexed

Indexed errors (purrr_error_indexed)
reduce_right

Reduce from the right (retired)
reduce

Reduce a list to a single value by iteratively applying a binary function
%>%

Pipe operator
reexports

Objects exported from other packages
rdunif

Generate random sample from a discrete uniform distribution
safely

Wrap a function to capture errors
slowly

Wrap a function to wait between executions
rerun

Re-run expressions multiple times
when

Match/validate a set of conditions for an object and continue with the action associated with the first valid match.
progress_bars

Progress bars in purrr
quietly

Wrap a function to capture side-effects
rate-helpers

Create delaying rate settings
splice

Splice objects and lists of objects into a list
rate_sleep

Wait for a given time
rbernoulli

Generate random sample from a Bernoulli distribution
transpose

Transpose a list.
update_list

Update a list with formulas
chuck

Get an element deep within a nested data structure, failing if it doesn't exist
as_vector

Coerce a list to a vector
accumulate

Accumulate intermediate results of a vector reduction
compose

Compose multiple functions together to create a new function
attr_getter

Create an attribute getter function
array-coercion

Coerce array to list
auto_browse

Wrap a function so it will automatically browse() on error
as_mapper

Convert an object into a mapper function
at_depth

Map at depth
along

Create a list of given length