Coding Style for R.
A primary aim of any coding style is to ensure consistency in coding and to ease the task for the reader in understanding the code. Coding style matters little to an automated compiler. So write your code for others to read.
I generally like the guidelines at Google but have my own idiosyncrasies. The style decisions I have made I motivate below, based on over 30 years of programming. Also see Wikipedia for coverage of many styles.
I have now made a more comprehensive guide available. I introduce it on the Revolutions Blog and you can access it directly from Hands On Data Science.
- Filenames end in ".R". This aligns with the fact that the
language is unambiguously called "R" and not "r".
Good: generate_plots.R Bad: generate_plots.r
- R binary data filenames end in ".RData". I have no strong
motivation for this except that it conforms to the capitalised
naming scheme.
Good: weather.RData Bad: weather.rdata weather.Rdata
- Function names use capitalised verbs, beginning with
lowercase.
Good: displayPlotAgain Bad: DisplayPlotAgain displayplotagain
- Variable names use underscore separated words.
Good: list_of_frames Bad: list.of.frames
- Constants are all capitals. This makes them stand out and
makes it clear that they should not be changed.
Good: MAX.LINES Bad: const.max.lines
- Named arguments in parameter lists do not have a space around
the =. I prefer this as visually it ties the named arguments
strongly together. This is the only situation where I tightly couple
a binary operator. in all other situations there should always be a
space around the operator.
Good: read.csv(file="data.csv", sep=";", na.strings=".") read.csv(file="data.csv", sep=";", na.strings=".")
- Use an indentation of 2. Some argue this is not enough to show the structure when using smaller fonts. If it is an issue for you then maybe 4 is okay. But I would choose a different font instead.
- Align curly braces. Thus an opening curly brace is on a
line by itself. This is a particular difference with many other
coding styles. My motivation is that the open and close curly braces
are then aligned visually and this provides an added visual check of
syntax correctness and visually gives a very strong code block
view. The placement of the open curly bracket at the end of the
previous line is endemic and in my opinion is bad practise, hiding
the opening of a block of code simply to save on having some
additional lines (which was important in my younger days where we
were limited to 24 lines on a terminal). This style also makes it
easier to comment out, for example, just the line containing the
"while" and still have valid syntax.
Good: while (sky.is.blue) { openTheWindows() doSomeRearch() } retireForTheDay() Bad: while (sky.is.blue) { openTheWindows() doSomeRearch() } retireForTheDay()
Copyright © 2006-2023 Togaware Pty Ltd
This site is hosted in the cloud by OpalStack.
Last Modified 2016-10-29 10:13:21 Graham Williams
Shop at Amazon