Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column index of maximum value in each Row of matrix

Tags:

r

matrix

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

like image 502
Balaji Suresh Avatar asked Mar 22 '16 13:03

Balaji Suresh


1 Answers

We can use max.col

 cbind(1:nrow(amat), max.col(amat, 'first'))
like image 141
akrun Avatar answered Nov 15 '22 10:11

akrun