Home > Back-end >  how to return matrix elements indexes for its values when sorted in R
how to return matrix elements indexes for its values when sorted in R

Time:09-17

let mymat be:

      [,1]  [,2]  [,3]  [,4]
[1,]  9.39  7.32  2.92 11.17
[2,] 10.16 12.85  3.23 10.81
[3,]  8.56  5.21 12.62 11.05

which is,

set.seed(1000)
mymat <- matrix(round(runif(12, min=1, max=15),2), nrow = 3, ncol = 4, byrow = TRUE)

I can get the index of max and min elements of mymat using arrayInd(). but what I need and I do not know how to get it neatly is, getting row-col index of ALL elements of matrix from the largest element to the smallest. something like:

 2 2   #index for max element which is 12.85 here
 3 3   # index for next largest value
 1 4   # index for next largest value
 .
 .
 .

CodePudding user response:

We could melt the matrix into long format data.frame which returns by default the row and column index as the first two column and the last column with 'value'. Now, it is easier to arrange the 'value' in descending order and select only the index columns

library(reshape2)
library(dplyr)
melt(mymat) %>% 
    arrange(desc(value)) %>% 
    select(-value)

-output

    Var1 Var2
1     2    2
2     3    3
3     1    4
4     3    4
5     2    4
6     2    1
7     1    1
8     3    1
9     1    2
10    3    2
11    2    3
12    1    3

If the matrix have dimnames attributes, the melt returns the first columns as the row/column names. But, if we want to remove those, then set the dimnames to NULL e.g.

dimnames(mymat) <- list(paste0("r-", 1:3), paste0("c-", 1:4))
dimnames(mymat) <- NULL

or using base R, create an index of the matrix elements with order, use to order the row and col indexes

i1 <- order(-mymat)
cbind(row(mymat)[i1], col(mymat)[i1])
   [,1] [,2]
 [1,]    2    2
 [2,]    3    3
 [3,]    1    4
 [4,]    3    4
 [5,]    2    4
 [6,]    2    1
 [7,]    1    1
 [8,]    3    1
 [9,]    1    2
[10,]    3    2
[11,]    2    3
[12,]    1    3

data

mymat <- structure(c(9.39, 10.16, 8.56, 7.32, 12.85, 5.21, 2.92, 3.23, 
12.62, 11.17, 10.81, 11.05), .Dim = 3:4)
  • Related