What is the use of the which() function in R?

Quick Overview

Asks what the which() function in R returns and when to use it instead of a logical mask. Tests knowledge of index positions, NA handling, which.max and which.min, matrix indices with arr.ind, and the edge cases that cause subsetting bugs.

What is the use of the which() function in R?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What is the use of the `which()` function in R? Explain what it returns, the related helper functions, and when you would use it instead of indexing with a logical vector directly. ```hint Compare two subsets Take a vector that contains an `NA` and compare `x[x > 5]` with `x[which(x > 5)]`. Then think about what `which()` returns when no element matches. ``` ### What a Strong Answer Covers - What `which()` takes as input and what it returns, including how it treats `NA` - The helpers `which.max()` and `which.min()`, and the `arr.ind` argument for matrices - When you need positions and when a logical mask is enough - The practical differences between subsetting with `which()` and with a logical vector, including an edge case that causes bugs ### Follow-up Questions - Why can `x[-which(x > 10)]` return an empty vector, and how would you write it safely? - If a vector has several elements equal to its maximum, what does `which.max()` return, and how would you get all of them? - How would you find the row and column of every negative value in a matrix? - What is the difference between `which(x == 8)[1]` and `match(8, x)`?

Overview: Asks what the which() function in R returns and when to use it instead of a logical mask. Tests knowledge of index positions, NA handling, which.max and which.min, matrix indices with arr.ind, and the edge cases that cause subsetting bugs.

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

What is the use of the which() function in R? Explain what it returns, the related helper functions, and when you would use it instead of indexing with a logical vector directly.

What a Strong Answer Covers Guidance

  • What which() takes as input and what it returns, including how it treats NA
  • The helpers which.max() and which.min() , and the arr.ind argument for matrices
  • When you need positions and when a logical mask is enough
  • The practical differences between subsetting with which() and with a logical vector, including an edge case that causes bugs

Follow-up Questions Guidance

  • Why can x[-which(x > 10)] return an empty vector, and how would you write it safely?
  • If a vector has several elements equal to its maximum, what does which.max() return, and how would you get all of them?
  • How would you find the row and column of every negative value in a matrix?
  • What is the difference between which(x == 8)[1] and match(8, x) ?