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

Working with lexical scoping

Lexical scoping, also known as static binding, determines how a value binds to a free variable in a function. This is a key feature that originated from the scheme functional programming language, and it makes R different from S. In the following recipe, we will show you how lexical scoping works in R.

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 understand how the scoping rule works:

  1. First, we create an x variable, and we then create a tmpfunc function with x+3 as the return:
    >x<- 5
    >tmpfunc<- function(){
    + x + 3
    + }
    >tmpfunc()
    [1] 8
    
  2. We then create a function named parentfunc with a childfunc nested function and see what returns when we call the parentfunc function:
    >x<- 5
    >parentfunc<- function(){
    + x<- 3
    + childfunc<- function(){
    + x
    + }
    + childfunc()
    + }
    >parentfunc()
    [1] 3
    
  3. Next, we create an x string, and then we create a localassign function to modify x within the function:
    > x <- 'string'
    >localassign<- function(x){
    + x <- 5
    + x
    + }
    >localassign(x)
    [1] 5
    >x
    [1] "string"
    
  4. We can also create another globalassign function but reassign the x variable to 5 using the <<- notation:
    > x <- 'string'
    >gobalassign<- function(x){
    + x <<- 5
    + x
    + }
    >gobalassign(x)
    [1] 5
    >x
    [1] 5
    

How it works...

There are two different types of variable binding methods: one is lexical binding, and the other is dynamic binding. Lexical binding is also called static binding in which every binding scope manages variable names and values in the lexical environment. That is, if a variable is lexically bound, it will search the binding of the nearest lexical environment. In contrast to this, dynamic binding keeps all variables and values in the global state. That is, if a variable is dynamically bound, it will bind to the most recently created variable.

To demonstrate how lexical binding works, we first create an x variable and assign 5 to x in the global environment. Then, we can create a function named tmpfunc. The function outputs x + 3 as the return value. Even though we do not assign any value to x within the tmpfunc function, x can still find the value of x as 5 in the global environment.

Next, we create another function named parentfunc. In this function, we assign x to 3 and create a childfunc nested function (a function defined within a function). At the bottom of the parentfunc body, we invoke childfunc as the function return. Here, we find that the function uses the x defined in parentfunc instead of the one defined outside parentfunc. This is because R searches the global environment for a matched symbol name, and then subsequently searches the namespace of packages on the search list.

Moving on, let's take a look at what will return if we create an x variable as a string in the global state and assign an x local variable to 5 within the function. When we invoke the localassign function, we discover that the function returns 5 instead of the string value. On the other hand, if we print out the value of x, we still see string in return. While the local variable and global variable have the same name, the assignment of the function does not alter the value of x in global state. If you need to revise the value of x in the global state, you can use the <<- notation instead.

There's more...

In order to examine the search list (or path) of R, you can type search() to list the search list:

>search()
[1] ".GlobalEnv""tools:rstudio"
[3] "package:stats" "package:graphics"
[5] "package:grDevices" "package:utils"
[7] "package:datasets" "package:methods"
[9] "Autoloads" "package:base"
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