typestar

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

  1. sapply simplifies results; lapply keeps a list.
  2. vapply fixes the return type for safety.
  3. apply works over matrix rows or columns; mapply zips.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 5 in Vectorized thinking, step 10 of 20 in Language basics.

← Previous Next →