Hadley Wickham R Code Style Guide

Object Names

Tip

Rule: Use lowercase with underscores for variable and function names.
Variables = nouns, Functions = verbs.

Good

day_one
day_1

Bad

first_day_of_the_month
DayOne
dayone
djm1
Warning

Avoid: Using names of existing functions or variables — this causes confusion.

# Bad examples
T <- FALSE
c <- 10
mean <- function(x) sum(x)

Syntax

Spacing

Tip

Rule: Place spaces around infix operators (=, +, -, <-, etc.) and after commas.
No spaces before commas.

Good

average <- mean(feet / 12 + inches, na.rm = TRUE)

Bad

average<-mean(feet/12+inches,na.rm=TRUE)

Exception: :, ::, and ::: do not need spaces.

# Good
x <- 1:10
base::get

# Bad
x <- 1 : 10
base :: get

Place a space before left parentheses, except in function calls.

# Good
if (debug) do(x)
plot(x, y)

# Bad
if(debug)do(x)
plot (x, y)

Extra spacing for alignment is fine:

list(
  total = a + b + c, 
  mean  = (a + b + c) / n
)

No spaces inside parentheses or square brackets unless there’s a comma.

# Good
if (debug) do(x)
diamonds[5, ]

# Bad
if ( debug ) do(x)
x[1,]
x[1 ,]

Curly Braces

Tip

Rule: Opening brace never on its own line. Closing brace on its own line unless followed by else.
Always indent code inside braces.

# Good
if (y < 0 && debug) {
  message("Y is negative")
}

if (y == 0) {
  log(x)
} else {
  y ^ x
}

# Bad
if (y < 0 && debug)
message("Y is negative")

if (y == 0) {
  log(x)
} 
else {
  y ^ x
}

Short one-line statements are acceptable:

if (y < 0 && debug) message("Y is negative")

Line Length

Note

Recommendation: Limit lines to 80 characters for readability and printing.
Break long code into functions when possible.


Indentation

Tip

Rule: Use two spaces for indentation — no tabs or mixing spaces and tabs.

For multi-line function definitions, align arguments:

long_function_name <- function(a = "a long argument", 
                               b = "another argument",
                               c = "another long argument") {
  # Code is indented by two spaces
}

Assignment

Tip

Rule: Use <- for assignment, not =.

# Good
x <- 5

# Bad
x = 5

Organisation

Commenting Guidelines

Tip

Rule: Start comments with # + space, explain why not what.
Use separators of - or = to create sections.

# Load data ---------------------------

# Plot data ---------------------------