Best practices for readable, sharable, and verifiable R code
.R
_
not .
# Good
getData.R
# Acceptable
get_data.R
# Bad
foo.bar.r
89317240934735.r
.
is also accepted.
with class names due to potential confusion with S3 method declarations
_
or -
with 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()
<-
not =
;
# Good
x <- 23
y <- 12
# Bad
x = 23; y = 12
23 -> x
=, +, -, <-,
etc.(
, except in a function call# 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
}
{
on its own line }
on its own line unless followed by else
else
statements with curly braces # Good
if (a < d) {
a <- (b + c) * d
} else {
a <- d
}
# Bad
if (a < d)
{
a <- (b + c) * d
} else a <- d
# 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)
#
followed by a space#
#' 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
seq(along = x)
to protect against instances where x
is emptyapply, lapply, etc
when possible
# 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
for better interpretability# Good
repeat {
...
}
# Bad
while (TRUE) {
...
}