Understanding closure
Functions are the first-class citizens of R. In other words, you can pass a function as the input to an other function. In previous recipes, we illustrated how to create a named function. However, we can also create a function without a name, known as closure (that is, an anonymous function). In this recipe, we will show you how to use closure in a standard function.
Getting ready
Ensure that you completed the previous recipes by installing R on your operating system.
How to do it...
Perform the following steps to create a closure in function:
- First, let's review how a named function works:
>addnum<- function(a,b){ + a + b + } >addnum(2,3) [1] 5
- Now, let's perform the same task to sum up two variables with closure:
> (function(a,b){ ...
Get R for Data Science Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.