Chapter 16 Style guide

16.1 What is a coding style?

“Good coding style is like using correct punctuation. You can manage without it, but it sure makes things easier to read.” Hadley Wickham.

“thus try to make use of it try to follow the style guides you may thin it is kind of useless in the beginning however you will see that it is especially when your functions get more complex very useful to do so i often spent hours to find my own bugs just because my coding style was horrible keep that in mind” Reto, 2019.

16.2 Special characters

  • do not use special characters (Umlaute, apostrophes, …)
  • neither for object names, nor comments!
  • you may have noticed it: object names have to start with a letter, blanks are not allowed

16.3 Language

Preferably in English. Especially if you hand over your code to someone else.

16.4 Script file names

Should be meaningful and use the .R suffix.

Good:

  • fit-linear-models.R
  • utility-functions.R
  • session02_exerciseA.R

Bad:

  • foo.R
  • things.R
  • exercise.R

16.5 Object names

Should be lowercase and meaningful! Use underscores to separate words within a name. If possible use nouns for variables and verbs for functions.

Good:

  • day_one
  • day_1
  • gender
  • height
  • smallest_male
  • temp_kelvin

Bad:

  • the_first_day_of_month
  • DayOne
  • dayone
  • djm1
  • foo
  • T (existing name!)
  • c (existing name!)
  • mean (existing name!)

16.6 Spaces: infix operators

Put spaces around all infix operators (+, /, *, &, ==, |), around the get operator (<-) and =’ s.

Well written code:

temp   <- temp * 9 / 5 + 32
volume <- 4 / 3 * pi**3
if (temp == 0) {
    cat("pretty cool")
}

Bad code:

temp<-temp*9/5+32
volume<-4/3*pi**3
if(   temp==0){ print("cool")   }

16.7 Spaces: colons

One exception: There is no space around colons (:, ::, :::):

Good:

x <- 1:10

Bad:

x <- 1 : 10

16.8 Spaces: multiple spaces

Ok to use multiple spaces if it increases readability. E.g.:

More well-structured …

list(
  total    = l + b + h,
  mean     = (l + b + h) / 3,
  variance = var(c(l + b + h))
)

… than this:

list(
  total = l + b + h,
  mean = (l + b + h) / 3,
  variance = var(c(l + b + h))
)

16.9 Spaces: brackets

A space before opening round brackets (() and after closing round brackets ()) except for function calls.

Good:

if (a == 4) { cat("a equals 4") }
if (debug) print(x)
mean(x)
plot(x, y, col = "red")

Bad:

if(a==4)
if(debug)print  (x)
mean (x)
plot (x,y,col="red")

16.10 Spaces: commas

Always use spaces after the comma.

Good:

x <- c(1, 2, 4)
x <- mat[1, ]
plot(x, y, col = "red")

Bad:

x <- c(1,2,4)
x <- mat[1,]
plot(x,y,col = "red")

16.11 Opening/closing brackets

Opening curly brackets should never go in a new line, but should always be followed by a new line. Final closing curly brackets should be in a separate line.

Good:

if (a == 10) {
  res <- TRUE
} else {
  res <- FALSE
}

myfun <- function(x) {
  # Instructions
}

Bad:

if (a == 10)
{
  res <- TRUE
} else
{
  res <- FALSE}

16.12 Indention

Use block-wise indention (RStudio supports you). Suggested by Hadley: use two spaces as indent.

Good:

powfun <- function(x) {
  res <- x**y
  return(res)
}

Bad:

powfun <- function(x) {
res <- x**y
return(res)
}

For very short statements:

powfun <- function(x, y) { return(x^y) }
if (a == 10) { res <- TRUE }
powfun <- function(x, y) return(x^y)
if (a == 10) res <- TRUE

16.13 Explicit return

My personal suggestion: explicitly use the command when returning results from a function!

Good:

powfun <- function(x) {
    res <- x^2
    return(res)
}
powfun <- function(x, y) return(x^y)

Bad:

powfun <- function(x) {
    res <- x^2
    res
}

For short functions or temporary functions:

powfun <- function(x, y) x^y
sapply(data, function(x) x^2)

16.14 Line breaks

Line breaks: lines should not be longer than 80 characters. Use line breaks for long statements.

Good:

data <- c(firstname  = "Reto",      lastname = "Stauffer",
          city       = "Innsbruck", zipcode  = "6020",
          department = "Department of Statistics")

Bad:

data <- c(firstname = "Reto", lastname = "Stauffer", city = "Innsbruck", zipcode = "6020", department = "Department of Statistics")

16.15 Nested indention

Use block-wise indention (RStudio supports you). Use two spaces as indent.

Good:

demo_function <- function(x) {
  if (a == 3) {
    res <- "This"
  } else {
    for (i in 1:10) {
      res <- a + i
    }
  }
  return(res)
}

Bad:

demo_function <- function(x) {
if (a == 3) {
res <- "This"
} else {
for (i in 1:10) {
res <- a + i
}
}
return(res)
}

16.16 Object assignment

Use <- and not =.

Good:

a <- 5
powfun <- function(x, y) return(x^y)

Bad:

a = 5
powfun = function(x, y) return(x^y)

16.17 Comments

  • Start to write comments!
  • Again: code is more often read then written,
  • comments help to understand code (also your own!).
  • Use # ------ or # ======== to separate code blocks.
# -----------------------------
# Define variables
x <- seq(0, 100, length.out = 100)
y <- sin(x / pi * 180)
# -----------------------------
# Create plot
plot(x, y, col = 5)

16.18 All together

Both code chunks do the very same. And both will work. I think there’s nothing to say here!

Good:

demo_function <- function(x) {
  if (a == 3) {
    res <- "This"
  } else {
    for (i in 1:10) {
      res <- a + i
    }
  }
  return(res)
}

Very, very bad:

DmoFn<-function(x)
{if(a==3) {res <- "This"
}else{
for(i in 1    :10) {
res= a   +i}}
    res}