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

前端 未结 4 848
我寻月下人不归
我寻月下人不归 2020-12-29 18:31

I know how to use <- and ->, and there are several writeups on the difference between equals assignment & arrow assignment,

4条回答
  •  感动是毒
    2020-12-29 19:03

    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 ->.

提交回复
热议问题