apply(), lapply(), sapply(), tapply()

The apply family applies a function over margins of arrays, lists or grouped data — cleaner and often faster than explicit loops. lapply returns a list; sapply simplifies to vector/matrix; vapply is the type-safe version.

basics
Functions: apply(X, MARGIN, FUN) lapply(X, FUN) sapply(X, FUN) tapply(X, INDEX, FUN)
m <- matrix(1:12, nrow = 3)

# apply: over rows (1) or columns (2)
apply(m, 1, sum)    # row sums
apply(m, 2, mean)   # column means

# lapply: returns list
vals <- list(a = c(1,2,3), b = c(4,5,6))
lapply(vals, mean)

# sapply: simplifies to vector
sapply(vals, mean)           # named numeric vector
sapply(1:5, function(x) x^2)

# tapply: apply by group
lengths <- c(82, 65, 110, 95, 55)
group   <- c("A","B","A","B","A")
tapply(lengths, group, mean)   # mean per group