📖

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
get_data.R

# Bad
foo.bar.r
89317240934735.r

Identifiers

# Good
variableName
functionName <- function()

# Acceptable
variable.name
FunctionName <- function() 

# Bad
variable_name
function_name <- function()
function.name <- 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

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
}

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

  • R Style Guide by Hadley Wickham
  • Google R Style Guide
  • R Coding Conventions by Henrik Bengtsson
  • The Comprehensive R Archive Network
  • Bioconductor Coding Style
  • Inspiration

  • Code Guide by mdo