← Back to R Course | Chapter 5: Functions | Lesson 5 of 7

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:

  1. Scope
Syntax
r
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

markup
x <- "global value"

show_scope <- function() {
  x <- "local value"
  cat("Inside function:", x, "\n")
}

show_scope()
cat("Outside function:", x, "\n")
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
  1. Expecting x <- "local" inside a function to change the global variable, when it creates a local one.
  2. Using <<- to change globals casually, which makes code hard to follow.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.