Why are there two assignment operators, `<-` and `->`?

  • A+

I know how to use <- and ->, and there are good writeups on the difference between equals assignment & arrow assignment, but I don't know when to prefer -> over <-.

It seems the community has coalesced around using <- for assignment.

Neither the google R style-guide, nor Hadley Wickam's tidyverse R style-guide even mention -> in the assignment section.

I'm curious about the design considerations that led the S/S-PLUS developers to put in the right arrow assign operator ->. In what setting(s) would using -> be considered more readable (or easier to type) versus <- or =?

I'm not familiar with any other language that allows the right-assignment semantics. What languages inspired R in this regard?


I think it is just a matter of personal preference.

Although -> predated magrittr pipes, one recent use case is that -> can be used to keep the flow from left to right in such pipes:

library(magrittr) input %>% fun1 %>% fun2 -> result 

On the other hand, given that <- is mostly used you might want to use <- even in that case.

The argument for <- is that it starts the line off with the value being set which is sort of like the purpose of the statement, particularly if the result variable is well named, whereas the right hand side is the mechanics and so is detail subservient to the result -- and one likes to start off with an overview and then only get into the detail later. Below we are defining parameter k. That it is 3 or whether it is defined by a constant as it is here or a complex expression seems incidental to the purpose of the statement.

k <- 3 

Personally, I never use ->.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: