Tuesday, October 12, 2010

Why I hate programming (part 2 of n)

The difference between using "=" and "<-" for assignment in R:

It seems that, historically, "=" was not allowed for variable assignment. My understanding is that in modern R, using "=" for assignment is (mostly) equivalent to using "<-", so that:

x = 2 % This line is the same as
x <- 2 % this line.

However, one should be aware that when using "=" to give parameters for functions, assignments do not occur (in the global workspace):

x <- rep(2, times=5) % "times" does not have value 5
times % gives an error
x <- rep(2, times<-5) % "times" IS set to have value 5
times % this will have value 5

There's also some weird differences with how "<-" and "=" get interpreted (maybe has to do with order of operations / syntactic sugar?):

x = y = 5 % both "x" and "y" will have value 5
x <- y <- 5 % both "x" and "y" will have value 5
x = y <- 5 % both "x" and "y" will have value 5
x <- y = 5 % gives an error

This is what R's documentation has to say about this nonsense:
"The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions."

Labels: ,


Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home