views:

430

answers:

4

What are differences in the assignment operators '=' and '<-' in R? I know that operators are slightly different as this example shows

> x <- y <- 5
> x = y = 5
> x = y <- 5
> x <- y = 5
Error in (x <- y) = 5 : could not find function "<-<-"

But is this the only difference?

+3  A: 

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.

Haim Evgi
+11  A: 

The difference is clearer when you use them inside a function. For example:

median(x = 1:10)
x        # Error: object 'x' not found

In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

median(x <- 1:10)
x        # [1]  1  2  3  4  5  6  7  8  9 10

In this case, x is declared in the user workspace, so you can use it after the function call has been completed.

There is a general preference among the R community for using ' <- ' for assignment (other than in function signatures) for compatibility with S-Plus. Note that the spaces help to clarify situations like

x<-3
# Does this mean assignment?
x <- 3
# Or less than?
x < -3
Richie Cotton
+6  A: 

Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.

http://google-styleguide.googlecode.com/svn/trunk/google-r-style.html#assignment

The R manual goes into nice detail on all 5 assignment operators.

http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

Nosredna
A: 

also if you want your code to be compatible with S & S-Plus use "<-"

tracius01