Site icon R-bloggers

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

[This article was first published on Why? » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:

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

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

If I’m missing something or you disagree, please leave a comment – I would be very interested.

References

To leave a comment for the author, please follow the link and comment on their blog: Why? » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.