R which() function – conditional index lookup
The R which() function is used to return the index positions of elements that satisfy a condition.
which() is very commonly used in data filtering and locating specific elements.
The syntax of the which() function is as follows:
which(x, arr.ind = FALSE)
Parameter description:
xA logical vector or an expression containing a logical condition.
arr.indWhen used for matrices/arrays, whether to return row and column indices. Default is FALSE.
Example
scores <- c(55, 62, 78, 85, 92, 70, 88, 95, 60, 82)
# Find the indices of passing grades (>=60)
pass_idx <- which(scores >= 60)
print("Indices of passing students:")
print(pass_idx)
# Get the corresponding scores by indices
print("Scores of passing students:")
print(scores[pass_idx])
# Find the position of the maximum value
max_idx <- which.max(scores)
print(paste("Index of the highest score:", max_idx, "Score:", scores[max_idx]))
# Find the position of the minimum value
min_idx <- which.min(scores)
print(paste("Index of the lowest score:", min_idx, "Score:", scores[min_idx]))
# Find the indices of passing grades (>=60)
pass_idx <- which(scores >= 60)
print("Indices of passing students:")
print(pass_idx)
# Get the corresponding scores by indices
print("Scores of passing students:")
print(scores[pass_idx])
# Find the position of the maximum value
max_idx <- which.max(scores)
print(paste("Index of the highest score:", max_idx, "Score:", scores[max_idx]))
# Find the position of the minimum value
min_idx <- which.min(scores)
print(paste("Index of the lowest score:", min_idx, "Score:", scores[min_idx]))
Executing the above code produces the following output:
[1] "及格学生的索引:" [1] 2 3 4 5 6 7 8 10 [1] "及格学生的成绩:" [1] 62 78 85 92 70 88 95 82 [1] "最高分索引: 8 成绩: 95" [1] "最低分索引: 1 成绩: 55"
which() also works for matrices. Combined with arr.ind = TRUE, it can return row and column coordinates:
Example
# Create a matrix
m <- matrix(1:12, nrow = 3)
print("Matrix:")
print(m)
# Find the row and column positions of elements greater than 8
positions <- which(m > 8, arr.ind = TRUE)
print("Positions of elements greater than 8 (row, column):")
print(positions)
m <- matrix(1:12, nrow = 3)
print("Matrix:")
print(m)
# Find the row and column positions of elements greater than 8
positions <- which(m > 8, arr.ind = TRUE)
print("Positions of elements greater than 8 (row, column):")
print(positions)
Executing the above code produces the following output:
[1] "矩阵:"
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
[1] "大于 8 的元素位置(行, 列):"
row col
[1,] 1 4
[2,] 2 4
[3,] 3 3
[4,] 3 4
Other extensions
R language examples