# Assignment operators in R: ‘=’ vs. ‘<-’

November 16, 2010
By

(This article was first published on Why? » R, and kindly contributed to R-bloggers)

In R, you can use  both ‘=’ and ‘<-’ as assignment operators. So what’s the difference between them and which one should you use?

### What’s the difference?

The main difference between the two assignment operators is scope. It’s easiest to see the difference with an example:
 ##Delete x (if it exists) > rm(x) > mean(x=1:10) #[1] 5.5 > x #Error: object 'x' not found 
Here x is declared within the function’s scope of the function, so it doesn’t exist in the user workspace. Now, let’s run the same piece of code with using the <- operator:
 > mean(x <- 1:10)# [1] 5.5 > x # [1] 1 2 3 4 5 6 7 8 9 10 
This time the x variable is declared within the user workspace.

### Which one should I use

Well there’s quite a strong following for the “<-” operator:

• The Google R style guide prohibits the use of “=” for assignment.
• Hadley Wickham’s style guide recommends “<-”
• If you want your code to be compatible with S-plus you should use “<-”
• I believe that the General R community recommend using “<-”, but I can’t find anything on the mailing list.

However, I tend always use the “=” operator for the following reasons:

• The other languages I program in (python, C and occasionally JavaScript) use the “=” operator.
• It’s quicker to type “=” and “<-”.
• Typically, when I type declare a variable – I only want it to exist in the current workspace.
• Since I have the pleasure of teaching undergraduates their first course in programming, using “=” avoids misleading expressions like if (x[1]<-2) 

Also Introducing Monte Carlo Methods with R, by Robert and Casella recommends using “=”.

###### References

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...