← Back to R Course | Chapter 3: Vectors | Lesson 7 of 7

Logical Indexing

In this page:

  1. Logical Indexing

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

markup
v <- c(2, 8, 5, 10, 3)

print(v > 5)
print(v[v > 5])

evens <- v[v %% 2 == 0]
print(evens)
🔒

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.