Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

Writing Functions — Arguments and Defaults

Arguments & Defaults 12 minA function defines a computation with formal arguments and a body. R matches supplied arguments using naming and position rules, with defaults for omitted arguments that have them.

r programming / Writing Functions — Arguments and Defaults

Explore each scene at your own pace.

01 · The rule

The rule

Writing Functions — Arguments and Defaults

A function defines a computation with formal arguments and a body. R matches supplied arguments using naming and position rules, with defaults for omitted arguments that have them.

Call a function with defaults and named arguments, then inspect its returned value.

Every week you divide each plot's harvest by its area to compare plots fairly. Most plots are 4 square metres, a couple are not, and the newsletter wants a unit on the end. Writing that once as a function, with sensible defaults, beats copying the same line ten times.

The rule

Arguments match by name first, then by position; defaults fill the gaps.

yield <- function(kg, area = 4, unit = "kg/m2") {
  paste(kg / area, unit)
}
  • function(...) lists the parameters: kg, area and unit.
  • area = 4 and unit = "kg/m2" are defaults, used when the caller leaves them out. kg has no default, so it is required.
  • The function returns the value of the last expression in its body. return() is only needed to leave early.

When you call it, R pairs the values you pass (the arguments) with the parameters in three passes:

  1. Arguments given by name go to that parameter.
  2. The remaining unnamed arguments fill the remaining parameters left to right.
  3. Any parameter still empty uses its default, or causes an error if it has none.
yield(12.5)                   # "3.125 kg/m2"    area and unit use defaults
yield(15, 5)                  # "3 kg/m2"        15 to kg, 5 to area
yield(8, unit = "kg per m2")  # "2 kg per m2"
yield(area = 2, 6)            # "3 kg/m2"        6 fills kg, the first empty slot
yield()                       # Error: argument "kg" is missing, with no default

Name every argument after the first one or two. yield(15, area = 5) is much easier to read months later than yield(15, 5).

Two more tools you will see often:

  • ... ("dots") collects any extra arguments and passes them on: total <- function(x, ...) sum(x, ...) lets a caller write total(c(1, NA), na.rm = TRUE) and get 1.
  • stopifnot() checks inputs at the top of a function: stopifnot(is.numeric(kg), area > 0) stops with a clear message instead of producing nonsense.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.