apply-Family
Functions in R
Master apply, lapply, sapply, tapply, and mapply as powerful alternatives to explicit loops for cleaner, more efficient R code.
What Are apply-Family Functions?
The apply family is a collection of R functions that let you perform an operation on every element of a data structure: each row of a matrix, each item in a list, or each group in a vector: without writing an explicit loop.
Think of them as a contract: "Apply this function to every piece of my data, and give me back the collected results."
Why Replace Explicit Loops?
The Big Picture: Input → Function → Output
Every apply-family function follows the same pattern: split the data into pieces, apply a function to each piece, and combine the results. The difference between them is what type of data goes in and what type comes out.
The Core Five Functions
apply(): Rows and Columns
Visualizing MARGIN in apply()
lapply() and sapply()
tapply(): Group-wise Operations
mapply(): Multiple Inputs
Loop vs apply: Side by Side
Both produce identical results. The apply version communicates its intent immediately: "sum each column." The loop version requires reading every line to understand the logic.
How to Choose the Right Function
Example 1: Column Statistics
Problem: Given a \( 4 \times 3 \) matrix of test scores, find the standard deviation of each column (each subject).
Example 2: Custom Functions with lapply
Problem: You have a list of character vectors (student names by class). Capitalize the first letter of each name.
Example 3: tapply() for Grouped Summaries
Problem: You have sales amounts and a factor indicating the region. Find the total sales per region.
Common Mistakes to Avoid
Summary Comparison Table
| Function | Input | Output | Use Case |
|---|---|---|---|
| apply() | Matrix / DF | Vector / Array | Row/column ops |
| lapply() | List / Vector | List (always) | Safe iteration |
| sapply() | List / Vector | Simplified | Quick exploration |
| tapply() | Vector + Factor | Named array | Group summaries |
| mapply() | Multiple vectors | Simplified | Parallel iteration |
Question 1 of 5
What does apply(mat, 1, sum) compute?
Question 2 of 5
Which function always returns a list, regardless of the input?
Question 3 of 5
You want to compute the mean score per department where scores is a numeric vector and dept is a factor. Which function should you use?
Question 4 of 5
What is the main risk of using sapply() inside a larger function or package?
Question 5 of 5
You need to call paste() on matching elements from three vectors: first names, middle initials, and last names. Which apply-family function is most appropriate?