What is the difference between <-, << - and - >> in R programming?
I have tried to find the answer through Google and stackoverflow, but still could not get the answer.
What is the difference between <-, << - and - >> in R programming?
I have tried to find the answer through Google and stackoverflow, but still could not get the answer.
<<-
and <-
are both assignment operators, but they are subtly different.
<-
only applies to the local environment where it is used, so if you use it to assign a variable inside a function, that variable will not be available outside that function.
If you use <<-
inside a function to declare a new variable with a name you haven't used anywhere else, it will create that variable in the global environment. If you use it to assign to an existing variable within your function (or any function which contains your function), it will be assigned to the existing variable instead.
It is almost always a bad idea to assign to the global environment from within a function. If you absolutely have to write variables from inside a function, it is better to use assign
to write the variable to another persistent environment.
local_assign <- function() {a <- 1;}
global_assign <- function() {b <<- 1;}
local_assign()
global_assign()
a
# Error: object 'a' not found
b
# [1] 1