Global vs Local Scope
Distinguish between .GlobalEnv, function environments, and closures.
Local Variables in Functions
Variables assigned with <- or = inside a function body are local to that function. They are created in the function's own environment and disappear when the function returns. They never affect the calling scope.
x <- 'global'
f <- function() {
x <- 'local' # creates a new local binding, does not modify global x
cat('Inside f: x =', x, '\n')
}
f()
cat('Outside f: x =', x, '\n') # still 'global'Function Parameters are Local
Function parameters are also local variables. Modifying a parameter inside the function does not affect the argument in the calling environment. R passes arguments by value (with copy-on-modify semantics).
double_it <- function(n) {
n <- n * 2 # modifies local copy only
cat('Inside:', n, '\n')
}
my_n <- 5
double_it(my_n)
cat('Outside:', my_n, '\n') # still 5