获取矩阵每一行中最大值的列索引
问题描述:
我有一个6 x 10的矩阵,在这里我必须找到每一行中最大值的行索引和列索引.
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)
这给了我矩阵:
[,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?
谢谢
答
我们可以使用max.col
cbind(1:nrow(amat), max.col(amat, 'first'))