01
Explain environments and lexical scoping in R.
Show answer
An environment is a collection of name-value bindings with a pointer to a parent environment. R uses lexical scoping: when a function looks up a variable, it searches its own environment, then the environment where it was defined, up through the global environment and attached packages. So a function defined inside another can read the outer function's variables, which enables closures. The <<- operator modifies a binding in a parent environment and should be used sparingly.