The apply family in R
R's idiomatic replacement for explicit loops.
scores <- list(math = c(90, 85), art = c(70, 95, 80))
means <- sapply(scores, mean)
as_list <- lapply(scores, range)
counts <- vapply(scores, length, integer(1))
m <- matrix(1:6, nrow = 2)
row_sums <- apply(m, 1, sum)
col_max <- apply(m, 2, max)
pairs <- mapply(function(a, b) a * b, 1:3, 4:6)
How it works
sapplysimplifies results;lapplykeeps a list.vapplyfixes the return type for safety.applyworks over matrix rows or columns;mapplyzips.
Keywords and builtins used here
applycfunctionintegerlapplylistmapplymatrixsapplyvapply
The run, in numbers
- Lines
- 11
- Characters to type
- 296
- Tokens
- 107
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 71 seconds.
Step 1 of 5 in Vectorized thinking, step 10 of 20 in Language basics.