← Back to R Course | Chapter 7: Data Structures | Lesson 6 of 7

which()

which tells you the positions where a condition is true, like asking 'which seats are taken?'. It gives you the seat numbers instead of the answers.

In this page:

  1. which()
Syntax
r
which(condition)
vector_name[which(condition)]

which()

which(condition) returns the *indices* where a logical vector is TRUE, rather than the values themselves.

This is useful when you need to know the position of matching elements, not just filter them out. which.max() and which.min() are shortcuts for finding the index of the largest/smallest value.

Note: which.max(v) is a shortcut for which(v == max(v))[1], finding the position of the largest value in one call.

Example: which()

markup
v <- c(3, 7, 2, 9, 4)

print(which(v > 4))
cat("Index of max value:", which.max(v), "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting which(v > 4) to return the values, when it returns their positions; use v[v > 4] for the values.
  2. Using which.max(v) and expecting all positions of ties, when it returns only the first.
  3. Forgetting that NA values in the condition are ignored by which(), so they are silently dropped.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.