The Wayback Machine - https://web.archive.org/web/20240713034410/https://www.geeksforgeeks.org/lexical-scoping-in-r-programming/
Open In App

Lexical Scoping in R Programming

Last Updated : 28 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Lexical Scoping in R programming means that the values of the free variables are searched for in the environment in which the function was defined. An environment is a collection of symbols, value, and pair, every environment has a parent environment it is possible for an environment to have multiple children but the only environment without the parent is the empty environment. If the value of the symbol is not found in the environment in which the function was defined then the search is continued in the parent environment. In R, the free variable bindings are resolve by first looking in the environment in which the function was created. This is called Lexical Scoping.

Why Lexical Scoping?

Lexical Scoping is a set of rules that helps to determine how R represents the value of a symbol. It is an in-built rule in R which automatically works at the language level. It is mostly used to specify statistical calculations. Lexical scoping looks up to symbol based on how functions were nested initially when they were created and not on how they were nested when they called upon. When we use lexical scoping we don’t have to know how the function is called and to figure out where the value of the variable will be looked upon. We only have to look at the function’s definition.

Lexical meaning in lexical scoping is completely different from usual English definition which means relating to words or vocabulary of a language which is distinguished from grammar and construction rather it comes from computer science term lexing meaning by which process that converts code represented as text to meaningful pieces which is comprehensible by programming language. Consider the following example:




f <- function(x, y)
{
  x * y * z
}


In this:

  • x and y are formal arguments
  • z as the free variable

Therefore, the scoping rules of the language determine how values are assigned to free variables. Free variables are not formal arguments and not local variables that are assigned inside of the function body.

Principles of Lexical Scoping

There are four basic principles behind R’s implementation of lexical scoping:

  1. Name Masking
  2. Functions vs variables
  3. A fresh start
  4. Dynamic Lookup

Let’s discuss each principle one by one.

Name Masking

The following example illustrates the most basic principle of lexical scoping, and you should have no problem predicting the output.

  • If variable is not defined inside the function:
    Example:




    c <- 10
    f <- function(a, b)
    {
      a + b + c
    }
    f(8, 5) 

    
    

    Output:

    [1] 23
    

    It takes the c value as 10 and then adds these numbers and finally we are having 23 as output.

  • If name is not defined inside the function:
    If a name isn’t defined inside a function, R will look one level up.
    Example:




    a <- 10
    b <- function()
    {
      c <- 11
      c(a, c)
    }
    b() 

    
    

    Output:

    [1] 10 11
    
  • When one function is defined inside another function:
    The same rules apply if a function is defined inside another function: look inside the current function, then where that function was defined, and so on, all the way up to the global environment, and then on to other loaded packages.
    Example:




    a <- 10
    g <- function(){
      b <- 20
      h <- function(){
        c <- 30
        c(a, b, c) 
      }
      h()
    }
    g()

    
    

    Output:

    [1] 10 20 30
    
  • When functions are created by another function:
    The same rules apply to closures, functions created by other functions.
    Example:




    a <- function(z){
      b <- 10
      function(){
        z + 4 * b
      }
    }
    x <- a(10)
    x() 

    
    

    Output:

    [1] 50
    

    R returns the accurate value of b after calling the function because x preserves the environment in which it was defined. The environment includes the value of b.

Functions vs Variables

The same principles apply regardless of the type of associated value — finding functions works exactly the same way as finding variables:
Example:




a <- function(x) 10 * x
b <- function(){
  a <- function(x) x + 10
  a(12)
}
b() 


Output:

[1] 22

A Fresh Start

When a function is called, a new environment is created every time. Each acknowledgement is completely independent because a function cannot tell what happened when it was run last time.
Example:




a <- function(){
  if(!exists("z"))
  {
    z <- 10
  }
  else
  {
    z <- z+10
  }
  z
}
a()


Output:

[1] 10

Dynamic Lookup

Lexical scoping controls where to look for values not when to look for them. R looks for the values when the function is executed not when it is created. The output of the function can be different depending on objects outside its environment.
Example:




g <- function() x^3
x <- 10
g() 


Output:

[1] 1000

There is a function in R which is findGlobals() from codetools and it helps us to find all global variables being used in a function and lists all the external dependencies of a function. findGlobals() find the global variables and functions which are used by the closure.
Example:




aGlobal <- rnorm(10)
bGlobal <- rnorm(10)
  
f <- function()
{ 
  a <- aGlobal
  b <- bGlobal
  plot(b ~ a)
}
codetools::findGlobals(f) 


Output:

[1] "{"       "~"       "<-"      "aGlobal" "bGlobal" "plot"

We can manually change the environment to the empty environment emptyenv(). emptyenv() is a totally empty environment.



Previous Article
Next Article

Similar Reads

Lexical Scoping vs Dynamic Scoping in R Programming
R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool. Scoping Rules of a language are responsible fo
4 min read
Dynamic Scoping in R Programming
R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool. The scoping rules for R are the main feature t
5 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x &lt;- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u &lt;- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N &lt;- 20 # Calling rf() Function y &lt;- rf(N, df1
1 min read
Article Tags :
three90RightbarBannerImg