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

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:

  1. Logical Indexing
Syntax
r
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

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

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

evens <- v[v %% 2 == 0]
print(evens)
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. Writing v[v > 5, ] with a comma on a vector, which gives an error about incorrect dimensions.
  2. Using && in place of & in v[v > 2 && v < 8], which only uses the first element and, in recent R versions, gives an error.
  3. Having NA values in the vector, so v[v > 5] returns NA entries 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:

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.