Functional programming-Map, Reduce, Filter and Lambda

Liang / 2018-06-17


This post will talk about four useful function in R programming. Map, Reduce, Filter and Lambda.

LAMBDA

Lambda can be seen as a short (normally one line) function definition. There is no particular syntax for lambda in R, except that you don’t need to assign the function to a variable (function name), and also you will need to enclose the function using brackets or curly brace. For example:

(function add(x, y) x+y)
{function add(x, y) x+y}

We can pass the lambda function as a parameter to other functions e.g. Map, Reduce or Filter.

Map

Map function allows the mapping from one vector to another using a map function, which can be specified by lambda. For example, let’s define a vector from 1 to 100.

x = 1:100

If we want to convert each element of the vector to its doubles, so we can pass a lambda to the Map function, like this:

y=Map({function (a) a*2}, x)

However, the variable y will store a list of vectors instead of a single vector. We can use the unlist function to unroll the list of vectors into a single vector.

unlist(y)
##   [1]   2   4   6   8  10  12  14  16  18  20  22  24  26  28  30  32  34
##  [18]  36  38  40  42  44  46  48  50  52  54  56  58  60  62  64  66  68
##  [35]  70  72  74  76  78  80  82  84  86  88  90  92  94  96  98 100 102
##  [52] 104 106 108 110 112 114 116 118 120 122 124 126 128 130 132 134 136
##  [69] 138 140 142 144 146 148 150 152 154 156 158 160 162 164 166 168 170
##  [86] 172 174 176 178 180 182 184 186 188 190 192 194 196 198 200

Reduce

Reduce will perform the function on a list of vectors one by one, and finally return a single value.

x=seq(1,10,0.5)
Reduce({function (x, y) x+y}, x)
## [1] 104.5

The lambda function can be instead with sum here.

Reduce(sum, x)
## [1] 104.5

Filter

The function Filter will remove all elements when they do not satisfy the condition (function returns false)

x = 1:10
Filter({function (x) x%%2==0}, x)
## [1]  2  4  6  8 10

Last modified on 2018-06-17