The most visible part of a coding style is the naming convention.
People use many different styles of naming conventions within the R
ecosystem (Bååth 2012). Popular ones are
alllowercase, period.separated,
underscore_separated, lowerCamelCase and
UpperCamelCase.
checklist defaultWe picked underscore_separated because that is the
naming convention of the tidyverse packages. It is
also the default setting in the lintr
package which we use to do the static code
analysis.
At first this seems a lot to memorise. RStudio makes things easier
when you activate all diagnostic options (Tools > Global
options > Code > Diagnostics). This
highlights several problems by showing a squiggly line and/or a warning
icon at the line number. Instead of learning all the rules by heart, run
check_lintr() regularly and fix any issues that come up. Do
this when working on every single project. Doing so enforces you to
consistently use the same coding style, making it easy to learn and use
it.
underscore_separated names for functions, parameters
and variables.|> or %>%){}<-, ->,
=+, -,*,
/, …,( or [
if (), for (),
while ()) and {,
e.g. function () {") to define character strings.Pro tip: We strongly recommend to use Air to format your code automatically when saving the file. This works in 99.9% of the cases and saves you a lot of time.
<- or -> to assign something.
Only use = to pass arguments to a function
(e.g. check_package(fail = TRUE)).is.na(x) instead of x == NA.seq_len() or seq_along() instead of
1:length(x), 1:nrow(x), … Advantage: when
length(x) == 0, 1:length(x) yields
c(1, 0), whereas seq_along(x) would yield an
empty vector.git. If it is code that you
need to run only under special circumstances, then either put the code
in a separate script and run is manually or write an if-else were you
run the code automatically when needed.assertthat::assert_that() to validate object or
conditions instead of if() stop().ifelse() instead of
if().checklist allows you to define your own set of linters
at the organisation level. Because checklist depends on the
citeme
package, and citeme allows to define custom organisation
settings via a git repository, we will reuse this repository. To do so,
create a .lintr file in the root of your organisations’
citeme repository. This allows for a different coding style
that better fits your organisation, but still enforces the same style
within your organisation.
In case there is no citeme repository in your
organisation, or there is no .lintr file in it,
checklist looks for a local .lintr file in the
root of your project. Note that a local .lintr file is
ignored if a .lintr file is found in your organisation’s
citeme repository. checklist falls back to
using the default .lintr file provided with the
checklist package when no other .lintr file is
found.