5 Syntax
5.1 Spacing
Spacing is important so others can browse your code with more ease. Put space around arithmetic and logical operators, and after “,”. Whether space should be inserted immediately after ( or [ and before ) or ] is a matter of personal choice, but whatever style you prefer, adhere to it throughout your project.
# Bad Examples
m=1
s=2
x=rnorm(1000,mean=m,sd=s)
# Good Examples
dMean <- 1 # mean
dSd <- 2 # standard deviation
nSize <- 1000 # sample size
vSamp <- rnorm(n = nSize, mean = dMean, sd = dSd)
# Last is preferred making longer code block less cramped, especially when there are multiple arguments
x[i,] and f(x) # Acceptable
x[i, ] # Better
x[ i, ] and f( x )# Best
5.2 Code Blocks
Code should be organized so that there is less repetition and more abstraction.
# Bad Example
a <- sin(1.2) + exp(5.7)
b <- sin(2.4) + exp(-2)
c <- a + b
# Better Example
f <- function(x, y){ return( sin(x) + exp(b) ) }
a <- f(2.4, -2)
b <- f(1.2, 5.7)
c <- a + b
One liner function definitions are reasonable if the line is short, simple and follow the explicit return, however for readability and testing the following is preferred.
# Even Better Example
f <- function(x, y)
{
return( sin(x) + exp(b) )
}
a <- f( 2.4, -2 )
b <- f( 1.2, 5.7 )
c <- a + b
5.3 Assignment
There are five ways to assign a variable values in R.
# Five ways to say thank you
thx <- 1
thx <<- 1
thx = 1
1 -> thx
1 ->> thx
Even though “=” and “<-” are interchangeable, typical R style guides urge the use of “<-”, one for historical reasons, another for consistency with the double “<<-” operator for which “=” has no counterpart. The rightwards form work naturally in conjunction with pipe operator “%>%” although the use of “%>%” lends to obfuscation and is discouraged.
For clarity and consistency, it is recommended to only use <- and <<- and do not use =, -> and ->>.
5.4 Semicolons
Don’t put ; at the end of a line and don’t use ; to put multiple commands on one line.
# Good Examples
x <- 5
y <- 2
z <- 3
#Bad Examples
x <- 5; y <- 2; z <- 3;
x <- 5; y <- 2;
z <- 3;
x <- 5;
y <- 2;
z <- 3;
5.6 Furthermore
There are tools to help you better format your code, packages such as “formatR”, “styler”, that can manage spacing and indentation reasonably.
5.5 Comments
Comments should be meaningful and add understanding to the code. If your code requires a comment for most lines, consider rewritting be clearer. Utilizing naming conventions is helpful. In addition, using organized files and creating functions for complex code blocks can be helpful.