which()
which(x, arr.ind = FALSE, useNames = TRUE) Returns:
integer · Updated March 13, 2026 · Base Functions base filtering indices logical
which() is a base R function that returns the indices of elements in a vector or array that are TRUE. It is essential for extracting positions of matching elements, making it a fundamental tool for data manipulation and conditional operations.
Syntax
which(x)
which(x, arr.ind = FALSE, useNames = TRUE)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | logical | required | A logical vector or array |
arr.ind | logical | FALSE | If TRUE, return array indices for matrices |
useNames | TRUE | logical | If TRUE, preserve names in the result |
Examples
Basic usage
x <- c(5, 12, 7, 8, 3)
# Find which elements are greater than 7
which(x > 7)
# [1] 2 4
Finding NA positions
y <- c(1, NA, 3, NA, 5)
# Find positions of NA values
which(is.na(y))
# [1] 2 4
Working with character vectors
words <- c("apple", "banana", "cherry", "apple")
# Find positions of "apple"
which(words == "apple")
# [1] 1 4
Using with data frames
df <- data.frame(name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 35))
# Find rows where age > 28
which(df$age > 28)
# [1] 2 3
Common Patterns
Combining with subsetting
values <- c(10, 20, 30, 40, 50)
# Get indices first, then subset
idx <- which(values > 25)
values[idx]
# [1] 30 40 50
Finding first or last match
z <- c(FALSE, FALSE, TRUE, TRUE, FALSE)
# First TRUE position
which(z)[1]
# [1] 3
# Last TRUE position
which(z)[length(which(z))]
# [1] 4
Using with which.min and which.max
numbers <- c(5, 2, 8, 1, 9)
# Find position of minimum
which.min(numbers)
# [1] 4
# Find position of maximum
which.max(numbers)
# [1] 5