apply Family (apply, lapply, sapply) (R)

The apply family applies a function repeatedly over a data structure without an explicit loop. apply works over matrix margins, lapply returns a list, and sapply simplifies to a vector or matrix.

R

These functions express 'do this to each element/row/column' functionally, which is more idiomatic (and often clearer) in R than writing for loops. lapply(x, f) applies f to each element of a list or vector and always returns a list; sapply(x, f) does the same but simplifies the result to a vector or matrix when possible.

apply(m, MARGIN, f) works over a matrix or array: MARGIN = 1 applies f to each row, MARGIN = 2 to each column. mapply iterates over multiple inputs in parallel, vapply is a safer sapply with a declared return type, and tapply applies a function to groups defined by a factor.

The apply family overlaps with the tidyverse's purrr::map functions, which many now prefer for consistency. Either way, the goal is the same: vectorized, loop-free iteration that's concise and idiomatic.

Syntax

sapply(1:3, function(x) x^2)
apply(matrix, 2, sum)   # column sums

Examples

R

squares <- sapply(1:4, function(x) x^2)
print(squares)
m <- matrix(1:6, nrow = 2)
print(apply(m, 1, sum))

Output:

[1]  1  4  9 16
[1]  9 12

See also

Back to the Dictionary