apply(), sapply(), lapply(), and mapply() iterate without explicit for loops—precursors to purrr (local) in tidyverse.
sapply on vectors
nums <- c(1, 2, 3, 4)
print(sapply(nums, function(x) x * 2))
apply on matrices
m <- matrix(1:6, nrow = 2)
print(apply(m, 1, sum)) # row sums
Margin 1 = rows, 2 = columns—read apply docs carefully.
Important interview questions and answers
- Q: sapply vs lapply?
A: lapply always returns a list; sapply tries to simplify to vector/matrix. - Q: When vectorization enough?
A: Prefer vectorized ops over apply when native—apply shines on complex row/column logic.
Self-check
- What margin sums rows in apply?
- What does sapply return for a numeric vector input?
Tip: Check whether native vectorization already does the job before reaching for apply.
Interview prep
- apply margins?
1 = rows, 2 = columns on matrices.