Hadley Wickham R Code Style Guide
Object Names
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
Avoid: Using names of existing functions or variables — this causes confusion.
# Bad examples
<- FALSE
T <- 10
c <- function(x) sum(x) mean
Syntax
Spacing
Rule: Place spaces around infix operators (=
, +
, -
, <-
, etc.) and after commas.
No spaces before commas.
Good
<- mean(feet / 12 + inches, na.rm = TRUE) average
Bad
<-mean(feet/12+inches,na.rm=TRUE) average
Exception: :
, ::
, and :::
do not need spaces.
# Good
<- 1:10
x ::get
base
# Bad
<- 1 : 10
x :: get base
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)
5, ]
diamonds[
# Bad
if ( debug ) do(x)
1,]
x[1 ,] x[
Curly Braces
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 {
} ^ x
y
}
# Bad
if (y < 0 && debug)
message("Y is negative")
if (y == 0) {
log(x)
} else {
^ x
y }
Short one-line statements are acceptable:
if (y < 0 && debug) message("Y is negative")
Line Length
Recommendation: Limit lines to 80 characters for readability and printing.
Break long code into functions when possible.
Indentation
Rule: Use two spaces for indentation — no tabs or mixing spaces and tabs.
For multi-line function definitions, align arguments:
<- function(a = "a long argument",
long_function_name b = "another argument",
c = "another long argument") {
# Code is indented by two spaces
}
Assignment
Rule: Use <-
for assignment, not =
.
# Good
<- 5
x
# Bad
= 5 x
Organisation
Commenting Guidelines
Rule: Start comments with #
+ space, explain why not what.
Use separators of -
or =
to create sections.
# Load data ---------------------------
# Plot data ---------------------------