ruk·si

📊 R
Style Guide

Updated at 2017-10-13 18:35

File names should be meaningful and end in .R. Use underscores instead of spaces.

# bad
foo.r
predict_ad_revenue.r

# good
predict_ad_revenue.R

File structure:

1. File description comment, including purpose of program, inputs, and outputs.
2. source() and library() statements.
3. Function definitions
4. Executed statements, if applicable (e.g., print, plot)

Unit tests go to *_test.R file.

# bad
prediction_tests.R

# good
predict_ad_revenue_test.R

Identifier naming rules:

variableNamesAreInCamelCase
using.dots.is.also.acceptable.in.variables

kConstantsStartWithSmallK

FunctionNamesStartWithCapitalLetter()

Use two space indentation.

# bad
for (i in 1:3) {
    print(i)
}

# good
for (i in 1:3) {
  print(i)
}

Always use <- for assignment, not =.

# bad
x = "Hello World!"

# good
x <- "Hello World!"

Prefer double quotes over single quotes. But use single quotes if the string contains a double quotes.

# bad
x <- 'Hello World!'
y <- "How \"convenient\""

# good
x <- "Hello World!"
y <- 'How "convenient"'

Avoid backtick-variables.

# bad
`x y` <- "Backticks are bad"
print(`x y`)
# [1] "Backticks are bad"

Sources