R Lazy Arguments
A lazy argument is a promise that is worked out only when the function body uses it. An argument the body never touches is never worked out at all.
An unused default never fires
The default for value would stop with an error. The body never uses value, so the call prints its line and ends cleanly.
report <- function(value = stop("never used")) {
cat("body ran\n")
}
report()A passed value replaces the default
The call passes 7 for value. The body prints 7 and the erroring default is never worked out.
report <- function(value = stop("never used")) {
print(value)
}
report(7)missing() spots a missing argument
check prints a plain line when no score is passed. A passed score prints as a number instead.
check <- function(score) {
if (missing(score)) {
cat("nothing passed\n")
} else {
print(score)
}
}
check()
check(9)A default built from another argument
tax defaults to a tenth of price. The first call uses that default and the second call passes its own tax value.
total_with_tax <- function(price, tax = price / 10) {
return(price + tax)
}
print(total_with_tax(100))
print(total_with_tax(100, 25))Example
checkout <- function(price, tax = price / 10) {
if (missing(tax)) {
cat("tax added by default\n")
}
print(price + tax)
}
checkout(50)
checkout(50, 8)Key points
- Each argument in a call becomes a promise paired with the code that was passed or the default.
- A default that would stop with an error never fires when the argument stays unused.
- A passed argument replaces the default, so the default is never worked out.
- missing() reports TRUE when no argument was passed for a name.
- missing() reports FALSE when an argument was passed for a name.
- A default can be worked out from another argument.
In this example, the first checkout call passes no tax, so the default of a tenth of the price is used and the total is 55. The second call passes a tax of 8, so no default line prints and the total is 58.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
A function has a default that stops with an error and its body never uses that argument. What happens when the function is called with no argument?