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.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.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.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 Hadley: 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.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:
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:
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.