16.5 Examples


 - Provides executable code on how to use the function in practice
 - Must run without errors or use `\dontrun{}`
 - **Keep in mind:** Most users will look at examples first 

Tension between readable and realistic example code vs. no errors and side effects

Examples executed in 4 situations:

  1. interactively with example()
  2. R CMD check on your computer(s)
  3. R CMD check by CRAN
  4. pkgdown website building

16.5.1 Contents

  • Show basic functionality
  • highlight easy to miss features
  • avoid edge cases
  • sectioning is awkward
  • try to use built-in datasets

16.5.2 Leave the world as you found it

There is no way to schedule clean up in examples like there are in functions and testing.

16.5.3 Errors

If you need to demonstrate an error you can

  • wrap code in try()
  • wrap code in \dontrun{}

Recommend using try()

16.5.4 Dependencies and conditional execution

Ok to do library() in the examples as

  • expect suggested packages available during R CMD check
  • cost of putting code inside {...} is high

Recommendation for conditional cases is to use @examplesIf tag

  • hides machinery from users
  • example code renders in pkgdown
  • doesn’t break CRAN’s prohibition of putting code in \dontrun{}

16.5.5 Intermixing examples and text

Alternative is using RMarkdown but downsides:

  • code in ```R blocks is never run
  • codes in ```{r} is run every time you document