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 ...

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.