Press "Enter" to skip to content

pmap and imap Examples in purrr

Steven Sanderson has a multi-parter for us. First up is a look at the pmap() function in R’s purrr library:

The pmap() function in R is part of the purrr library, which is a package designed to make it easier to work with functions that operate on vectors, lists, and other types of data structures.

The pmap() function is used to apply a function to a list of arguments, where each element in the list contains the arguments for a single function call. The function is applied in parallel, meaning that each call is executed concurrently, which can help speed up computations when working with large datasets.

Next up is the imap() function:

The imap() function is a powerful tool for iterating over a list or a vector while also keeping track of the index or names of the elements. This function applies a given function to each element of a list, along with the name or index of that element, and returns a new list with the results.

The imap() function takes two main arguments: x and .fx is the list or vector to iterate over, and .f is the function to apply to each element. The .f function takes two arguments: x and i, where x is the value of the element and i is the index or name of the element.

Both of these sound a little complex and abstract at first, though as you get more familiar with them, you get to see just how powerful they are.