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.

It is also possible to chain assignments

In this next example we declare a function called mysum.

We could also have used “=” for assignment

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

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

whereas this does not work

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.
  • “<<-” 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.

    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.

One thought on “Assignment Operators in R

  • July 11, 2018 at 1:00 am
    Permalink

    This was the most simplest explanation of the operator “<<-"

    Thank you!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.