Basic standard
- Default to using projects, rather than
setwd()
etc
- Packages
- Load packages at head of script, rather than dotted through the code
- Keep package loading minimal (nothing “just in case”)
- Make explicit reference to custom/non-CRAN packages, and how they should be loaded
- Help your future self (or another user of the code)
- Use descriptive and consistent variable names
- If variables need to be set by the user, consider collecting those together at the head of the script with appropriate comments. Or consider collecting these together into a settings file
- Add sections of code to make the structure of your script clear
- Consider breaking long complex scripts into functional units. So one script to load your data, one to tidy it, a third to calculate something…
- Include authorship, contact details, and brief documentation of the purpose of the script
- Avoid extremely repetitious code. Consider using functions to avoid repeating yourself
- Consider using styler to keep your code formatted consistently
Enhanced standard
- Make explicit reference to any formal style conventions employed
- Use version control
- For ambitious projects, consider using renv which will capture R and package versions
- For more onerous scripts, identify memory and CPU requirements listed at start
- consider using project templates for presentations/reports/dashboards
- Consider loading individual functions via
package::function()
syntax rather than wholesale package loading for namespace and performance reasons
- consider using targets to encourage the use of functions, visually displays the build pipeline and avoids unnecessary re-running of up-to-date code
Considerations for teams and groups
- Have a house code style, possibly implemented using styler Code styling for readability is important, and no-one agrees, so you’ll need to lead.
- When documentation is extremely important, consider using roxygen2 to encourage best documentation practice