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:
-
x A logical vector or an expression containing a logical condition.
-
arr.ind When used with a matrix/array, whether to return row and column indices, defaults to FALSE.
Example
scores
<-
c
(
55
,
62
,
78
,
85
,
92
,
70
,
88
,
95
,
60
,
82
)
Find the indices of passing scores (>=60)
pass_idx
<-
which
(
scores
=
60
)
(
"Indices of passing students:"
)
(
pass_idx
)
Get the corresponding scores by index
(
"Scores of passing students:"
)
(
scores
[
pass_idx
]
)
Find the position of the maximum value
max_idx
<-
which.max
(
scores
)
(
paste
(
"Index of the highest score:"
, max_idx,
"Scores:"
, scores
[
max_idx
]
)
)
Find the position of the minimum value
min_idx
<-
which.min
(
scores
)
(
paste
(
"Index of the lowest score:"
, min_idx,
"Scores:"
, scores
[
min_idx
]
)
)
The output of the code above is:
[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 with matrices; combined with arr.ind = TRUE it can return row and column coordinates:
Example
Create a matrix
m
<-
matrix
(
1
:
12
,
nrow
=
3
)
(
"Matrix:"
)
(
m
)
Find the row and column positions of elements greater than 8
positions
<-
which
(
m
8
, arr.
ind
=
TRUE
)
(
"Positions of elements greater than 8 (row, column):"
)
(
positions
)
The output of the code above is:
[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
R Language Examples