User Tools

Site Tools


tools:style_guides:r

R style guide

R code that is submitted to be included in any of the R tools developed at BSC should follow these style guidelines, based on the tidyverse style guide:

  • Use `←` for variable assignment
  • Include spaces between operators (e.g. `+`, `-`, `&`), before `{`, and after `for`, `if`, `while`, `,` and `)`.
  • When possible, maximum line length should be 100 characters (soft limit of 80 characters).
  • Number of indentation spaces is 2, using tabs for indentation is forbidden.
  • Double quotes are recommended for strings. When writing quotes within quoted text, use double quotes outside and single quotes inside. E.g.: `“Parameter 'na.rm' is missing.”`
  • Self-explanatory names are preferred for variables. Try to be consistent with the variable naming style. Generally: avoid special characters (except underscores) and reserved words (ex: if, for, else, …)
  • Remember to include short comments to make the code easier to understand. Comments should be in their own line and they should start with `#` followed by a space. Comments that start with `##` and a space are for details not needed to understand the general procedure but useful to make note of more technical aspects of the code.

Examples

# Proper spacing, indentation spaces and text quotes:
NewFunction <- function(text = "default", uppercase = TRUE) {
  # Check uppercase parameter
  if (!is.logical(uppercase)) {
    stop("Parameter 'uppercase' should be TRUE or FALSE.")
  }
  # Only transform text if needed
  if (uppercase && is.character(text)) {
  text <- toupper(text)
  }
  return(text)
}
# How to format line breaks to avoid long lines:
my_strings <- list(one = "un",
                   two = "dos",
                   three = "tres",
                   four = "quatre")
# or:
my_strings <- list(
  one = "un",
  two = "dos",
  three = "tres",
  four = "quatre"
)

Other resources

For more tips on writing clean and easy to read code, check the tidyverse style guide. You can use the styler R package to automatically style your code, and it can even be integrated in RStudio!

tools/style_guides/r.txt · Last modified: 2024/09/10 14:39 by vagudets