Learn R Programming

⚠️There's a newer version (1.0.4) of this package.Take me there.

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("remotes")
remotes::install_github("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

1,257,542

Version

1.0.1

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Hadley Wickham

Last Published

January 10th, 2023

Functions in purrr (1.0.1)

as_mapper

Convert an object into a mapper function
as_vector

Coerce a list to a vector
imap

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

Transform a function to wait then retry after an error
attr_getter

Create an attribute getter function
auto_browse

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

Find the value or position of the first match
cross

Produce all combinations of list elements
chuck

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

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

Does a list contain an object?
at_depth

Map at depth
head_while

Find head/tail that all satisfies a predicate.
array-coercion

Coerce array to list
get-attr

Infix attribute accessor
compose

Compose multiple functions together to create a new function
invoke

Invoke functions.
list_flatten

Flatten a list
keep

Keep/discard elements based on their values
flatten

Flatten a list of lists into a simple vector
faq-adverbs-export

Best practices for exporting adverb-wrapped functions
list_transpose

Transpose a list
list_simplify

Simplify a list to an atomic or S3 vector
modify_tree

Recursively modify a list
lmap

Apply a function to list-elements of a list
map2

Map over two inputs
map

Apply a function to each element of a vector
modify

Modify elements selectively
modify_in

Modify a pluck location
keep_at

Keep/discard elements based on their name/position
lift

Lift the domain of a function
list_assign

Modify a list
list_c

Combine list elements into a single data structure
negate

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

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

Apply a function to each element of a vector conditionally
map_raw

Functions that return raw vectors
partial

Partially apply a function, filling in some arguments
pluck_depth

Compute the depth of a vector
progress_bars

Progress bars in purrr
%>%

Pipe operator
rdunif

Generate random sample from a discrete uniform distribution
prepend

Prepend a vector
quietly

Wrap a function to capture side-effects
reduce

Reduce a list to a single value by iteratively applying a binary function
slowly

Wrap a function to wait between executions
reexports

Objects exported from other packages
reduce_right

Reduce from the right (retired)
rate_sleep

Wait for a given time
splice

Splice objects and lists of objects into a list
rbernoulli

Generate random sample from a Bernoulli distribution
purrr-package

purrr: Functional Programming Tools
purrr_error_indexed

Indexed errors (purrr_error_indexed)
possibly

Wrap a function to return a value instead of an error
map_depth

Map/modify elements at given depth
rerun

Re-run expressions multiple times
pmap

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

Wrap a function to capture errors
when

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

Functions that return data frames
rate-helpers

Create delaying rate settings
transpose

Transpose a list.
update_list

Update a list with formulas
accumulate

Accumulate intermediate results of a vector reduction
along

Create a list of given length