How to find the index of n number of maximums in each row of a matrix in R?


If a matrix has multiple columns and values in each row are different then there will be number of maximums equal to the number of columns. Suppose, we want to extract the index of two maximums in each row in a matrix called M then we can use the below command −

t(apply(M,1,order,decreasing=TRUE)[1:2,]) 

Example1

Live Demo

> M1<-matrix(rpois(80,5),ncol=4)
> M1

Output

      [,1] [,2] [,3] [,4]
 [1,]    7    4    4   10
 [2,]    7    1    4    3
 [3,]    9    6    6    4
 [4,]    6    5    3    3
 [5,]    3    3    2    4
 [6,]    5    6    2    2
 [7,]    4    7    3   10
 [8,]    6    0   11    6
 [9,]    1    6    2    2
[10,]    4    9    4    9
[11,]    4   10    3    6
[12,]    3    9    3   11
[13,]    5    4    7    2
[14,]    6    7    6    6
[15,]    2    5    6    3
[16,]    2    5    8    2
[17,]    0    3    1    6
[18,]    6   10    6    4
[19,]    3    4    5    5
[20,]    4    5    8    4

Finding the index of two maximums in each of M1 −

> t(apply(M1,1,order,decreasing=TRUE)[1:2,])

Output

      [,1] [,2]
 [1,]    4    1
 [2,]    1    3
 [3,]    1    2
 [4,]    1    2
 [5,]    4    1
 [6,]    2    1
 [7,]    4    2
 [8,]    3    1
 [9,]    2    3
[10,]    2    4
[11,]    2    4
[12,]    4    2
[13,]    3    1
[14,]    2    1
[15,]    3    2
[16,]    3    2
[17,]    4    2
[18,]    2    1
[19,]    3    4
[20,]    3    2

Example2

Live Demo

> M2<-matrix(rpois(80,50),ncol=4)
> M2

Output

      [,1] [,2] [,3] [,4]
 [1,]   65   52   42   63
 [2,]   52   49   43   54
 [3,]   50   35   49   57
 [4,]   52   42   36   52
 [5,]   48   36   45   43
 [6,]   49   65   62   51
 [7,]   52   46   56   51
 [8,]   43   51   41   53
 [9,]   53   40   51   55
[10,]   52   48   48   41
[11,]   54   44   48   42
[12,]   43   34   58   54
[13,]   41   50   51   45
[14,]   47   40   56   39
[15,]   49   48   42   38
[16,]   50   56   47   56
[17,]   55   48   39   52
[18,]   49   39   48   37
[19,]   53   49   58   50
[20,]   38   57   48   59

Finding the index of two maximums in each of M2 −

> t(apply(M2,1,order,decreasing=TRUE)[1:2,])

Output

      [,1] [,2]
 [1,]    1    4
 [2,]    4    1
 [3,]    4    1
 [4,]    1    4
 [5,]    1    3
 [6,]    2    3
 [7,]    3    1
 [8,]    4    2
 [9,]    4    1
[10,]    1    2
[11,]    1    3
[12,]    3    4
[13,]    3    2
[14,]    3    1
[15,]    1    2
[16,]    2    4
[17,]    1    4
[18,]    1    3
[19,]    3    1
[20,]    4    2

Updated on: 06-Mar-2021

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements