What is the global assignment operator in R?

Overview

In R, the global assignment operator (<<-) creates a global variable inside a function.

Note: We can also create a global variable outside of a function. The <<- operator helps us make a variable that belongs to the global scope even when defined in a function.

Code

The code given below illustrates this:

# creating a function
my_function <- function() {
# creating a variable using the global assignment operator
my_variable <<- "interesting!"
paste("R is", my_variable)
}
# calling the function
my_function()
# printing the variable
print(my_variable)

Explanation

  • Line 2: We create a function called my_function.
  • Line 5: We create a global variable, called my_variable, inside the function we created.
  • Line 6: We display the value of variable the my_variable.
  • Line 10: We call the function my_function.
  • Line 13: We print the global variable my_variable outside the function.

We can create a global variable within a function, using the global assignment operator <<-.

Note: Interestingly, we can refer to a variable and change the value of the variable that we created inside a function, by using the global assignment operator.

Code

The code given below illustrates this:

# creating a global variable
my_variable <- "awesome"
# creating a function
my_function <- function() {
# using the global assignment operator
my_variable <<- "fantastic"
paste("R is", my_variable)
}
# calling the function
my_function()
# calling the variable outside the function
paste("R is", my_variable)

Explanation

  • Line 2: We create a global variable called my_variable.
  • Line 5: We create a function called my_function.
  • Line 8: We refer to the global variable my_variable, which we created initially, using the global assignment operator <<- and change its value to a new value.
  • Line 9: We return the global variable my_variable.
  • Line 13: We call the function my_function.
  • Line 15: We print the global variable my_variable.

We changed the value of a global variable from my_variable = awesome to my_variable = fantastic by referring to the global variable inside of a function, using the global assignment operator <<-.