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