120

I'm using R 2.8.1 and it is possible to use both = and <- as variable assignment operators. What's the difference between them? Which one should I use?

Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
Mehper C. Palavuzlar
  • 9,619
  • 21
  • 55
  • 68

2 Answers2

67

From here:

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.

Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
18

Reading from "Introducing Monte Carlo Methods with R", by Robert and Casella:

"The assignment operator is =, not to be confused with ==, which is the Boolean operator for equality. An older assignment operator is <- and, for compatibility reasons, it still remains functional, but it should be ignored to ensure cleaner programming. (As pointed out by Spector, P. (2009). 'Data Manipulation with R' - Section 8.7., an exception is when using system.time, since = is then used to identify keywords)

A misleading feature of the assignment operator <- is found in Boolean expressions such as

> if (x[1]<-2) ...

which is supposed to test whether or not x[1] is less than -2 but ends up allocating 2 to x[1], erasing its current value! Note also that using

> if (x[1]=-2) ...

mistakenly instead of (x[1]==-2) has the same consequence."

George Dontas
  • 28,739
  • 18
  • 104
  • 145