📖

R Style Guide

Best practices for readable, sharable, and verifiable R code

R is a high-level programming language used primarily for statistical computing and graphics. R does not have any well defined coding recommendations or de facto standards. This style guide provides some recommendations based on personal experience and expert opinions (see Additional Guides). Use your best judgement and common sense when deciding whether to adhere to these recommendations. Be consistent. Use style to enhance legibility. Ultimately, a unified style will help make collaboration and sharing code easier.

Table of contents

Naming Conventions

File Names

# Good
getData.R

# Acceptable
get_data.R
	
# Bad
foo.bar.r
89317240934735.r

Identifiers

# Good
pcaEmbedding  # variable
getPcaEmbedding <- function()  # function

# Acceptable
pca.embedding
getEmb <- function() 

# Bad
pca_embedding
get_pca_embedding <- function()
get.pca.embedding <- function() 

# Really bad
pe
gpe <- function()
foo-bar <- function()

Syntax

General Syntax

# Good 
x <- 23
y <- 12

# Bad
x = 23; y = 12
23 -> x

Spacing

# Good
someFunction <- function(a, b, c, d = 100) {
    if (a < d) {
        a <- (b + c) * d
    }
}

# Bad
someFunction <- function(a,b,c,d= 100) { 
  if(a<d) a<-(b+c)*d 
}

Curly Braces

# Good
if (a < d) {
    a <- (b + c) * d
} else {
    a <- d
}

# Bad
if (a < d) 
{
    a <- (b + c) * d
} else a <- d

Line Length

# Good
someFunction(optionA = alpha,
             optionB = bravo,
             optionC = charlie,    
             optionD = delta)

# Acceptable
someFunction(optionA = alpha,
    optionB = bravo, optionC = charlie,    
    optionD = delta)

# Bad
someFunction(optionA = alpha, optionB = bravo, optionC = charlie, optionD = delta)

Organization

Commenting

#' Add together two numbers.
#' 
#' @param x A number.
#' @param y A number.
#'
#' @return The sum of x and y.
#'
#' @examples
#' add(1, 1)
#' add(10, 1)
#'
add <- function(x, y) {
    # general comment
    x + y  # inline comment
}


#' Next function

Additional Tips

Loops

# Good
lapply(seq(along = x), function(i) {
    doSomething(i)
})

# Acceptable
for (i in seq(along = x)) {
    doSomething(i)
}

# Bad
for (i in 1:length(x)) {
    doSomething(i)
}

Repeat

# Good
repeat {
    ...
}

# Bad
while (TRUE) {
    ...
}

References and Resources

Additional Guides

  • The tidyverse style guide by Hadley Wickham
  • (an older) R Style Guide by Hadley Wickham
  • Google's R Style Guide
  • R Coding Conventions by Henrik Bengtsson
  • Bioconductor Coding Style
  • Inspiration

  • Code Guide by mdo