Mapping

purrr 1.1.0

purrr
There are three big new mapping features in purrr 1.0.0: progress bars, better errors, and map_vec().
Published

December 20, 2022

Install purrr 1.0.0 with:

pak::pak("cran/purrr@1.0.0")

Load the package with:

Mapping

There are three big new mapping features in purrr 1.0.0:

  • Progress bars!
  • Better errors
  • A new map_* family member: map_vec().

Progress bars

See a progress bar for long running jobs using .progress = TRUE:

x <- map(1:100, \(x) Sys.sleep(0.1), .progress = TRUE)
 ■■■■■■■                           21% |  ETA:  8s
 ■■■■■■■■■■■■■■■■                  50% |  ETA:  5s
 ■■■■■■■■■■■■■■■■■■■■■■■■■         79% |  ETA:  2s

Set .progress to a string if you want to identify the progress bar (in this case, .progress = "Saving plots").

x <- map(1:100, \(x) Sys.sleep(0.1), .progress = "Waiting...")
Waiting... ■■■■■■■■■■■■                      37% |  ETA:  6s
Waiting... ■■■■■■■■■■■■■■■■■■■■■             66% |  ETA:  3s
Waiting... ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■     95% |  ETA:  1s

Better errors

map() and friends now tell you which element caused the problem in the function you mapped.

In this case, we have a list with two numeric and one character value. When we try to divide it by 2 using map(), we get an error telling us there’s an issue with index 3 ("a").

x <- list(10, 5, "a")
x |> map(\(x) x / 2)
Error in `map()`:
ℹ In index: 3.
Caused by error in `x / 2`:
! non-numeric argument to binary operator

map_vec()

The map_* family applies a function to each element of a list. We’ve had map(), map_lgl(), map_int(), map_dbl(), and map_chr().

1:3 |> map(\(x) x / 2) # map always returns a list
[[1]]
[1] 0.5

[[2]]
[1] 1

[[3]]
[1] 1.5

Now we have: map_vec()!

map_vec() is a generalized map_*() that works with an arbitrary types of vectors, like dates, factors, and date-times.

1:3 |> map_vec(\(i) as.Date(ISOdate(2023, 2 + i, 5)))
[1] "2023-03-05" "2023-04-05" "2023-05-05"

It will error if you try to combine different types:

list("a", 1) |> map_vec(identity)
Error in `map_vec()`:
! Can't combine `<list>[[1]]` <character> and `<list>[[2]]` <double>.

Learn more