01 / 22

apply-Family
Functions in R

Master apply, lapply, sapply, tapply, and mapply as powerful alternatives to explicit loops for cleaner, more efficient R code.

R Programming

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?

Readability
One line replaces 4-6 lines of loop boilerplate: initialization, indexing, and accumulation disappear.
Fewer Bugs
No off-by-one errors, no forgotten pre-allocation, no accidental overwrites of the loop variable.
Idiomatic R
R was designed for vectorized operations. Using apply-family functions follows R's core philosophy and conventions.

The Big Picture: Input → Function → Output

INPUT Matrix, List, Vector, Data Frame apply-Family Splits data into pieces, applies FUN to each piece, collects results OUTPUT Vector, List, Matrix, Array FUN (your function) Split → Apply → Combine

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()
Matrices and data frames: apply a function to each row or column.
lapply()
Lists and vectors: returns a list of results, always.
sapply()
Like lapply, but simplifies the result to a vector or matrix when possible.
tapply()
Applies a function to groups defined by a factor: split-apply-combine by category.
mapply()
The multivariate version: applies a function to matching elements of multiple inputs.

apply(): Rows and Columns

# Syntax apply(X, MARGIN, FUN) # MARGIN = 1 → apply FUN to each ROW # MARGIN = 2 → apply FUN to each COLUMN mat <- matrix(1:12, nrow = 3) apply(mat, 1, sum) # Row sums: 22, 26, 30 apply(mat, 2, mean) # Column means: 2, 5, 8, 11

Visualizing MARGIN in apply()

Col 1 Col 2 Col 3 Col 4 1 4 7 10 2 5 8 11 3 6 9 12 sum → 22 MARGIN = 1 (rows) 1 2 3 4 5 6 7 8 9 mean → 2 MARGIN = 2 (cols) Col 1 Col 2 Col 3

lapply() and sapply()

# lapply: always returns a LIST nums <- list(a = 1:5, b = 6:10, c = 11:15) lapply(nums, mean) # $a [1] 3 $b [1] 8 $c [1] 13 # sapply: simplifies to a named vector sapply(nums, mean) # a b c # 3 8 13
lapply()
Safe and predictable: always returns a list. Great inside other functions where you need a guaranteed type.
sapply()
Convenient for interactive use: simplifies to a vector or matrix. But the return type can surprise you.

tapply(): Group-wise Operations

# Syntax: tapply(X, INDEX, FUN) # Split vector X by factor INDEX, apply FUN to each group scores <- c(88, 92, 76, 95, 81, 89) subject <- c("Math", "Sci", "Math", "Sci", "Math", "Sci") tapply(scores, subject, mean) # Math Sci # 81.67 92.00

mapply(): Multiple Inputs

# mapply: multivariate sapply # Syntax: mapply(FUN, ..., MoreArgs) mapply(rep, 1:4, 4:1) # rep(1,4) → 1 1 1 1 # rep(2,3) → 2 2 2 # rep(3,2) → 3 3 # rep(4,1) → 4 # Weighted average example values <- c(10, 20, 30) weights <- c(0.2, 0.3, 0.5) mapply(function(v, w) v * w, values, weights) # 2 6 15

Loop vs apply: Side by Side

Explicit Loop result <- numeric(ncol(mat)) for (j in 1:ncol(mat)) { total <- 0 for (i in 1:nrow(mat)) { total <- total + mat[i,j] } result[j] <- total } 8 lines of code apply() Version apply(mat, 2, sum) 1 line of code vs

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

1
Identify your input type. Matrix or data frame? Use apply(). List or vector? Use lapply() or sapply().
2
Decide on your output type. Need a guaranteed list? Use lapply(). Want automatic simplification? Use sapply().
3
Grouping by a factor? Use tapply(). It's like doing apply but split by categories.
4
Multiple parallel inputs? Use mapply(). It zips multiple vectors together element-by-element.
5
Write and test FUN separately before plugging it in. Use anonymous functions for short operations.

Example 1: Column Statistics

Problem: Given a \( 4 \times 3 \) matrix of test scores, find the standard deviation of each column (each subject).

# Create the matrix scores <- matrix( c(85, 92, 78, 90, 88, 76, 95, 82, 91, 84, 87, 93), nrow = 4 ) # Apply sd() to each column (MARGIN = 2) apply(scores, 2, sd) # [1] 6.24 8.14 4.03

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.

classes <- list( bio = c("alice", "bob"), chem = c("carol", "dave", "eve") ) cap_first <- function(x) { paste0(toupper(substr(x,1,1)), substr(x,2,nchar(x))) } lapply(classes, cap_first) # $bio [1] "Alice" "Bob" # $chem [1] "Carol" "Dave" "Eve"

Example 3: tapply() for Grouped Summaries

Problem: You have sales amounts and a factor indicating the region. Find the total sales per region.

sales <- c(120, 340, 210, 450, 180, 290) region <- c("East", "West", "East", "West", "East", "West") tapply(sales, region, sum) # East West # 510 1080 # Equivalent loop version: result <- c() for (r in unique(region)) { result[r] <- sum(sales[region == r]) } # 4 lines vs 1 line

Common Mistakes to Avoid

✕ Wrong MARGIN in apply()
Using MARGIN=1 when you mean columns (MARGIN=2). Remember: 1=rows, 2=columns. Think of the dimension you keep.
✕ Using sapply() in production
sapply() can return a list, vector, or matrix depending on the result. Use vapply() or lapply() for predictable return types.
✕ Mishandling Function Arguments
Don't call the function inside the apply call, e.g., lapply(x, mean(trim=0.1)). This is an error. Instead, pass extra arguments directly: lapply(x, mean, trim = 0.1).

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?