lambda Function Builder

John Mount


The CRAN version of the R package wrapr package now includes a concise anonymous function constructor: l().

To use it please do the following: attach wrapr and ask it to place a definition for l() in your environment:

wrapr::defineLambda(name = "l")
##  [1] "LEFT_NAME"    "OTHER_SYMBOL" "X"            "Y"           
##  [5] "angle"        "d"            "d2"           "df"          
##  [9] "exp_step"     "f"            "f5"           "inputs"      
## [13] "l"            "model"        "model_f"      "model_o"     
## [17] "model_p"      "plotb"        "pred_step"    "s4"          
## [21] "s5"           "variable"     "x"

Note: throughout this document we are using the letter “l” as a stand-in for the Greek letter lambda, as this non-ASCII character can cause formatting problems in some situations.

You can use l() to define functions. The syntax is: l(arg [, arg]*, body [, env=env]). That is we write a l()-call (which you can do by cutting and pasting) and list the desired function arguments and then the function body. For example the function that squares numbers is:

l(x, x^2)
## function (x) 
## x^2

We can use such a function to square the first four positive integers as follows:

sapply(1:4, l(x, x^2))
## [1]  1  4  9 16

Dot-pipe style notation does not need the l() factory as it treats pipe stages as expressions parameterized over the variable “.”:

1:4 %.>% { .^2 }
## [1]  1  4  9 16

If you do want an operator notation for function construction you can also use on of the variations of the named map builder:

(1:4) %.>% (x := { x^2 })(.)
## [1]  1  4  9 16

And we can build functions that take more than one argument as follows:

l(x, y, x + 3*y)
## function (x, y) 
## x + 3 * y