Two important assignment operators in R are
<-
and
=
. Lets look at some examples.
This first example assignes 3 to variable x. Notice that a space before and after the assignment operator makes the code more readable.
> x <- 3 > x [1] 3 >
It is also possible to chain assignments
> a<-b<-3 > a [1] 3 > b [1] 3
In this next example we declare a function called mysum.
mysum <- function(a,b){ return (a+b) }
We could also have used “=” for assignment
x = 3 mysum = function(a,b){ return (a+b) }
Difference between = and <-
However, there is a difference between the two operators. = is only allowed at the top level i.e. if the complete expression is written at the prompt. so = is not allowed in control structures. Here’s an example
> if (aa=0) {print ("test")} Error: unexpected '=' in "if (aa=" > aa Error: object 'aa' not found > if (bb<-0) {print ("test")} > bb [1] 0
In the example above we tried to set aa to 0 using the equals operator but that did not work, however setting bb to 0 using <-works. Note that in real life no programmer would really have to assign bb this way, so this example is for demonstration only.
There is another difference too. look at this example. <- opearator makes the variables available in the
current scope.
also note that this is legal
mysum = function(a = 2,b = 3){ return (a+b) }
whereas this does not work
mysum = function(a <- 2,b <- 3){ return (a+b) }
Other operators in R are :
- “->” : This operator is similar to the <- operator, however it assigns the value on the left to the variable on the right.
> 3->a > a [1] 3
- “<<-” and “->>”: This operator assigns the variable to the parent scope. It first looks for the variable in the parent scope and if it can’t find one then it creates a new one in the parent scope. The operator is mainly used inside functions.
> x<-1 > myfun <- function() { + x <<- 3 + y <<- 4 + z <- 5 + return (x+y+z) + } > print(myfun()) [1] 12 > x [1] 3 > y [1] 4 > z Error: object 'z' not found
In Line 1 we assign 1 to x. In the function we assign 3 to x and 4 to y using the <<- operator but assign 5 to z using the <- operator. After function execution x is reassigned a new value and y is assigned a value but z is not.
This was the most simplest explanation of the operator “<<-"
Thank you!