33

I was wondering if there is a technical difference between the assignment operators "=" and "<-" in R. So, does it make any difference if I use:

Example 1: a = 1 or a <- 1

Example 2: a = c(1:20) or a <- c(1:20)

Thanks for your help

Sven

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
R_User
  • 10,682
  • 25
  • 79
  • 120

1 Answers1

44

Yes there is. This is what the help page of '=' says:

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

With "can be used" the help file means assigning an object here. In a function call you can't assign an object with = because = means assigning arguments there.

Basically, if you use <- then you assign a variable that you will be able to use in your current environment. For example, consider:

matrix(1,nrow=2)

This just makes a 2 row matrix. Now consider:

matrix(1,nrow<-2)

This also gives you a two row matrix, but now we also have an object called nrow which evaluates to 2! What happened is that in the second use we didn't assign the argument nrow 2, we assigned an object nrow 2 and send that to the second argument of matrix, which happens to be nrow.

Edit:

As for the edited questions. Both are the same. The use of = or <- can cause a lot of discussion as to which one is best. Many style guides advocate <- and I agree with that, but do keep spaces around <- assignments or they can become quite hard to interpret. If you don't use spaces (you should, except on twitter), I prefer =, and never use ->!

But really it doesn't matter what you use as long as you are consistent in your choice. Using = on one line and <- on the next results in very ugly code.

Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • 4
    This answer is wrong (and unfortunately the documentation is wrong too). As explained elsewhere, the only difference between the operators is their precedence. But, contrary to what this answer says, both `=` and `<-` assignment are evaluated in the same environment, and it is categorically wrong to say that `=` can only be used at the top level. – Konrad Rudolph Aug 16 '19 at 13:40
  • 2
    Also, in your example, I guess `matrix(1,nrow=2)` requires that there is an argument called `nrow`, and it doesn't matter at which possition you put `nrow=2` since it is a keyword argument, while if you instead write `nrow<-2` it does matter at which position you put it, because not it's all of a sudden a positional argument and not a keyword argument? If so, I guess it would also be pretty easy to misinterpret the expression `nrow<-2` as a keyword argument and not a positional argument, and hence that expression should perhaps be avoided inside function calls? – HelloGoodbye Sep 18 '19 at 20:09