Logical Indexing
Logical indexing keeps only the items that pass a true-or-false test, like a sieve that lets through only the ones you want. You describe the rule and R filters the list.
In this page:
Syntax
vector_name[vector_name > value]
vector_name[condition]
Logical Indexing
A vector can be indexed with a logical vector of the same length, selecting only the elements where the corresponding value is TRUE.
This is commonly built from a comparison, like v[v > 5], to filter a vector based on a condition. Logical indexing is one of R's most powerful and frequently used idioms.
Note:
v[v > 5] reads almost like English: "give me the elements of v that are greater than 5".
Example: Logical Indexing
v <- c(2, 8, 5, 10, 3)
print(v > 5)
print(v[v > 5])
evens <- v[v %% 2 == 0]
print(evens)
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
- Writing
v[v > 5, ]with a comma on a vector, which gives an error about incorrect dimensions. - Using
&&in place of&inv[v > 2 && v < 8], which only uses the first element and, in recent R versions, gives an error. - Having
NAvalues in the vector, sov[v > 5]returnsNAentries for those positions.
Chapter Summary
- Vectors hold several values of one type, created with
c()and other constructors. - Vector arithmetic works on whole vectors at once, and indexing selects elements by position, name, or logical condition.
- Named vectors and vector functions help you label and summarize data.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: