5

I have a 6 x 10 matrix where I have to find the row index and column index of the maximum value in each row.

set.seed(75)
amat <- matrix( sample(10, size=60, replace=T), nrow=6)

which gives me the 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   10     1

Now, I want to navigate row by row, and get the row index and column index of the maximum value in each row.

To get the maximum value in each row, I did:

apply(amat,1,max)
[1]  7 10 10  9  9 10

How do I get the row and column indices of the first occurrence of the maximum value?

Thanks

Pierre L
  • 28,203
  • 6
  • 47
  • 69
Balaji Suresh
  • 55
  • 1
  • 10
  • Some similar posts: [(1)](http://stackoverflow.com/questions/11636620/how-to-return-a-vector-containing-the-labels-of-the-maximum), [(2)](http://stackoverflow.com/questions/8220343/is-there-something-like-a-pmax-index), [(3)](http://stackoverflow.com/questions/15094861/how-does-one-lookup-of-max-value-in-matrix) – alexis_laz Mar 22 '16 at 13:43

1 Answers1

11

We can use max.col

 cbind(1:nrow(amat), max.col(amat, 'first'))
akrun
  • 874,273
  • 37
  • 540
  • 662