Purrr – functions on vectors and lists

The Purrr library is a function programming toolkit for working with functions, vectors, and lists that makes it easy to avoid loops.

Let’s begin our exploration of this library by initializing it:

Create a list x with 100 elements:

Using the map function, we will implement an arbitrary function for each element of the list. For example, to check if a given element is greater than 7:

Let us now create another list y:

Given two lists of the same size, we can sum the corresponding elements using the map2 function:

With pmap we can implement any function on any number of lists or vectors:

The purrr library has many tools to quickly filter lists and vectors. Let’s first write a function func that returns a boolean value if x is greater than 20:

We use the keep function to select the elements of the list that satisfy the expression in the function:

We achieve the opposite effect with the discard function:

The head_while function returns all the first elements of the list that satisfy the expression:

To check if all elements of the list satisfy the expression, every is used:

Some checks if any of the elements satisfy the expression:

Has_element can be used to check whether a list contains a particular element:

Use the detect function to return the first value from the list that satisfies the expression:

We can also return just the index of that list element with detect_index:

To concatenate lists, we use append and prepend. The difference between them is that the order of the concatenated elements is reversed:

Given a multidimensional list:

We can simplify it to one-dimensional using flatten:

Or transpose:

The library presented today is a powerful toolbox to work with functional programming on vectors and lists. We have presented only a few of the most interesting applications. For more, you’ll have to consult the documentation 🙂

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil