R

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:

library(purrr)

Create a list x with 100 elements:

x = as.list(runif(100,1,100))

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:

map(x,function(x) x > 7)

Let us now create another list y:

y = as.list(runif(100,1,100))

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

map2(x,y,sum)

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

z = as.list(runif(100,1,100))
pmap(list(x,y,z),function(x,y,z) sqrt(x^2+y^2+z^2))

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:

func = function(x) x > 20

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

keep(x,func)

We achieve the opposite effect with the discard function:

discard(x,func)

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

head_while(x, func)

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

every(x, func)
[1] FALSE

Some checks if any of the elements satisfy the expression:

some(x,func)
[1] TRUE

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

n = c("ibm","asus","acer","microsoft")
has_element(n,"asus")
[1] TRUE

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

func = function(x) x < 20
detect(x,func)
[1] 14.75841

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

detect_index(x,func)
[1] 5

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

append(x,y)

Given a multidimensional list:

l = list(list(1,2,3),list(4,5),list(5))

We can simplify it to one-dimensional using flatten:

flatten(l)

Or transpose:

transpose(l)

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. Required fields are marked *