Apply-style functions run one operation across pieces of data. sapply simplifies the result when it can.

Program

Play the script to sum each list element and select one named total.

apply_family.R
Replay: real traced execution (multi-file project)
values <- list(a = 1:3, b = 4:5)
totals <- sapply(values, sum)
answer <- totals["b"]
cat(answer, "\n", sep = "")
  1. values ← a=1:3, b=4:5

    1values <- list(a = 1:3, b = 4:5)2totals <- sapply(values, sum)
    values this stepa=1:3, b=4:5values
  2. totals ← a=6, b=9

    1values <- list(a = 1:3, b = 4:5)2totals <- sapply(values, sum)3answer <- totals["b"]
    values this stepa=6, b=9totalsa=1:3, b=4:5values
  3. answer ← 9

    2totals <- sapply(values, sum)3answer <- totals["b"]4cat(answer, "\n", sep = "")
    values this step9answer9totals["b"]
  4. cat(answer, " ", sep = "")

    3answer <- totals["b"]4cat(answer, "\n", sep = "")
    output9
    values this step9answer

Follow the List

  1. values has two named pieces: a = 1:3 and b = 4:5.
  2. sapply(values, sum) runs sum once for a and once for b.
  3. The sums are a = 6 and b = 9.
  4. totals["b"] selects 9, and cat prints it. | name | values | sum | | --- | --- | --- | | a | 1, 2, 3 | 6 | | b | 4, 5 | 9 |
list A list can hold vectors of different lengths under names.
sapply `sapply(values, sum)` runs `sum` for each list element.
named vector The result keeps names such as `a` and `b`.

Exercise: apply_family.R

Reproduce the printed value 9 from list item b, then add one number to b and predict its new sum before running it.