Coding best practices: Style matters

Matters of Style

First, some motivation. Here are two equivalent blocks of code:

Which you would have recognized written like this:

One is pretty easy to read, the other is horrendous. The two style guides you should use in your R code are:

Use meaningful and consistent names

  • Dots: variable.name (Google preferred)
  • Camel case: variableName (Google accepted)
  • Capitalized: VariableName (Google accepted)
  • Underscore: variable_name (Tidyverse)

In choosing names, be sure that the names you choose have meaning.

Bad:

Good:

Use white space!

R doesn’t care about spaces or newlines in your code. Use this to write beautiful code!

Compare:

To:

Note the use of:

  • Named arguments when you’ve got more than 2 - 3 arguments
  • White space around all operators (“=”, “>”, etc.)
  • New lines to enhance readability; keep each line < 80 characters
  • White space to line up “=”

Assignment opperator holy wars