R Global Variables

Global variables in R are created outside of any function and can be read from anywhere in your script, including from inside functions.

What Makes a Variable Global

A variable created at the top level of a script — not inside a function — lives in the global environment for the rest of the session. Any function you define afterward can read that variable's value, even though the function never received it as an argument.

Example

company <- "Hyring"

greet <- function() {
  cat("Welcome to", company, "\n")
}

greet()

Functions Get Their Own Local Copies

When a function assigns to a variable with the plain <- operator, it creates a new local variable inside that function's own environment, even if a global variable with the same name already exists. The global variable outside is left untouched.

Example

count <- 1

increment <- function() {
  count <- count + 1
  print(count)
}

increment()
print(count)
Note: In the example above, increment() prints 2, but the global count still prints 1 afterward — the function only ever changed its own local copy.

Changing a Global Variable from Inside a Function

To actually modify a variable in the global environment from inside a function, use the superassignment operator <<- instead of <-. This tells R to look outside the function for an existing variable with that name and update it there.

Example

total <- 0

addToTotal <- function(amount) {
  total <<- total + amount
}

addToTotal(50)
addToTotal(25)
print(total)
OperatorWhere It Assigns
<-Creates or updates a variable in the current (local) scope
<<-Updates a variable in an enclosing or global scope, searching outward until it finds one
Note: Relying heavily on <<- to modify global state from inside functions makes code harder to reason about and debug. Most R style guides recommend having functions return a value instead and reassigning the result explicitly, e.g. total <- addToTotal(total, 50).