1.4 Coding conventions
We mostly/loosely follow the tidyverse
style guide with a couple exceptions. The primary purpose of these exceptions is to speed up typing by eliminating characters or reducing the need to use the Shift key. Sorry tidyverse
style guide team!
1.4.1 Exception: We’ll use =
not <-
for assignments
Most R coders use <-
for object assignment (e.g. x <- 2
to store 2
as the object x
). We will use the equals sign (e.g. x=2
) because it is faster to type, it is similar to what is used in Python, MATLAB, and Julia, and will be equivalent to <-
in almost all situations. When they are not equivalent, we’ll resort to using <-
.
One situation when <-
works and =
doesn’t involves trying to make an assignment when calling another function.
tryCatch(x = runif(1)) # Fails. It interprets x as an argument of tryCatch
tryCatch(x <- runif(1)) # Works
summary(lm1 = lm(mpg ~ wt, mtcars)) ## Fails. It thinks lm1 is an argument of summary
summary(lm1 <- lm(mpg ~ wt, mtcars)) ## Works.
We will rarely try to make assignments like that anyway. Instead, we’ll do things like
x=runif(1)
tryCatch(x)
lm1 = lm(mpg ~ wt, mtcars)
summary(lm1)
In rare cases, we may not be able to avoid it, in which case we’ll use <-
.
You can of course feel free to use <-
when you are coding, but we won’t typically be using it in these notes.
1.4.2 Exception: We’ll use .
more than _
for names
The style guide recommends using _
instead of .
in function names, column names, etc. (e.g. first_name
instead of first.name
, add_row()
instead of add.row()
). We’ll use both, but we will more often use .
because it is faster to type.
At times we’ll probably be a little lazy with some of the conventions in the style guide but we’ll do our best.