01 / 20

The Apply Family
apply / lapply / sapply

Master R's powerful apply-family functions to replace loops, process data structures elegantly, and write cleaner, faster code.

R Programming

What Are Apply Functions?

In R, the apply family is a set of functions that let you run the same operation on every element of a data structure: without writing a loop. Instead of telling R how to iterate, you tell it what to do to each piece.

apply()
Works on matrices and data frames, row-by-row or column-by-column
lapply()
Works on lists and vectors, always returns a list
sapply()
Same as lapply but tries to simplify the result to a vector or matrix

Why Not Just Use Loops?

Loops work in R, but apply functions offer key advantages. They're more concise, more readable, and often faster because R is optimized for vectorized operations.

for Loop
You manage the index, the storage, and the iteration logic manually
Apply Function
You provide the data and the function: R handles the rest automatically

The Big Picture

INPUT element 1 element 2 element 3 ... element n FUN(x) your function applied to each OUTPUT result 1 result 2 result 3 ... result n

apply(): Matrices and Data Frames

apply(X, MARGIN, FUN)
X
X: A matrix or data frame (must be 2-dimensional)
M
MARGIN: 1 = apply function to each row, 2 = apply to each column
F
FUN: The function to apply (e.g., mean, sum, or a custom function)

MARGIN = 1 vs MARGIN = 2

MARGIN = 1 (rows) 1 2 3 4 5 6 7 8 9 sum → c(6, 15, 24) MARGIN = 2 (cols) 1 2 3 4 5 6 7 8 9 sum → c(12, 15, 18)
# Row sums apply(mat, 1, sum) # → 6, 15, 24 # Column sums apply(mat, 2, sum) # → 12, 15, 18

lapply(): Lists In, Lists Out

lapply(X, FUN)

lapply stands for "list apply." It takes a list (or vector) and applies a function to every element. The result is always a list, no matter what.

# Double every number nums <- list(10, 20, 30) lapply(nums, function(x) x * 2) # → list(20, 40, 60)

sapply(): The Simplified Version

sapply(X, FUN)

sapply stands for "simplified apply." It works exactly like lapply but tries to simplify the output. If every result is a single value, you get a vector. If each result is the same length, you get a matrix.

# Same operation, simpler output nums <- list(10, 20, 30) sapply(nums, function(x) x * 2) # → c(20, 40, 60) ← vector, not list!

lapply vs sapply: The Difference

c(1, 4, 9, 16) lapply(x, sqrt) sapply(x, sqrt) list( [[1]] 1, [[2]] 2, [[3]] 3, [[4]] 4 ) Always a LIST c(1, 2, 3, 4) numeric vector Simplified VECTOR

How to Choose the Right Function

1
Identify your data. Is it a matrix/data frame, or a list/vector?
2
If matrix or data frame: use apply(). Decide MARGIN: 1 for rows, 2 for columns.
3
If list or vector: use lapply() for a guaranteed list output, or sapply() for a simplified result.
4
Write or choose your function. It can be a built-in like mean, or a custom function(x) ...
5
Check the result. Is it the shape you expected? If sapply surprises you, switch to lapply.

Example 1: Column Means with apply()

You have a matrix of student test scores. Find the average score for each subject (column).

# 3 students, 4 subjects scores <- matrix( c(85, 90, 78, 92, 88, 95, 70, 82, 88, 96, 74, 80), nrow = 3, ncol = 4 ) # Average per subject (column) apply(scores, 2, mean) # → 84.33 91.67 80.00 83.33

Example 2: Cleaning Data with lapply()

You have a list of city names with messy capitalization. Convert them all to uppercase.

# Messy city names cities <- list("new york", "los Angeles", "CHICAGO") # Clean them all at once lapply(cities, toupper) # → list("NEW YORK", "LOS ANGELES", "CHICAGO")

Example 3: Custom Functions with sapply()

Given a vector of radii, compute the area of each circle using \( A = \pi r^2 \).

# Circle radii radii <- c(1, 2, 3, 5) # Compute areas sapply(radii, function(r) pi * r^2) # → 3.14 12.57 28.27 78.54

Anonymous Functions Explained

You don't always need a named function. An anonymous function is a function you define right inside the apply call: it has no name and exists only for that moment.

# Named function approach double_it <- function(x) x * 2 sapply(1:5, double_it) # Anonymous function approach (same result!) sapply(1:5, function(x) x * 2) # → 2 4 6 8 10

Common Mistakes to Avoid

✕ Wrong MARGIN
Using MARGIN = 1 when you meant columns, or MARGIN = 2 when you meant rows. Always double-check.
✕ Forgetting Parentheses
Writing apply(mat, 2, mean()) instead of apply(mat, 2, mean). Pass the function name, don't call it.
✕ sapply Surprises
sapply may return a list if results have unequal lengths. Use lapply if you need predictable output.

Summary Comparison

apply() lapply() sapply()
Input Matrix / Data frame List / Vector List / Vector
Output Vector, array, or list Always a list Vector, matrix, or list
MARGIN? Yes (1 or 2) No No
Best for Row/column ops on 2D data Safe, predictable iteration Quick, clean results
Predictable? Depends on FUN Very predictable Can surprise you

Question 1 of 5

What does MARGIN = 2 mean in the call apply(mat, 2, sum)?

Question 2 of 5

What type of output does lapply() always return?

Question 3 of 5

Which code correctly computes the mean of each row in a matrix m?

Question 4 of 5

What is wrong with this code?
apply(mat, 2, mean())

Question 5 of 5

You run sapply(list(1:3, 1:5), length). What is the output?