Purrr – mapping pmap functions to data

In functional programming paradigm, map is used to map a set of values to another set of values based on the function used.



In general sense, a unit of function should only be used to map one value to another. While this utility can be applied to a list of inputs to produce another set of input using map function.  It takes two inputs

  • Function
  • Sequence of values

It produces new sequence of values where the function has been applied.

which prints

Note that the above is only used for one input. For two input values you can use map2.

Now for situations where you need to use multiple input values(say multiple lists) to apply to a function, you can use pmap

An important point- Length of x and y should be same.

which produces


What’s the difference to map and map2?

Both map and map2 take vector arguments directly like x = and y = , while pmap takes a list of arguments like list(x = , y = ).

Exploring purrr furthur, I see new use cases which I will explain in next posts.


purrrr is a productivity ninza. Try to  use it.

Think Functional!

Functional Programming in R – what is Lazy evaluation?

Under Lazy evaluation, evaluation of function argument is delayed until necessary. This differs to strict evaluation where the arguments of a function are evaluated before the function is called.

Let’s see an example-

In the first function call, “I am evaluated” is not printed as it is not required to be evaluated. This is also called call-by-promise.

It could be useful when you have parameters which need to be evaluated when only certain conditions are met.

Another example-

Here b is not evaluated until the execution reaches the expression a + b.

Moreover, The expressions you give to function calls are evaluated in the scope outside the function.

Hence the below will give error as it remains unknown when b = a is evaluated as it looks for the value of ain the global scope(outside function f)