Assignment Operators in R

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
> 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 :

• “-&gt” : 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