1  ESQlabs’ R Good Practices

1.1 Within projects

1.1.1 R projects

  • Use R projects. R projects should be created when your project was initialized.

  • Do not use setwd, with R projects the working directory should already be set to the right location.

  • Only use relative paths that are contained within your project structure.

1.1.2 Renv

  • Use {renv} to ensure every collaborator use the same version of the packages. Ideally your project should have been set up with {renv}.

1.1.3 Style

  • Respect coding style.

  • Help yourself and others by using {styler} package (for indentations and line breaks compliance), and {lintr} package for checking style (line length, variable casing, …).

    • Both packages provides easily accessible RStudio Addins (e.g. Style current file, Lint current file).

    • Styling current file will directly reformat your file, while linting your file will tell you where and why your code is not compliant to the defined style.

    • Both packages and a default .lintr should be ready to use within your project (soon).

1.1.4 Code Organisation and Structure

  • Respect code header (include author, date, …), should be at the very beginning of the script:

    ################################
    # Authors:     Name 
    # Property:     ESQlabs GmbH
    # Initial Date: DD.MM.YYYY
    # Last updated: DD.MM.YYYY
    ################################
  • Use sections (commented lines of - or =) to break up your file into easily readable chunks.

    # Load Libraries --------------------
  • Load needed packages at the beginning of the file, in the first section just after the header.

  • Source needed files (for example containing “homemade” functions) just after loading packages in a specific section.

  • Define constant parameters in a specific section just after loading packages or sourcing files.

1.1.5 Comments

  • Comment your code. Explain the “why” not the “what” or “how”.

  • Once your code is finalized remove any commented code from your files.

1.1.6 Functions

  • Generic “homemade” functions that might be needed in various R scripts should be written in a separate file sourced when needed.

  • Avoid having too many nested levels (for loops, …). Try to create functions instead.