“There are only two hard things in Computer Science: cache invalidation and naming things.”
— Phil Karlton
In contrast to the tidyverse/style guide, in the Gaiti Lab we follow Google’s current R style guide when it comes to naming conventions.
Function names should be BigCamelCase to clearly distinguish them from other objects, i.e. every word’s first letter is capitalized.
Variable names (this includes named arguments in functions) should be camelCase, i.e. “first letter of each word is capitalized, except for the first letter of the entire compound word, which may be either upper or lower case” (ref).
Base R uses dots in function names (contrib.url()) and class names (data.frame), but it’s better to reserve dots exclusively for the S3 object system. In S3, methods are given the name function.class; if you also use . in function and class names, you end up with confusing methods like as.data.frame.data.frame().
If you find yourself attempting to cram data into variable names (e.g. model_2018, model_2019, model_2020), consider using a list or data frame instead.
Generally, variable names should be nouns and function names should be verbs. Strive for names that are concise and meaningful (this is not easy!).
Show the code
# GooddayOne# BadfirstDayOfTheMonthdjm1
Where possible, avoid re-using names of common functions and variables. This will cause confusion for the readers of your code.
Show the code
# BadT <-FALSEc <-10mean <-function(x) sum(x)
4.2 Spacing
4.2.1 Commas
Always put a space after a comma, never before, just like in regular English.
Show the code
# Goodx[, 1]# Badx[,1]x[ ,1]x[ , 1]
4.2.2 Parentheses
Do not put spaces inside or outside parentheses for regular function calls.
The embracing operator, { }, should always have inner spaces to help emphasise its special behaviour:
Show the code
# GoodMaxBy <-function(data, var, by) { data |>group_by({{ by }}) |>summarise(maximum =max({{ var }}, na.rm =TRUE))}# BadMaxBy <-function(data, var, by) { data |>group_by({{by}}) |>summarise(maximum =max({{var}}, na.rm =TRUE))}
4.2.4 Infix operators
Most infix operators (==, +, -, <-, etc.) should always be surrounded by spaces:
# Goodpackage?stats?mean# Badpackage ? stats? mean
4.2.5 Extra spaces
Adding extra spaces is ok if it improves alignment of = or <-.
Show the code
# Goodlist(total = a + b + c,mean = (a + b + c) / n)# Also finelist(total = a + b + c,mean = (a + b + c) / n)
Do not add extra spaces to places where space is not usually allowed.
4.3 Vertical space
Use vertical whitespace sparingly, and primarily to separate your “thoughts” in code, much like paragraph breaks in prose.
Avoid empty lines at the start or end of functions.
Only use a single empty line when needed to separate functions or pipes.
It often makes sense to put an empty line before a comment block, to help visually connect the explanation with the code that it applies to.
4.4 Function calls
4.4.1 Named arguments
A function’s arguments typically fall into two broad categories: one supplies the data to compute on; the other controls the details of computation. When you call a function, you typically omit the names of data arguments, because they are used so commonly. If you override the default value of an argument, use the full name:
Avoid partial matching, where you supply a unique prefix of a function argument.
Show the code
# Goodrep(1:2, times =3)cut(1:10, breaks =c(0, 4, 11))# Badrep(1:2, t =3)cut(1:10, br =c(0, 4, 11))
4.4.2 Assignment
Avoid assignment in function calls:
Show the code
# Goodx <-ComplicatedFunction()if (nzchar(x) <1) {# do something}# Badif (nzchar(x <-ComplicatedFunction()) <1) {# do something}
The only exception is in functions that capture side-effects:
Show the code
output <-capture.output(x <-f())
4.4.3 Long function calls
Strive to limit your code to 80 characters per line. This fits comfortably on a printed page with a reasonably sized font. If you find yourself running out of room, this is a good indication that you should encapsulate some of the work in a separate function or use early returns to reduce the nesting in your code.
If a function call is too long to fit on a single line, use one line each for the function name, each argument, and the closing ). This makes the code easier to read and to change later.
Show the code
# GoodDoSomethingVeryComplicated(something ="that",requires = many,arguments ="some of which may be long")# BadDoSomethingVeryComplicated("that", requires, many, arguments,"some of which may be long" )
As described under Named arguments, you can omit the argument names for very common arguments (i.e. for arguments that are used in almost every invocation of the function). If this introduces a large disparity between the line lengths, you may want to supply names anyway:
You may place multiple unnamed arguments on the same line if they are closely related to each other. A common example of this is creating strings with paste(). In such cases, it’s often beneficial to match one line of code to one line of output.
Braced expressions, {}, define the most important hierarchy of R code, allowing you to group multiple R expressions together into a single expression. The most common places to use braced expressions are in function definitions, control flow, and in certain function calls (e.g. tryCatch() and test_that()).
To make this hierarchy easy to see:
{ should be the last character on the line. Related code (e.g., an if clause, a function declaration, a trailing comma, …) must be on the same line as the opening brace.
The contents should be indented by two spaces.
} should be the first character on the line.
Show the code
# Goodif (y <0&& debug) {message("y is negative")}if (y ==0) {if (x >0) {log(x) } else {message("x is negative or zero") }} else { y^x}test_that("call1 returns an ordered factor", {expect_s3_class(call1(x, y), c("factor", "ordered"))})tryCatch( { x <-scan()cat("Total: ", sum(x), "\n", sep ="") },interrupt =function(e) {message("Aborted by user") })# Badif (y <0&& debug) {message("Y is negative")}if (y ==0){if (x >0) {log(x) } else {message("x is negative or zero") }} else { y ^ x }
It is occasionally useful to have empty braced expressions, in which case it should be written {}, with no intervening space.
R defines three types of looping constructs: for, while, and repeat loops.
The body of a loop must be a braced expression.
Show the code
# Goodfor (i in seq) { x[i] <- x[i] +1}while (WaitingForSomething()) {cat("Still waiting...")}# Badfor (i in seq) x[i] <- x[i] +1while (WaitingForSomething()) cat("Still waiting...")
It is occasionally useful to use a while loop with an empty braced expression body to wait. As mentioned in Braced expressions, there should be no space within the {}.
4.6.2 If statements
A single line if statement must never contain braced expressions. You can use single line if statements for very simple statements that don’t have side-effects and don’t modify the control flow.
A multiline if statement must contain braced expressions.
Show the code
# Goodif (x >10) { x *2}if (x >10) { x *2} else { x *3}# Badif (x >10) x *2# In particular, this if statement will only parse when wrapped in a braced# expression or call{if (x >10) x *2else x *3}
When present, else should be on the same line as }.
Avoid implicit type coercion (e.g. from numeric to logical) in the condition of an if statement:
Show the code
# Goodif (length(x) >0) {# do something}# Badif (length(x)) {# do something}
& and | should never be used inside of an if clause because they can return vectors. Always use && and || instead.
ifelse(x, a, b) is not a drop-in replacement for if (x) a else b. ifelse() is vectorised (i.e. if length(x) > 1, then a and b will be recycled to match) and it is eager (i.e. both a and b will always be evaluated).
4.6.3 Control flow modifiers
Syntax that affects control flow (like return(), stop(), break, or next) should always go in their own {} block:
Show the code
# Goodif (y <0) {stop("Y is negative")}find_abs <-function(x) {if (x >0) {return(x) } x *-1}for (x in xs) {if (is_done(x)) {break }}# Badif (y <0) stop("Y is negative")find_abs <-function(x) {if (x >0) return(x) x *-1}for (x in xs) {if (is_done(x)) break}
Use ", not ', for quoting text. The only exception is when the text already contains double quotes and no single quotes.
Show the code
# Good"Text"'Text with "quotes"''<a href="http://style.tidyverse.org">A link</a>'# Bad'Text''Text with "double" and \'single\' quotes'
4.9.2 Logical vectors
Prefer TRUE and FALSE over T and F.
4.10 Comments
Each line of a comment should begin with the comment symbol and a single space: #
In data analysis code, use comments to record important findings and analysis decisions. If you need comments to explain what your code is doing, consider rewriting your code to be clearer. If you discover that you have more comments than code, consider switching to R Markdown.
4.10 Comments
Each line of a comment should begin with the comment symbol and a single space:
#In data analysis code, use comments to record important findings and analysis decisions. If you need comments to explain what your code is doing, consider rewriting your code to be clearer. If you discover that you have more comments than code, consider switching to R Markdown.