Scope
Scope is about where a name can be seen, like toys that belong to one room. A variable made inside a function stays inside it and does not leak out.
In this page:
Syntax
x <- global_value
function_name <- function() {
x <- local_value # local to the function
x
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting
x <- "local"inside a function to change the global variable, when it creates a local one. - Using
<<-to change globals casually, which makes code hard to follow. - Using a variable defined inside a function after it has returned, which gives
object not found.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: