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:
Syntax
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()
v <- c(3, 7, 2, 9, 4)
print(which(v > 4))
cat("Index of max value:", which.max(v), "\n")
Login to try C/C++/Java/PHP code in the editor
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
- Expecting
which(v > 4)to return the values, when it returns their positions; usev[v > 4]for the values. - Using
which.max(v)and expecting all positions of ties, when it returns only the first. - Forgetting that
NAvalues in the condition are ignored bywhich(), so they are silently dropped.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: