Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R which() Function - Conditional Index Lookup

R which() Function - Conditional Index Lookup

R Language Examples R Language Examples

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:

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

)

print

(

"Indices of passing students:"

)

print

(

pass_idx

)

Get the corresponding scores by index

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,

"Scores:"

, scores

[

max_idx

]

)

)

Find the position of the minimum value

min_idx

<-

which.min

(

scores

)

print

(

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

)

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

)

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 R Language Examples