1
votes

I find people use

which(matrix==max(matrix, na.rm=FALSE)) 

to show both row and column index. But my question is how do I extract row index and column index individually and then return these two values into another parameters?

like matrix=

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

the max value is matrix[6,9]=15 how could I find row =6 and column = 9 separately and return 6 to a parameter:A, 9 to parameter:B Thank you guys very much.

2
Just use d=which(matrix==max(matrix, na.rm=F),T); rowmax=c(d)[1];colmax=c(d)[1]Onyambu
I think it should be colmax=c(d)[2] ? Thank you very much.Daniell Zhu
You are right about thatOnyambu

2 Answers

0
votes

For a large matrix which.max should be more efficient than which. So, for a matrix m, we can use

A = row(m)[d <- which.max(m)]
B = col(m)[d] 
0
votes

Maybe a roundabout way but if the matrix is called "mat":

colmax <- {which(mat == max(mat)) %/% nrow(mat)} + 1
rowmax <- which(mat == max(mat)) %% nrow(mat)