This is an issue that's perplexed me and my students for years now, and I realise now that others have been asking the same question. My stock response for recommending <-
assignment (e.g. in my Introduction to Visualising Spatial Data in R) has been that "that's what R developers use and we trust them".
But when Yihui Xie, an eminent R developer, advocates =
, I'm no longer sure.
Is that a sufficient reason? The best reason I've seen so far for favouring <-
is that "mathematicians would be confused by x = x + 1
, but not x <- x + 1
". Fair enough but most mathematicians I know can also understand programs that use =
for assignment. (Reference: comments under here http://alyssafrazee.com/introducing-R.html )
The other reason is that =
is used for arguments in functions, so <-
should be used in function calls. But what are the precise contexts in which =
will fail? And is there not an advantage of reserving <-
/->
for situations where it's really needed, such as:
In a function:
system.time(x <- rnorm(10e6))
system.time(x = rnorm(10e6)) # error
system.time({x = rnorm(10e6)}) # no error
Right hand assignment:
library("dplyr")
data_frame(x = 1:26, y = letters) %>%
filter(x %% 3 == 0) %>%
top_n(n = 3, wt = x) -> df
df