0
0
R Programmingprogramming~5 mins

Variable scope (lexical scoping) in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is lexical scoping in R?
Lexical scoping means that R looks for a variable's value in the environment where the function was defined, not where it is called.
Click to reveal answer
beginner
In R, where does the interpreter look first when resolving a variable inside a function?
It first looks inside the function's own environment (local environment) for the variable.
Click to reveal answer
intermediate
What happens if a variable is not found in the local environment in R?
R looks in the parent environment, continuing up the chain until it finds the variable or reaches the empty environment.
Click to reveal answer
beginner
Explain the difference between local and global variables in R.
Local variables exist only inside a function and are not visible outside. Global variables exist in the global environment and can be accessed anywhere unless shadowed by local variables.
Click to reveal answer
intermediate
What is the output of this R code?<br>
f <- function() { x <- 10; function() x }
<br>Then calling g <- f() and g()?
The output is 10. The inner function remembers the value of x from the environment where it was created (lexical scoping).
Click to reveal answer
In R, if a variable is not found inside a function, where does R look next?
AIn the parent environment
BIn the function's arguments only
CIn the global environment only
DIt throws an error immediately
What does lexical scoping depend on in R?
AWhere the function is called
BWhere the function is defined
CThe order of function arguments
DThe size of the variable
Which environment contains variables defined inside a function in R?
ALocal environment
BGlobal environment
CParent environment
DSystem environment
What will happen if a variable is not found in any environment in R?
AR uses a default value
BR creates the variable automatically
CR returns NULL
DR throws an error
What is a closure in R related to lexical scoping?
AA function without arguments
BA function that runs faster
CA function that remembers its defining environment
DA function that modifies global variables
Explain how R finds the value of a variable inside a function using lexical scoping.
Think about the chain of environments R checks.
You got /5 concepts.
    Describe the difference between local and global variables in R and how lexical scoping affects their visibility.
    Consider where variables are created and accessed.
    You got /4 concepts.