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 = "")
  1. add_tax ← function(price)

    1add_tax <- function(price) {2  price * 1.08
    values this stepfunction(price)add_tax
  2. subtotal ← 25

    3}4subtotal <- 255total <- add_tax(subtotal)
    values this step25subtotal
  3. call ← add_tax(25)

    4subtotal <- 255total <- add_tax(subtotal)6cat(total, "\n", sep = "")
    values this stepadd_tax(25)call25subtotal
  4. return value ← 27

    1add_tax <- function(price) {2  price * 1.083}
    values this step27return value25price
  5. total ← 27

    4subtotal <- 255total <- add_tax(subtotal)6cat(total, "\n", sep = "")
    values this step27total
  6. cat(total, " ", sep = "")

    5total <- add_tax(subtotal)6cat(total, "\n", sep = "")
    output27
    values this step27total

Call the Function

  1. add_tax names a reusable calculation.
  2. subtotal is 25.
  3. add_tax(subtotal) passes 25 as price.
  4. The function multiplies by 1.08 and returns 27.
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