which() &
Logical Subsetting
Learn to filter and extract exactly the data you need from R vectors and data frames using logical conditions and the powerful which() function.
What is Subsetting?
Subsetting means selecting specific elements from a data structure: picking certain rows from a data frame, or certain values from a vector. In R, square brackets [ ] are your primary tool for subsetting.
The Power of Logical Vectors
When you apply a comparison operator to a vector, R returns a logical vector of the same length: a TRUE/FALSE value for every element.
Logical Subsetting in Action
Pass that logical vector inside the brackets and R returns only the elements where the condition is TRUE.
Introducing which()
The which() function takes a logical vector and returns the integer positions (indices) where the condition is TRUE: not the values themselves, but where they live.
The which() Syntax
Direct Logical vs which()
Both approaches get you the same subset values, but they work differently under the hood. Understanding the distinction matters when dealing with NA values.
| x[condition] | x[which(condition)] | |
|---|---|---|
| Returns | Values directly | Values via indices |
| NA handling | Includes NA | Skips NA |
| Typical use | Quick filtering | When you need positions |
| Speed | Slightly faster | Extra step (indices) |
The NA Difference
Combining Multiple Conditions
Use logical operators to combine conditions for more precise filtering.
How to Apply Logical Subsetting
Example 1: Filtering Grades
Task: Find all students who scored above 75 on the exam.
Example 2: which() with Data Frames
Task: Find the row numbers of students in the "A" grade range (\( \geq 90 \)).
Example 3: Complex Filtering
Task: From a temperature dataset, find days that were warm (\( > 75 \)) and not rainy.
Subsetting Data Frames
Data frames use two dimensions: df[rows, columns]. Logical conditions typically filter rows.
Common Mistakes
Summary Cheat Sheet
| Pattern | Code | Returns |
|---|---|---|
| Direct subset | x[x > 5] | Values (may include NA) |
| Get indices | which(x > 5) | Integer positions |
| Subset via which | x[which(x > 5)] | Values (NA-safe) |
| AND condition | x[a & b] | Both TRUE |
| OR condition | x[a | b] | Either TRUE |
| NOT condition | x[!a] | Opposite of a |
| Min/Max index | which.min(x) | Position of min value |
Question 1 of 5
Given x <- c(4, 9, 2, 7, 1), what does which(x > 5) return?
Question 2 of 5
Given y <- c(3, NA, 8, NA, 5), what does y[y > 4] return?
Question 3 of 5
Which operator should you use for element-wise AND when subsetting a vector?
Question 4 of 5
Given a data frame df with column age, which code correctly selects rows where age is between 18 and 25 (inclusive)?
Question 5 of 5
What does which.max(c(10, 30, 20, 30)) return?