Loops and Apply
Apply Family
Summarizing a List
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 = "")
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:5valuestotals ← 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:5valuesanswer ← 9
2totals <- sapply(values, sum)3answer <- totals["b"]4cat(answer, "\n", sep = "")values this step9answer9totals["b"]cat(answer, " ", sep = "")
3answer <- totals["b"]4cat(answer, "\n", sep = "")output9values this step9answer
Follow the List
valueshas two named pieces:a = 1:3andb = 4:5.sapply(values, sum)runssumonce foraand once forb.- The sums are
a = 6andb = 9. totals["b"]selects9, andcatprints 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.