Thursday, April 19, 2012

The 5 assignment operators of "R"





In every programming language I've used, '=' is the assignment operator, but in R you can assign 1 to x in the 5 different ways listed below.  I'm sharing this with you because it reminded me how many ways there are to skin a cat, and how each of those choices has tradeoffs.



[A] x = 1

[B] x <-1

[C] 1 -> x

[D] x <<- 1

[E] 1 ->> x





[A] x = 1

'=' is supported in R, but rarely used.  Google Style Guide says don't use it. And I've never seen R code that does.



[B] x <-1

'<-' Is the most commonly used, so you'll almost always see x<-1.  Some R people claim x<-1 is a superior assignment operator since the '=' assignment  operator (x=1) can be confused with the equality operator (x==1).     It strikes me the '<-' assignment operator can be confusing as well.  When using negative integers a single space can really change the meaning aka: x<-1 vs x < -1. Trade offs are everywhere!



[C] 1 -> x

Assignment arrows work in both directions in the human mind, and they do in R too.



[D] x <<- 1



 '<<-'.  Assign not to x in local scope, but the x that is in the first parent scope.  To do this in a C family language you'd have to specify you wanted the x in the parent scope e.g:  ::x = 1. Notice the difference in R is that the operator changes the meaning of the variable passed to it. This is very strange in other languages.



[E] 1 ->> x

Assignment arrows work in both directions in the human mind, and they do in R too.





No comments:

Post a Comment