How to find the column and row indices of values in a matrix using which function in R?

R ProgrammingServer Side ProgrammingProgramming

To find the row and column indices of values in a matrix, we cannot simply use which function because it returns the index based on sequence of the numbers in the matrix. For example, if we have a matrix M as below −

1 2 3
4 1 6
7 8 1

Now if we try to find the index using which(M==1) then it will return 1 5 9

Because 1 is placed at 1, 5 and 9.

Hence, we need to use arr.ind = TRUE so that the matrix can be read as an array by which function.

Example

Consider the below matrix −

 Live Demo

> M<-matrix(sample(1:10,100,replace=TRUE),nrow=10)
> M

Output

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 9 5 4 5 2 7 6 7 1 1
[2,] 2 6 5 4 2 4 6 4 4 8
[3,] 10 4 9 10 8 4 4 4 5 5
[4,] 8 2 5 10 4 1 3 10 5 8
[5,] 10 1 8 9 10 10 3 8 6 10
[6,] 4 3 4 8 8 4 9 1 9 7
[7,] 5 8 1 5 5 9 9 10 8 7
[8,] 9 9 9 5 5 9 7 2 5 2
[9,] 5 6 5 6 8 9 9 10 1 9
[10,] 7 1 1 6 8 9 5 1 2 4

Finding the index for 1 to 10 values in the matrix M −

Example

> which(M==1,arr.ind=TRUE)

Output

row col
[1,] 5 2
[2,] 10 2
[3,] 7 3
[4,] 10 3
[5,] 4 6
[6,] 6 8
[7,] 10 8
[8,] 1 9
[9,] 9 9
[10,] 1 10
> which(M==2,arr.ind=TRUE)

Output

row col
[1,] 2 1
[2,] 4 2
[3,] 1 5
[4,] 2 5
[5,] 8 8
[6,] 10 9
[7,] 8 10
> which(M==3,arr.ind=TRUE)

Output

row col
[1,] 6 2
[2,] 4 7
[3,] 5 7
> which(M==4,arr.ind=TRUE)

Output

row col
[1,] 6 1
[2,] 3 2
[3,] 1 3
[4,] 6 3
[5,] 2 4
[6,] 4 5
[7,] 2 6
[8,] 3 6
[9,] 6 6
[10,] 3 7
[11,] 2 8
[12,] 3 8
[13,] 2 9
[14,] 10 10
> which(M==5,arr.ind=TRUE)

Output

row col
[1,] 7 1
[2,] 9 1
[3,] 1 2
[4,] 2 3
[5,] 4 3
[6,] 9 3
[7,] 1 4
[8,] 7 4
[9,] 8 4
[10,] 7 5
[11,] 8 5
[12,] 10 7
[13,] 3 9
[14,] 4 9
[15,] 8 9
[16,] 3 10
> which(M==6,arr.ind=TRUE)

Output

row col
[1,] 2 2
[2,] 9 2
[3,] 9 4
[4,] 10 4
[5,] 1 7
[6,] 2 7
[7,] 5 9
> which(M==7,arr.ind=TRUE)

Output

row col
[1,] 10 1
[2,] 1 6
[3,] 8 7
[4,] 1 8
[5,] 6 10
[6,] 7 10

Example

> which(M==8,arr.ind=TRUE)

Output

row col
[1,] 4 1
[2,] 7 2
[3,] 5 3
[4,] 6 4
[5,] 3 5
[6,] 6 5
[7,] 9 5
[8,] 10 5
[9,] 5 8
[10,] 7 9
[11,] 2 10
[12,] 4 10
> which(M==9,arr.ind=TRUE)

Output

row col
[1,] 1 1
[2,] 8 1
[3,] 8 2
[4,] 3 3
[5,] 8 3
[6,] 5 4
[7,] 7 6
[8,] 8 6
[9,] 9 6
[10,] 10 6
[11,] 6 7
[12,] 7 7
[13,] 9 7
[14,] 6 9
[15,] 9 10
> which(M==10,arr.ind=TRUE)

Output

row col
[1,] 3 1
[2,] 5 1
[3,] 3 4
[4,] 4 4
[5,] 5 5
[6,] 5 6
[7,] 4 8
[8,] 7 8
[9,] 9 8
[10,] 5 10
raja
Published on 07-Sep-2020 06:58:14
Advertisements