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.
The code given below illustrates this:
# creating a functionmy_function <- function() {# creating a variable using the global assignment operatormy_variable <<- "interesting!"paste("R is", my_variable)}# calling the functionmy_function()# printing the variableprint(my_variable)
my_function
.my_variable
, inside the function we created.my_variable
.my_function
.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.
The code given below illustrates this:
# creating a global variablemy_variable <- "awesome"# creating a functionmy_function <- function() {# using the global assignment operatormy_variable <<- "fantastic"paste("R is", my_variable)}# calling the functionmy_function()# calling the variable outside the functionpaste("R is", my_variable)
my_variable
.my_function
.my_variable
, which we created initially, using the global assignment operator <<-
and change its value to a new value.my_variable
.my_function
.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 <<-
.