Search code examples
rmatrixranking

R: Create a list of combinations of row names and column names and rank them


I have two matrices:

matrix1:

     col1   col2
row1  5      4

row2  4      6




matrix2:

     col1   col2
row1  48     50

row2  47     46

What I want is a new matrix or table:

          Dim1   Dim2   rank
row2col1   4      47     1
row1col2   4      50     2
row1col1   5      48     3
row2col2   6      46     4

As you can see, I want to rank different combinations of rows and columns first based on dim1, and if there is a tie, by using dim2. The result matrix must be sorted using this rank. How can I achieve it? It is worth noting that matrix1 and 2 contains values for the dim1 and dim2 and have exactly the same column and row names.


Solution

  • Assuming there are no duplicate rows:

    a <- array(c(5,4,4,6,48,47,50,46),c(2,2,2))
    dimnames(a) <- list(c("row1", "row2"), c("col1", "col2"), c("m1", "m2"))
    # , , m1
    # 
    # col1 col2
    # row1    5    4
    # row2    4    6
    # 
    # , , m2
    # 
    # col1 col2
    # row1   48   50
    # row2   47   46
    
    library(reshape2)
    b <- acast(melt(a), Var1+Var2~Var3)
    b <- b[order(b[,1], b[,2]),]
    

    Or for an arbitrary number of columns:

    b <- b[do.call(order, lapply(seq_len(ncol(b)), function(i) b[,i])),]
    #add ranks
    b <- cbind(b, rank=seq_len(nrow(b)))
    
    #           m1 m2 rank
    # row2_col1  4 47    1
    # row1_col2  4 50    2
    # row1_col1  5 48    3
    # row2_col2  6 46    4