01 / 20

Avoiding
Global State

Learn why global variables create hidden bugs in R analysis scripts and how to write self-contained functions that produce reliable, reproducible results.

R Programming

What Is Global State?

Global state refers to any variable or object that lives in R's global environment: the workspace you see when you type ls(). Every script you source and every line you run in the console writes to this shared space by default.

Global Environment
The top-level workspace where R stores objects created outside any function.
Local Scope
Variables created inside a function: they exist only while the function runs, then disappear.

Why Does It Matter?

When your analysis depends on global variables, three dangerous things happen: results change depending on what ran before, bugs hide in the order of execution, and your code becomes impossible to share reliably.

1
Hidden dependencies: A function silently reads a variable it did not receive as an argument.
2
Order-dependent results: Running chunks in a different sequence yields different outputs.
3
Reproducibility failure: A colleague runs your script on a clean session and gets errors or wrong numbers.

R's Scoping Rules

R uses lexical scoping: when a function cannot find a variable locally, it searches the enclosing environment, then the parent of that environment, all the way up to the global environment and loaded packages.

Global Environment n <- 100 threshold <- 0.05 df <- read.csv(...) my_analysis(data, alpha) data (parameter) alpha (parameter) result (local) lookup if not found locally helper() looks here first, then up

The Core Rule

This is the principle of functional purity. A pure function:

1
Depends only on its inputs: same arguments always produce the same output.
2
Has no side effects: does not modify variables outside its own scope.
3
Is testable in isolation: you can call it without setting up global state first.

Pure vs. Impure Functions

Pure Function data alpha analyze(data, alpha) return(result) ✓ Predictable Impure Function data threshold (global) analyze(data) return(result) modifies global ✕ Unpredictable

<<- vs. <-: Know the Difference

<- (Local Assignment) <<- (Global Assignment)
Scope Current environment only Searches parent environments, writes to global
Side Effects None Modifies external state
Debugging Easy: variable exists only locally Hard: changes visible everywhere
Recommended? ✓ Always ✕ Almost never

How to Eliminate Global State

1
Identify all free variables: Look for names used inside a function that are not defined there or passed as arguments.
2
Add them as parameters: Every free variable becomes an explicit function argument with a sensible default if appropriate.
3
Return, don't assign globally: Replace any <<- with return(). Let the caller decide where to store the result.
4
Test in a clean session: Restart R (Ctrl+Shift+F10 in RStudio) and run your script from top to bottom. If it breaks, you have a hidden dependency.
5
Use codetools::findGlobals(): This built-in tool lists every global reference in a function automatically.

Example 1: Before (Global Dependency)

✕ Impure: reads global variable
# threshold lives in the global environment threshold <- 0.05 flag_significant <- function(p_values) { # 'threshold' is NOT an argument! p_values < threshold } flag_significant(c(0.03, 0.12, 0.001)) # Works... but only because threshold exists globally

Example 1: After (Self-Contained)

✓ Pure: all inputs are explicit
flag_significant <- function(p_values, threshold = 0.05) { p_values < threshold } # Default threshold flag_significant(c(0.03, 0.12, 0.001)) # [1] TRUE FALSE TRUE # Custom threshold: no globals needed flag_significant(c(0.03, 0.12, 0.001), threshold = 0.01) # [1] FALSE FALSE TRUE

Example 2: The <<- Trap

✕ Side effect: modifies global state
results <- list() run_model <- function(formula, data) { model <- lm(formula, data = data) results <<- c(results, list(model)) # ^^^ writes to global 'results' } run_model(y ~ x, df) run_model(y ~ x + z, df)
✓ Fixed: return the result instead
run_model <- function(formula, data) { model <- lm(formula, data = data) return(model) } results <- list( run_model(y ~ x, df), run_model(y ~ x + z, df) )

Example 3: The Pipeline Pattern

Chain pure functions together using the pipe operator. Each function takes input and returns output: no globals touched.

✓ Clean pipeline: no global state
library(dplyr) clean_data <- function(raw_df, min_age = 18) { raw_df |> filter(!is.na(age), age >= min_age) |> mutate(age_group = cut(age, c(18,30,50,100))) } summarize_groups <- function(df) { df |> group_by(age_group) |> summarize(mean_score = mean(score)) } # Compose the pipeline report <- read.csv("survey.csv") |> clean_data(min_age = 21) |> summarize_groups()

Visualizing Data Flow

CSV file read.csv() raw data clean_data() clean data summarize() report min_age = 21 Data flows through arguments only No global variables touched at any step ✓ Reproducible ✓ Testable ✓ Shareable

Common Mistakes

✕ Relying on run order
Running chunks out of order in a notebook and getting different results because a global variable was overwritten.
✕ Using <<- for convenience
Accumulating results into a global list with <<- instead of returning values from functions.
✕ Hardcoding file paths
Embedding absolute paths like "C:/Users/me/data.csv" rather than passing the path as a function argument.

Summary: Global vs. Local

Aspect Global State Local / Pure
Dependencies Hidden: function silently reads globals Explicit: every input is an argument
Reproducibility Fragile: depends on session history Robust: works in any clean session
Testing Hard: must set up globals first Easy: call with arguments, check output
Collaboration Risky: colleagues need your exact setup Safe: self-contained and shareable
Debugging Confusing: side effects ripple everywhere Clear: data flows in one direction

Question 1 of 5

What does R do when a function references a variable that is not defined locally and not passed as an argument?

Question 2 of 5

What happens when scale_values is called the second time?

Question 3 of 5

Which of the following is the best way to fix a function that uses a global variable called alpha?

Question 4 of 5

What does the <<- operator do in R?

Question 5 of 5

You restart R with a clean session and source your analysis script. It fails with "object 'df' not found". What is the most likely cause?