Scope
In this page:
Scope
Variables created inside a function are local to that function's execution and disappear once it returns, without affecting variables of the same name outside. R uses lexical scoping, meaning a function can read variables from its enclosing environment, but assignments inside the function create new local variables by default rather than modifying the outer one. The <<- operator can explicitly modify a variable in an enclosing scope, though it's used sparingly.
Warning: Assigning to a variable inside a function with <- creates a new local variable -- it does not modify a same-named variable outside the function.
Example: Scope
x <- "global value"
show_scope <- function() {
x <- "local value"
cat("Inside function:", x, "\n")
}
show_scope()
cat("Outside function:", x, "\n")
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: