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.
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.
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.
The Big Picture
apply(): Matrices and Data Frames
MARGIN = 1 vs MARGIN = 2
lapply(): Lists In, Lists Out
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.
sapply(): The Simplified Version
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.
lapply vs sapply: The Difference
How to Choose the Right Function
Example 1: Column Means with apply()
You have a matrix of student test scores. Find the average score for each subject (column).
Example 2: Cleaning Data with lapply()
You have a list of city names with messy capitalization. Convert them all to uppercase.
Example 3: Custom Functions with sapply()
Given a vector of radii, compute the area of each circle using \( A = \pi r^2 \).
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.
Common Mistakes to Avoid
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?