Functions

Author

Alec L. Robitaille, Isabella C. Richmond

Structure

Name

Arguments

  • nouns
  • options that modify how the function runs

Body

Return

Structure

name <- function(arguments) {
  body

  return()
}

Naming

snake_case

verb_noun

  • plot_cars()
  • count_trees()
  • model_elephants()

Planning

Define inputs, outputs

Functions should strive to do one thing, with no side effects

  • a common exemption is writing files or generating plots

Checks

Make sure users provide appropriate inputs and arguments

Handle errors with informative errors

  • stopifnot()
  • stop()
  • warning()
  • message()

Control flow

Manage choices, if something do this, else do this

  • if()
  • else()
  • ifelse()

Testing/approach

Simple approach

  • testing scripts
  • interactive tests

Extended approach

  • full testing suites with {testthat} or {tinytest}