What are global variables in R?

Overview

Global variables in R are variables created outside a given function.

A global variable can also be used both inside and outside a function.

Code example

Let’s learn to create a global variable outside a function while using this same variable inside the function:

# creating a variable
myGlobalvariable <- "awesome"
# creating a function
# using the variable inside the function
my_function <- function() {
paste("R is", myGlobalvariable)
}
# calling the function
my_function()

Code explanation

  • Line 2: We create a variable my_global_variable.
  • Line 5: We create a function my_function.
  • Line 6: We use the global variable, my_global_variable, inside the my_function function.
  • Line 11: We call the my_function function.

When a variable is created with the same name as a global variable inside a given function, it is called the local variable. This variable can only be used inside the given function. The global variable will now have the same original value whenever it is printed outside the function. However, the local variable with the same name will print its value only when printed inside the function.

The code example below explains it all:

# creating a global variable
my_global_variable <- "This is the global variable"
# creating a function
# creating a local variable
my_function <- function() {
my_global_variable <- "This is the local variable"
paste("R is", my_global_variable)
}
# calling the variabe inside the function
my_function()
# calling the variable ouside the function
my_global_variable

Code explanation

  • Line 2: We create a global variable variable called my_global_variable.
  • Line 6: We create the my_function function.
  • Line 7: We create a local variable with the same name as my_global_variable.
  • Line 12: We call my_function.
  • Line 13: We call the my_global_variable outside the function.

When you print my_global_variable, it will return "This is the global variable" because we are printing it outside the function.

Free Resources