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