Global variables in R are variables created outside a given function.
A global variable can also be used both inside and outside a function.
Let’s learn to create a global variable outside a function while using this same variable inside the function:
# creating a variablemyGlobalvariable <- "awesome"# creating a function# using the variable inside the functionmy_function <- function() {paste("R is", myGlobalvariable)}# calling the functionmy_function()
my_global_variable
.my_function
.my_global_variable
, inside the my_function
function.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 variablemy_global_variable <- "This is the global variable"# creating a function# creating a local variablemy_function <- function() {my_global_variable <- "This is the local variable"paste("R is", my_global_variable)}# calling the variabe inside the functionmy_function()# calling the variable ouside the functionmy_global_variable
my_global_variable
.my_function
function.my_global_variable
.my_function
.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.