R Language: Scoping Rules of R

0

Scoping rules in R determine how the values of variables are assigned in a function. There are two types of variables in R: local variables and free variables.

  • Local variables are variables that are defined within the body of a function. The values of local variables are only accessible within the function in which they are defined.
  • Free variables are variables that are not defined within the body of a function, but are used within the function. The values of free variables are searched for in the environment in which the function was defined.

R uses lexical scoping, which means that the values of free variables are searched for in the environment in which the function was defined, not in the environment in which the function is called. This means that the values of free variables can be changed by other functions that are defined in the same environment.

Here is an example of lexical scoping in R:

my_function <- function(x) {

  y <- 10

  z <- x + y

  return(z)

}


x <- 5

z <- my_function(x)


print(z)

In this example, the variable `x` is a local variable in the function `my_function()`. The variable `y` is a free variable in the function `my_function()`. The value of `y` is searched for in the environment in which `my_function()` was defined, which is the global environment. The value of `y` in the global environment is 10, so the value of `z` is 15.

Post a Comment

0Comments
Post a Comment (0)