The tidyverse is built on the idea that problems are most easily solved within the structure of a data frame.

The purrr package allows for functional programming that plays well with data frames using the map functions and for capturing errors with the safely functions. However, the combination of functional programming and capturing errors in purrr returns a list which does not work well with data frames.

purrrplus adds functionality to purrr that allows the combination of functional programming and capturing errors to be kept within the structure of a data frame. This is useful for many data analysis tasks and is particularly useful for conducting simulations.

To learn more about the package, you can either continue reading or watch this video:

Introduction to purrrplus video


Getting started

The old way

The irrelevant variable causes pmap to throw an error:

One way around this is to remove the irrelevant variables:

However, now calculate_if_positive function throws an error that stops everything if any of the rows contain a negative number:

We are applying the function calculate_if_positive 4 times (once for each row in the data frame numbers). It should work for rows 2 and 3 and throw an error for rows 1 and 4.

The purrrr function safely allows us to capture the results when it works and the error when it doesn’t:

However, a function wrapped in safely returns a list which is difficult to work with:

The purrrplus way

pmap_safely is the key function in purrrplus. pmap_safely takes a data frame (which might contain irrelevant variables) and applies a function (which returns a named list or a named vector and might throw an error) to each row.

pmap_safely adds an error and a result column (which come from applying the function) to the inputted data frame.


Notice that "_result" is appended to each of these columns so any subsequent analysis can easily differentiate between variables the function produced and variables it didn’t.