Logical Indexing
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: