Global vs. local assignment operators in R (<<- vs. <-)

You, R
Back

Understanding the difference between local and global assignment operators in R can be tricky to get your head around. Here’s an example which should clear things up.

First, let’s create two variables named “global_var” and “local_var” and give them the values “global” and “local”, respectively. Notice we are using the standard assignment operator <- for both variables.

global_var <- 'global'
local_var <- 'local'
global_var
# RETURNS: 'global'
local_var
# RETURNS: 'local'

Next, let’s create a function to test out the global assignment operator (<<-). Inside this function, we will assign a new value to both of the variables we just created; however, we will use the <- operator for the local_var and the <<- operator for the global_var so that we can observe the difference in behavior.

my_function <- function() {
   global_var <<- 'na'
   local_var <- 'na'
   print(global_var)
   print(local_var)
}
my_function()
# RETURNS:
# 'na'
# 'na'

This function performs how you would expect it to intuitively, right? The interesting part comes next when we print out the values of these variables again.

global_var
# RETURNS: 'na'
local_var
# RETURNS: 'local'

From this result, we can see the difference in behavior caused by the differing assignment operators. When using the <- operator inside the function, it’s scope is limited to just the function that it lives in. On the other hand, the <<- operator has the ability to edit the value of the variable outside of the function as well.

© Trevor French.RSS