01 / 20
?

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.

R Programming

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.

By Position
x[3] gets the 3rd element
By Logic
x[x > 5] gets elements greater than 5
By Name
x["age"] gets the element named "age"

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.

# Create a vector scores <- c(72, 85, 90, 61, 95, 78) # Apply a condition scores >= 80 # [1] FALSE TRUE TRUE FALSE TRUE FALSE
scores 72 85 90 61 95 78 >= 80 FALSE TRUE TRUE FALSE TRUE FALSE

Logical Subsetting in Action

Pass that logical vector inside the brackets and R returns only the elements where the condition is TRUE.

scores <- c(72, 85, 90, 61, 95, 78) # Direct logical subsetting scores[scores >= 80] # [1] 85 90 95 # Step by step: mask <- scores >= 80 # logical vector scores[mask] # same result # [1] 85 90 95

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.

scores <- c(72, 85, 90, 61, 95, 78) which(scores >= 80) # [1] 2 3 5 # Then use those indices to subset scores[which(scores >= 80)] # [1] 85 90 95
[1] [2] [3] [4] [5] [6] 72 85 90 61 95 78 which() returns 2 3 5 Integer positions, not values

The which() Syntax

which(logical_condition)
Input
A logical vector (TRUE/FALSE values), usually from a comparison like x > 10
Output
An integer vector of positions where the condition is TRUE

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

x <- c(10, NA, 30, 5, NA, 25) # Direct logical subsetting x[x > 8] # [1] 10 NA 30 NA 25 # NAs sneak in! # Using which() x[which(x > 8)] # [1] 10 30 25 # Clean result

Combining Multiple Conditions

Use logical operators to combine conditions for more precise filtering.

& AND
Both conditions must be TRUE
| OR
At least one must be TRUE
! NOT
Flips TRUE to FALSE and vice versa
ages <- c(15, 22, 17, 30, 12, 19) # AND: teens (13-19) ages[ages >= 13 & ages <= 19] # [1] 15 17 19 # OR: young or old ages[ages < 15 | ages > 25] # [1] 30 12

How to Apply Logical Subsetting

1
Identify your data. What vector or column do you want to filter?
2
Write the condition. Use comparison operators: >, <, ==, !=, >=, <=
3
Choose your method. Direct: x[condition] for quick results. Or which(condition) when you need indices or have NAs.
4
Combine if needed. Use &, |, ! for multi-condition filters.
5
Verify output. Check with length() or str() that your result makes sense.

Example 1: Filtering Grades

Task: Find all students who scored above 75 on the exam.

grades <- c(88, 65, 92, 73, 81, 77, 56) names <- c("Ali", "Bo", "Cat", "Dan", "Eve", "Fay", "Gus") # Step 1: Build the condition passed <- grades > 75 passed # [1] TRUE FALSE TRUE FALSE TRUE TRUE FALSE # Step 2: Use it to subset names[passed] # [1] "Ali" "Cat" "Eve" "Fay" grades[passed] # [1] 88 92 81 77

Example 2: which() with Data Frames

Task: Find the row numbers of students in the "A" grade range (\( \geq 90 \)).

df <- data.frame( student = c("Ali", "Bo", "Cat", "Dan"), score = c(92, 78, 95, 88) ) # Get row indices a_rows <- which(df$score >= 90) a_rows # [1] 1 3 # Subset the data frame df[a_rows, ] # student score # 1 Ali 92 # 3 Cat 95

Example 3: Complex Filtering

Task: From a temperature dataset, find days that were warm (\( > 75 \)) and not rainy.

temp <- c(68, 82, 79, 91, 73, 85) rain <- c(FALSE, TRUE, FALSE, FALSE, TRUE, FALSE) # Combine: warm AND not rainy good_days <- which(temp > 75 & !rain) good_days # [1] 3 4 6 temp[good_days] # [1] 79 91 85

Subsetting Data Frames

Data frames use two dimensions: df[rows, columns]. Logical conditions typically filter rows.

df <- data.frame( city = c("NYC", "LA", "CHI", "HOU"), pop = c(8.3, 3.9, 2.7, 2.3), coast = c(TRUE, TRUE, FALSE, TRUE) ) # Coastal cities with pop > 3 million df[df$coast & df$pop > 3, ] # city pop coast # 1 NYC 8.3 TRUE # 2 LA 3.9 TRUE # Same with which() df[which(df$coast & df$pop > 3), ]

Common Mistakes

✕ Using = instead of ==
x[x = 5] is assignment, not comparison. Always use == for equality checks.
✕ Forgetting NA traps
x[x > 5] returns NAs when data has missing values. Use which() or add & !is.na(x).
✕ Using && instead of &
&& only checks the first element. Use single & for element-wise comparison on vectors.

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?