The apply family runs a function repeatedly over a vector, list, matrix, or data frame — usually replacing a for loop with a single, more readable line of code.
sapply() — Simplify Result to a Vector
R Code
nums <- list(1:3, 4:6, 7:9) sapply(nums, sum) sapply(1:5, function(x) x^2)
Output
[1] 6 15 24 [1] 1 4 9 16 25
lapply() — Always Returns a List
R Code
lapply(1:3, function(x) x * 10)
Output
[[1]] [1] 10 [[2]] [1] 20 [[3]] [1] 30
💡 Tip
sapply() and lapply() do the exact same computation - the only difference is the output shape. Use sapply() when you want a clean vector/matrix, and lapply() when the results are different lengths or types and a list is more appropriate.apply() — Row or Column Operations on a Matrix
R Code
m <- matrix(1:6, nrow = 2) m apply(m, 1, sum) # MARGIN=1: row sums apply(m, 2, mean) # MARGIN=2: column means
Output
[,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [1] 9 12 [1] 1.5 3.5 5.5
mapply() — Apply Over Several Vectors in Parallel
R Code
a <- c(1, 2, 3) b <- c(10, 20, 30) mapply(function(x, y) x + y, a, b)
Output
[1] 11 22 33
vapply() — sapply() with a Guaranteed Output Type
vapply() works like sapply() but forces you to declare the expected output type, which prevents silent surprises in production code.
R Code
vapply(1:5, function(x) x^2, FUN.VALUE = numeric(1))
Output
[1] 1 4 9 16 25
Advanced: Applying a Function to Every Column of a Data Frame
🚀 Advanced Example
sapply() over a data frame automatically treats each column as one element - a very common pattern for column-wise summaries.R Code
df <- data.frame(a = c(1,2,3), b = c(10,20,30)) sapply(df, mean) sapply(df, function(col) max(col) - min(col)) # range per column
Output
a b 2.0 20.0 a b 2 20
Key Points
- sapply() simplifies to a vector/matrix when possible; lapply() always returns a list.
- apply(m, MARGIN, f) applies f across rows (MARGIN=1) or columns (MARGIN=2) of a matrix or data frame.
- mapply() applies a function across several vectors in parallel, element by element.
- vapply() is a safer sapply() that enforces an expected output type.