What is the MARGIN argument in apply() and how does it control row versus column operations?

Quick Overview

Asks what the MARGIN argument of R's apply() function does and how it switches between row-wise, column-wise and element-wise operations. Tests understanding of matrix dimensions, the shape of the returned result, and faster built-in alternatives.

What is the MARGIN argument in apply() and how does it control row versus column operations?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

In R, what is the `MARGIN` argument in `apply()` and how does it control row versus column operations? ```hint Track the dimensions Write out a small 2 x 3 matrix and ask which of its dimensions survives in the result for each `MARGIN` value. Then check what happens when the function returns more than one number. ``` ### What a Strong Answer Covers - The values `MARGIN` can take and what the function receives for each - How `MARGIN` relates to `dim()` and to the shape of the result - A small worked example with its output - How the result is laid out when the function returns several values per row or column - Faster built-in alternatives, and what `apply()` does to a data frame ### Follow-up Questions - Why does `apply(m, 1, function(r) r / sum(r))` come back transposed, and how would you fix it? - What happens when you call `apply()` on a data frame that has a character column? - How would you use `MARGIN` on a three-dimensional array? - When would you use `sapply()`, `lapply()` or `sweep()` instead of `apply()`?

Overview: Asks what the MARGIN argument of R's apply() function does and how it switches between row-wise, column-wise and element-wise operations. Tests understanding of matrix dimensions, the shape of the returned result, and faster built-in alternatives.

PracHub logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

In R, what is the MARGIN argument in apply() and how does it control row versus column operations?

What a Strong Answer Covers Guidance

  • The values MARGIN can take and what the function receives for each
  • How MARGIN relates to dim() and to the shape of the result
  • A small worked example with its output
  • How the result is laid out when the function returns several values per row or column
  • Faster built-in alternatives, and what apply() does to a data frame

Follow-up Questions Guidance

  • Why does apply(m, 1, function(r) r / sum(r)) come back transposed, and how would you fix it?
  • What happens when you call apply() on a data frame that has a character column?
  • How would you use MARGIN on a three-dimensional array?
  • When would you use sapply() , lapply() or sweep() instead of apply() ?