...

/

Indentation

Indentation

In this lesson we will learn about indentation and spacing in R.

Line Length

The maximum line length is 8080 characters. This is the amount that will fit comfortably on a printed page at a reasonable size.

Indentation

When indenting your code, use two spaces.

Never use tabs or mix tabs and spaces.

Exception: When a line break occurs inside parentheses, align the wrapped line with the first character inside the parenthesis.

Spacing

  • Place spaces around all binary operators (=, +, -, <-, etc.).
    • Exception: Spaces around ='s are optional when passing parameters in a function call.
Press + to interact
# GOOD
someFunction <- function(a, b, c, d = 100) {
a <- (b + c) * d
tab.prior <- table(df[df$days.from.opt < 0, "campaign.id"])
}
}
# BAD
someFunction <- function(a,b,c,d= 100) { # Spaces missing after comma
a<-(b+c)*d # Spaces missing after operators
tab.prior <- table(df[df$days.from.opt<0, "campaign.id"]) # Needs spaces around '<'
}
  • Do not place a space before a comma, but always place one after a comma.
Press + to interact
# GOOD
tab.prior <- table(df[df$days.from.opt < 0, "campaign.id"])
total <- sum(x[, 1])
total <- sum(x[1, ])
# BAD
tab.prior <- table(df[df$days.from.opt < 0,"campaign.id"]) # Needs a space after the comma
total <- sum(x[,1]) # Needs a space after the comma
total <- sum(x[ ,1]) # Needs a space after the comma, not before
  • Place a space before left parenthesis, except in a function call.
Press + to interact
# GOOD
if (debug)
# BAD
if(debug) # Needs space after `if`
  • Extra spacing (i.e., more than one space in a row) is okay if it improves the alignment of equals signs = or arrows <-.
Press + to interact
# GOOD
plot(x = x.coord,
y = data.mat[, MakeColName(metric, ptiles[1], "roiOpt")],
ylim = ylim,
xlab = "dates",
ylab = metric,
main = (paste(metric, " for 3 samples ", sep = "")))
# BAD
plot(x = x.coord,
y = data.mat[, MakeColName(metric, ptiles[1], "roiOpt")],
ylim = ylim,
xlab = "dates",
ylab = metric,
main = (paste(metric, " for 3 samples ", sep = "")))
  • Do not place spaces around code in parentheses or square brackets.
    • Exception: Always place a space after a comma.
Press + to interact
# GOOD
if (debug)
# BAD
if ( debug ) # No spaces around debug
# GOOD
x[1, ]
# BAD
x[1,] # Needs a space after the comma