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:
1 |
library(purrr) |
Create a list x with 100 elements:
1 |
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:
1 |
map(x,function(x) x > 7) |
Let us now create another list y:
1 |
y = as.list(runif(100,1,100)) |
Given two lists of the same size, we can sum the corresponding elements using the map2 function:
1 |
map2(x,y,sum) |
With pmap we can implement any function on any number of lists or vectors:
1 2 |
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:
1 |
func = function(x) x > 20 |
We use the keep function to select the elements of the list that satisfy the expression in the function:
1 |
keep(x,func) |
We achieve the opposite effect with the discard function:
1 |
discard(x,func) |
The head_while function returns all the first elements of the list that satisfy the expression:
1 |
head_while(x, func) |
To check if all elements of the list satisfy the expression, every is used:
1 2 |
every(x, func) [1] FALSE |
Some checks if any of the elements satisfy the expression:
1 2 |
some(x,func) [1] TRUE |
Has_element can be used to check whether a list contains a particular element:
1 2 3 |
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:
1 |
func = function(x) x < 20 |
1 2 |
detect(x,func) [1] 14.75841 |
We can also return just the index of that list element with detect_index:
1 2 |
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:
1 |
append(x,y) |
Given a multidimensional list:
1 |
l = list(list(1,2,3),list(4,5),list(5)) |
We can simplify it to one-dimensional using flatten:
1 |
flatten(l) |
Or transpose:
1 |
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 🙂