Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Functions  ›  Lesson

Writing Functions — Arguments and Defaults

Arguments & Defaults 12 minA function packages code behind a name, and when you call it R matches arguments by name first, then by position, and fills any that are still missing with their defaults.

Writing Functions — Arguments and Defaults

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.

The shortcut

Draw one slot per parameter. Fill the named ones first, hand out the unnamed values left to right into the empty slots, then drop defaults into whatever is left. Now evaluate the body.

Tracing yield(area = 2, 6)Step 1 of 4
  1. Named first

    area = 2 goes straight into the area slot.

Drills

Answer fast — trust the rule.

quick drill

What does yield(15, 5) return?

quick drill

What does yield(12.5) return?

quick drill

What does yield(unit = "kg", 8, 2) return?

quick drill

What happens when you call yield() with no arguments?

quick drill

A function body has no return(). What does the function return?

Remember

  • Arguments match by name first, then by position; defaults fill the gaps.
  • Shortcut: fill named slots, hand out unnamed values left to right, then drop in defaults.
  • Trap: calling with bare positions past the first one or two; name them instead.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainTrace the call

Given yield <- function(kg, area = 4, unit = "kg/m2") paste(kg / area, unit), explain how R matches the arguments in yield(unit = "kg", 8, 2) and what the call returns.