R Tutorial
Fundamentals of R
Variables
Input and Output
Decision Making
Control Flow
Functions
Strings
Vectors
Lists
Arrays
Matrices
Factors
DataFrames
Object Oriented Programming
Error Handling
File Handling
Packages in R
Data Interfaces
Data Visualization
Statistics
Machine Learning with R
In programming languages, variable scoping determines how the value of a variable is looked up. There are two main scoping rules used across different languages: lexical (or static) scoping and dynamic scoping. R uses lexical scoping, but it's beneficial to understand both to grasp the broader concept.
assign()
with the inherits
option can mimic dynamic scoping behavior.Consider the following pseudo-code:
x = 10 function f() { print(x) } function g() { x = 5 f() } g()
Under Lexical Scoping: The print statement in f()
would show 10
because f
would use the value of x
from the environment where it was defined, which is the global environment.
Under Dynamic Scoping: The print statement in f()
would show 5
because f
would use the value of x
from the environment where it was called, which is inside function g
.
While R uses lexical scoping by default, understanding both lexical and dynamic scoping concepts is valuable. Lexical scoping, as seen in R, offers predictability and modularity. Dynamic scoping, although not native to R, provides flexibility based on the calling environment, but it can make code harder to reason about and debug.
R lexical scoping examples:
Overview: Offer practical examples demonstrating lexical scoping in R.
Code:
# Lexical scoping example outer_function <- function(x) { inner_function <- function(y) { x + y } inner_function } # Create closures with different values of x closure1 <- outer_function(5) closure2 <- outer_function(10) # Call closures with different y values result1 <- closure1(3) # Output: 8 result2 <- closure2(3) # Output: 13