On R Code Style

Master R

By Guangming Lang Comment

I didn’t pay much attention to code style until recently when I had to collaborate with a couple of guys on a project. That experience taught me having a consistent style across all team members can greatly reduce communication time and help people understand each other’s code. If you’re not already using a style, you should decide on a style today. Even if you program solo, you will also benefit from sticking to a style. It will allow you to write code faster, for example, once you choose a style, you don’t have to spend time deciding whether you should use all lowercase letters chained by dots or undersores or use camelCase everytime you write a variable name. It will also make your code easier to read.

The best way of choosing a style is to adopt from the existing ones. Here’s an excellent style guide by Hadley. We decided our style based on it with a few modifications. For example, we use = instead of <- since we don’t see any practical harm of using = over <-1 and it’s a bit harder to type <- than =2. At the moment, I’m only aware of one occasion where <- and = are not interchangeable, and it’s when used in the substitute() function.

# <- works
substitute(x <- x + 1, list(x = 1))
## 1 <- 1 + 1
# but = runs into error
substitute(x = x + 1, list(x = 1))
## Error in substitute(x = x + 1, list(x = 1)): unused argument (x = x + 1)
  1. see this stackoverflow thread 

  2. Yihui Xie (the author of the famous package knitr) and Alyssa Frazee also prefer = over <-

If you enjoyed this post, get updates. It's FREE