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,areaandunit.area = 4andunit = "kg/m2"are defaults, used when the caller leaves them out.kghas 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:
- Arguments given by name go to that parameter.
- The remaining unnamed arguments fill the remaining parameters left to right.
- 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 defaultName 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 writetotal(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.