0
0
R Programmingprogramming~5 mins

Variable scope (lexical scoping) in R Programming

Choose your learning style9 modes available
Introduction

Variable scope tells us where a variable can be used in a program. Lexical scoping means R looks for a variable inside the place where the code is written, not where it is run.

When you want to use a variable inside a function without changing the global variable.
When you want to create small pieces of code that use variables only inside them.
When you want to avoid mistakes by keeping variables separate in different parts of your program.
Syntax
R Programming
variable_name <- value

my_function <- function() {
  local_variable <- value
  # use local_variable here
}

Variables created inside a function are local to that function.

If a variable is not found inside the function, R looks outside in the environment where the function was created.

Examples
The function uses the variable x from outside because of lexical scoping.
R Programming
x <- 10

my_func <- function() {
  print(x)  # prints 10
}

my_func()
The x inside the function is local and does not change the outside x.
R Programming
x <- 5

my_func <- function() {
  x <- 20
  print(x)  # prints 20
}

my_func()
print(x)  # prints 5
Sample Program

This program shows how inner_func finds variables x and y using lexical scoping.

R Programming
x <- 100

outer_func <- function() {
  y <- 10
  inner_func <- function() {
    print(x)  # looks outside both functions
    print(y)  # looks in outer_func
  }
  inner_func()
}

outer_func()
OutputSuccess
Important Notes

Lexical scoping helps keep code organized and avoids accidental changes to variables.

Remember, R looks for variables starting inside the function, then outside where the function was made.

Summary

Lexical scoping means variables are found where the code is written, not where it runs.

Variables inside functions are local and separate from outside variables.

This helps prevent mistakes and keeps code clean.