If you are a beginner R programmer, it is a good idea to learn and start using the good practices in coding. Even if the code is just for you, it is a good idea to practice good style guide to help the “future yourself”. Google has a good list of things to do and not to do while programming in R. Similarly, R-guru Hadley Wickham also has wonderful tips on R coding style guide. Here are five coding style guide tips that will help you become a better programmer.
Commenting
Commenting your code is a very good idea, for you and the future yourself. Begin the comment line with ” the comment symbol # and one space”. Hadley Wickham recommends to use the remaining of commented lines with – and = to break up your file into easily readable chunks.
# Load data ---------------------------
# parse data ==========================
# plot results ==========================
File names
Needles to say file names should be meaningful and end in .R.
Good
fit-models.R
parse_tweets.R
helper-functions.R
Bad:
script.r
things.r
Assignment
Yes, R is weird. It has an unusual assignment operator “<-” instead of “=” sign. While assigning things, use <- /strong>, not = .
Good
x <- 5
Bad:
x = 5
Spacing
Use spaces around these operators =
, +
, -
, <-.
Use space when using “=” in function call.
Good
x <- 1:10
Bad:
x <- 1 : 10
Also remember to use a space after a comma, and never before.
Good
column1_mean <- mean(x[, 1]) row1_median <- median(x[1, ])
Curly braces
Conditionals in R use curly braces. While opening curly brace, it should not be on its own line and should always be followed by a new line. Similarly, while closing a curly brace, it should always go on its own line, unless it’s followed by else
. Remember to indent the code inside curly braces.
Good
if ( x > 15){ print("x is bigger") }
Bad
if (x > 15) print("x is bigger")
Good
if (y == 0) { y = y + 1 } else { y = y + 2 }
Bad
if (y == 0) { y = y + 1 } else { y = y + 2 }
Variable names
Choosing the right meaningful names for variables and function is the key. Hadley Wickham strong recommends that the variable and function names should be in lowercase. If you have multiple words in the names, use an underscore (_) to separate words within a name. Also , “variable names should be nouns and function names should be verbs”.
Good
sample_one sample_1
Bad
my_really_long_variable_name mrlvn