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.” Headley 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:

Bad code:

16.7 Spaces: colons

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

Good:

Bad:

16.8 Spaces: multiple spaces

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

More well-structured …

… than this:

16.9 Spaces: brackets

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

Good:

Bad:

16.10 Spaces: commas

Always use spaces after the comma.

Good:

Bad:

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:

Bad:

16.12 Indention

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

Good:

Bad:

For very short statements:

16.13 Explicit return

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

Good:

Bad:

For short functions or temporary functions:

16.16 Object assignment

Use <- and not =.

Good:

Bad:

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.

16.18 All together

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

Good:

Very, very bad: