Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
R for Data Science Cookbook (n)

You're reading from   R for Data Science Cookbook (n) Over 100 hands-on recipes to effectively solve real-world data problems using the most popular R packages and techniques

Arrow left icon
Product type Paperback
Published in Jul 2016
Publisher
ISBN-13 9781784390815
Length 452 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Yu-Wei, Chiu (David Chiu) Yu-Wei, Chiu (David Chiu)
Author Profile Icon Yu-Wei, Chiu (David Chiu)
Yu-Wei, Chiu (David Chiu)
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Functions in R FREE CHAPTER 2. Data Extracting, Transforming, and Loading 3. Data Preprocessing and Preparation 4. Data Manipulation 5. Visualizing Data with ggplot2 6. Making Interactive Reports 7. Simulation from Probability Distributions 8. Statistical Inference in R 9. Rule and Pattern Mining with R 10. Time Series Mining with R 11. Supervised Machine Learning 12. Unsupervised Machine Learning Index

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:

  1. First, let's review how a named function works:
    >addnum<- function(a,b){
    + a + b
    + }
    >addnum(2,3)
    [1] 5
    
  2. Now, let's perform the same task to sum up two variables with closure:
    > (function(a,b){
    + a + b
    + })(2,3)
    [1] 5
    
  3. We can also invoke a closure function within another function:
    >maxval<- function(a,b){
    + (function(a,b){
    + return(max(a,b))
    + }
    + )(a, b)
    + }
    >maxval(c(1,10,5),c(2,11))
    [1] 11
    
  4. In a similar manner to the apply family function, you can use the vectorization calculation:
    > x <- c(1,10,100)
    > y <- c(2,4,6)
    > z <- c(30,60,90)
    > a <- list(x,y,z)
    >lapply(a, function(e){e[1] * 10})
    [[1]]
    [1] 10
    [[2]]
    [1] 20
    [[3]]
    [1] 300
    
  5. Finally, we can add functions into a list and apply the function to a given vector:
    > x <- c(1,10,100)
    >func<- list(min1 = function(e){min(e)}, 
     max1 = function(e){max(e)} )
    >func$min1(x)
    [1] 1
    >lapply(func, function(f){f(x)})
    $min1
    [1] 1
    $max1
    [1] 100
    

How it works...

In R, you do not have to create a function with the actual name. Instead, you can use closure to integrate methods within objects. Thus, you can create a smaller and simpler function within another object to accomplish complicated tasks.

In our first example, we illustrated how a normally-named function is created. We can simply invoke the function by passing values into the function. On the other hand, we demonstrate how closure works in our second example. In this case, we do not need to assign a name to the function, but we can still pass the value to the anonymous function and obtain the return value.

Next, we demonstrate how to add a closure within a maxval named function. This function simply returns the maximum value of two passed parameters. However, it is possible to use closure within any other function. Moreover, we can use closure as an argument in higher order functions, such as lapply and sapply. Here, we can input an anonymous function as a function argument to return the multiplication of 10 and the first value of any vector within a given list.

Furthermore, we can specify a single function, or we can store functions in a list. Therefore, when we want to apply multiple functions to a given vector, we can pass the function calls as an argument list to the lapply function.

There's more...

Besides using closure within a lapply function, we can also pass a closure to other functions of the apply function family. Here, we demonstrate how we can pass the same closure to the sapply function:

> x <- c(1,10,100)
> y <- c(2,4,6)
> z <- c(30,60,90)
> a <- list(x,y,z)
>sapply(a, function(e){e[1] * 10})
[1] 10 20 300
You have been reading a chapter from
R for Data Science Cookbook (n)
Published in: Jul 2016
Publisher:
ISBN-13: 9781784390815
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime