R Calls and Formals
match.call reads the call that ran a function, as it was written. formals reads a function's arguments and their defaults.
The call as written
show_call prints match.call from inside its own body. The value 1 was passed without a name and still prints matched to x.
show_call <- function(x, y) {
print(match.call())
}
show_call(1, y = 2)Names matched to values
tag prints its call for two different calls. The first call passes both values and the second leaves the default in place.
tag <- function(name, score = 0) {
print(match.call())
}
tag("Ana", score = 90)
tag("Bo")Read the formals
formals prints both arguments of add. The entry for a is empty and the entry for b holds its default of 2.
add <- function(a, b = 2) {
a + b
}
print(formals(add))
print(formals(add)$b)Change a default through formals
The first call to add uses the default of 2 and gives 3. The assignment into formals changes the default to 10, and the next call gives 11.
add <- function(a, b = 2) {
a + b
}
print(add(1))
formals(add)$b <- 10
print(add(1))Example
quote_price <- function(seats, price = 20) {
print(match.call())
seats * price
}
print(quote_price(3))
formals(quote_price)$price <- 25
print(quote_price(3))Key points
- match.call returns the call with each value matched to its argument name.
- A value passed without a name still gains its argument name in the printed call.
- formals returns the argument list of a function.
- An argument with no default shows as an empty entry in the formals print.
- Assigning into formals changes a default for later calls.
- The next call after the change uses the new default.
In this example, quote_price prints its call and works out 3 times the default price of 20, giving 60. The formals assignment then sets the default price to 25, and the same call gives 75.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does formals(add)$b <- 10 do?