Indentation
In this lesson we will learn about indentation and spacing in R.
Line Length
The maximum line length is 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.
- Exception: Spaces around
Press + to interact
# GOODsomeFunction <- function(a, b, c, d = 100) {a <- (b + c) * dtab.prior <- table(df[df$days.from.opt < 0, "campaign.id"])}}# BADsomeFunction <- function(a,b,c,d= 100) { # Spaces missing after commaa<-(b+c)*d # Spaces missing after operatorstab.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
# GOODtab.prior <- table(df[df$days.from.opt < 0, "campaign.id"])total <- sum(x[, 1])total <- sum(x[1, ])# BADtab.prior <- table(df[df$days.from.opt < 0,"campaign.id"]) # Needs a space after the commatotal <- sum(x[,1]) # Needs a space after the commatotal <- 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
# GOODif (debug)# BADif(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
# GOODplot(x = x.coord,y = data.mat[, MakeColName(metric, ptiles[1], "roiOpt")],ylim = ylim,xlab = "dates",ylab = metric,main = (paste(metric, " for 3 samples ", sep = "")))# BADplot(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
# GOODif (debug)# BADif ( debug ) # No spaces around debug# GOODx[1, ]# BADx[1,] # Needs a space after the comma