Flow and Data
Functions
Reusing a Calculation
Functions name a calculation so the same logic can be called with different inputs.
Program
Play the script to follow a subtotal into a function call and back out as a taxed total.
functions.R
Replay: real traced execution (multi-file project)
add_tax <- function(price) {
price * 1.08
}
subtotal <- 25
total <- add_tax(subtotal)
cat(total, "\n", sep = "")
add_tax ← function(price)
1add_tax <- function(price) {2 price * 1.08values this stepfunction(price)add_taxsubtotal ← 25
3}4subtotal <- 255total <- add_tax(subtotal)values this step25subtotalcall ← add_tax(25)
4subtotal <- 255total <- add_tax(subtotal)6cat(total, "\n", sep = "")values this stepadd_tax(25)call25subtotalreturn value ← 27
1add_tax <- function(price) {2 price * 1.083}values this step27return value25pricetotal ← 27
4subtotal <- 255total <- add_tax(subtotal)6cat(total, "\n", sep = "")values this step27totalcat(total, " ", sep = "")
5total <- add_tax(subtotal)6cat(total, "\n", sep = "")output27values this step27total
Call the Function
add_taxnames a reusable calculation.subtotalis25.add_tax(subtotal)passes25asprice.- The function multiplies by
1.08and returns27.
25 -> add_tax -> 27
function
`function(price) { ... }` creates a reusable calculation.
argument
The call `add_tax(subtotal)` passes the current subtotal as `price`.
return value
The last expression in this function becomes the returned value.
Exercise: functions.R
Write an add_tax function, call it with a subtotal, and print the taxed total