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

Scope

In this page:

  1. Scope

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")
🔒

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.