如何在 R 矩阵中找到最小值和最大值的行列号?
一个矩阵可以有一个或多个最小值和最大值。此外,矩阵的大小可以只有一列和多行,也可以有数千列和数千行。矩阵中最小值和最大值的行列号可以使用以下语法找到 -
对于最大值
which(“Matrix_Name”==min(“Matrix_Name”),arr.ind=TRUE)
对于最小值>
which(“Matrix_Name”==max(“Matrix_Name”),arr.ind=TRUE)
示例
M1<-matrix(1:25,ncol=5) M1 [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25 which(M1==max(M1),arr.ind=TRUE) row col [1,] 5 5 which(M1==min(M1),arr.ind=TRUE) row col [1,] 1 1 M2<-matrix(rnorm(25),ncol=5) M2 [,1] [,2] [,3] [,4] [,5] [1,] -1.4194231 0.5835903 1.4665574 -1.6387592 0.7048224 [2,] 0.3352523 -0.2876772 1.1042358 -0.1989225 0.7347379 [3,] -1.5743547 0.4834883 -1.1198968 -0.6436345 -0.1437520 [4,] -2.1785618 1.6925537 1.5120286 -1.0856419 2.5269400 [5,] 0.9766656 2.0222188 -0.2966057 -0.1720232 -0.2257814 which(M2==max(M2),arr.ind=TRUE) row col [1,] 4 5 which(M2==min(M2),arr.ind=TRUE) row col [1,] 4 1 M3<-matrix(rnorm(25,2.5),ncol=5) M3 [,1] [,2] [,3] [,4] [,5] [1,] 3.670105 3.256981 1.925999 2.9184274 1.728779 [2,] 3.765994 3.205739 3.695557 4.0209779 2.434685 [3,] 1.748879 2.480154 3.676999 2.0010259 3.159799 [4,] 1.582952 2.676389 2.396969 0.3748771 1.165021 [5,] 1.720008 2.329690 2.409057 3.8057733 3.965829 which(M3==max(M3),arr.ind=TRUE) row col [1,] 2 4 which(M3==min(M3),arr.ind=TRUE) row col [1,] 4 4 M4<-matrix(rpois(36,2),ncol=6) M4 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 2 2 1 3 1 1 [2,] 3 1 0 1 0 3 [3,] 0 1 4 1 4 2 [4,] 1 3 2 1 1 4 [5,] 1 2 0 1 2 1 [6,] 1 1 0 3 0 2 which(M4==max(M4),arr.ind=TRUE) row col [1,] 3 3 [2,] 3 5 [3,] 4 6 which(M4==min(M4),arr.ind=TRUE) row col [1,] 3 1 [2,] 2 3 [3,] 5 3 [4,] 6 3 [5,] 2 5 [6,] 6 5 M5<-matrix(rpois(36,10),ncol=6) M5 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 11 10 13 10 10 8 [2,] 9 8 10 8 8 9 [3,] 8 11 8 7 9 10 [4,] 6 15 5 14 6 8 [5,] 11 7 11 9 8 12 [6,] 9 15 17 11 7 14 which(M5==max(M5),arr.ind=TRUE) row col [1,] 6 3 which(M5==min(M5),arr.ind=TRUE) row col [1,] 4 3 M6<-matrix(runif(36,2,5),ncol=6) M6 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3.652903 2.144873 4.801257 2.941041 4.132117 3.925266 [2,] 3.819255 2.695592 4.610663 2.062571 4.881452 3.256637 [3,] 2.203137 2.821375 2.481268 2.069606 4.042738 4.101515 [4,] 2.499690 3.593453 4.813508 2.304928 2.285617 3.713846 [5,] 3.684496 2.369803 4.974936 4.422779 2.097394 4.059585 [6,] 3.573778 3.780176 3.772600 2.699202 2.060818 2.948795 which(M6==max(M6),arr.ind=TRUE) row col [1,] 5 3 which(M6==min(M6),arr.ind=TRUE) row col [1,] 6 5
广告