What is the difference between apply(), lapply(), sapply(), and tapply()?

Quick Overview

Compare the R functions apply(), lapply(), sapply() and tapply() by what each one iterates over and what each one returns. Tests working knowledge of base R iteration, return types and grouped aggregation, along with the pitfalls that break R scripts in practice.

What is the difference between apply(), lapply(), sapply(), and tapply()?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What is the difference between `apply()`, `lapply()`, `sapply()`, and `tapply()`? For each function, say what it iterates over and what kind of object it returns. ```hint Two axes Compare them on the shape of the input each one walks over and on the type of object each one hands back. One of them is less predictable than the others on the second axis. ``` ### What a Strong Answer Covers - What each function iterates over: matrix margins, list elements, or groups. - What each one returns, and which one has a return type that depends on the results. - A safer alternative when the output type must be fixed. - A small example of each call. ### Follow-up Questions - What happens when you call `apply()` on a data frame with a mix of numeric and character columns? - What does `sapply()` return for an empty input, or when the function returns vectors of different lengths? How does `vapply()` help? - How would you do the same group-by aggregation as `tapply()` with `split()` plus `lapply()`, or with dplyr? - Is the apply family faster than a `for` loop in R? When would you use a vectorized function instead?

Overview: Compare the R functions apply(), lapply(), sapply() and tapply() by what each one iterates over and what each one returns. Tests working knowledge of base R iteration, return types and grouped aggregation, along with the pitfalls that break R scripts in practice.

Nov 25, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

What is the difference between apply(), lapply(), sapply(), and tapply()?

For each function, say what it iterates over and what kind of object it returns.

What a Strong Answer Covers Guidance

  • What each function iterates over: matrix margins, list elements, or groups.
  • What each one returns, and which one has a return type that depends on the results.
  • A safer alternative when the output type must be fixed.
  • A small example of each call.

Follow-up Questions Guidance

  • What happens when you call apply() on a data frame with a mix of numeric and character columns?
  • What does sapply() return for an empty input, or when the function returns vectors of different lengths? How does vapply() help?
  • How would you do the same group-by aggregation as tapply() with split() plus lapply() , or with dplyr?
  • Is the apply family faster than a for loop in R? When would you use a vectorized function instead?