ref.: Hadley

Assignment operators in R

The great debate: <- vs =

ref.: Hadley

Assignment operators in R

The great debate: <- vs =

The operators <- and = can be used, almost interchangeably, to assign to variable in the same environment. Yet, <- is preferred and advised in R Coding style guides from Google and Hadley. Some users pointed out on Twitter that this makes code slightly more difficult to read if you come from another programming language. <- is used in F#, OCaml, R and S to my knowledge. Even if <- is generally rare in programming, I suppose its meaning is quite easy to grasp (it’s an assignment arrow). Nonetheless this led me down a rabbit hole trying to determine the functional differences with these two assignment operators.

This is not just a matter of style and interpretability. There are functional consequences if assignment opperators in R are using incorrectly. R will treat = as a named function argument before it will interpret it as assignment. As an example of where this makes a practical difference:

within(data.frame(a=rnorm(2)), b = a^2) # Error
## Error in eval(substitute(expr), e): argument is missing, with no default
within(data.frame(a=rnorm(2)), b <- a^2) # Success
##            a          b
## 1 -0.5221077 0.27259643
## 2  0.1855074 0.03441299

Or when you want to handle a possible exception:

tryCatch(x = runif(5)) # Error
## Error in tryCatchList(expr, classes, parentenv, handlers): argument "expr" is missing, with no default
tryCatch(x <- runif(5)) # Success

So, if you use = for assignment, you have to remember to treat these situations differently. Which results in your code needing extra levels of brackets/braces, or mixing = and <-. Or you could just use <- everywhere you intend to do assignment and not worry about the edge cases. Keep in mind that this is not to be confused with the other, less common, assignment operators in R (e.g., <<-, ->>, :=, _). I’ll hold off an explanation for a future blog post.

IMO, <- adds some charm to the use of the R programming language. I take pride in it for that reason.

Avatar
Shan Sabri

Using novel high-throughput approaches to understand and engineer the immune system to fight cancer.