Search code examples
rsortingmatrixrow

Sorting a matrix rowname based on column of another matrix


I have two matrices similar to below:

a b c d             id1   id2  id3   id4
1 2 3 4              b     1    2    3
6 7 8 9              c     0    2    4
                     d     1    2    2
                     a     5    6    8

The expected out put is as follow :

     b c d a
[1,] 2 3 4 1
[2,] 7 8 9 6

And I want to sort the row name of the left matrix according to the first column (id1) of the second matrix. Does anyone has any suggestion that how can it be processed ? I was simply trying "first matrix"[colnames("second matrix"),]. but it was not that easy.

Thanks


Solution

  • You could do

    first_mat[,second_mat[, 1]]
    
    #     b c d a
    #[1,] 2 3 4 1
    #[2,] 7 8 9 6
    

    data

    first_mat <- structure(c(1L, 6L, 2L, 7L, 3L, 8L, 4L, 9L), .Dim = c(2L, 
      4L), .Dimnames = list(
      NULL, c("a", "b", "c", "d")))
    
    second_mat <- structure(c("b", "c", "d", "a", "1", "0", "1", "5", "2", "2", 
      "2", "6", "3", "4", "2", "8"), .Dim = c(4L, 4L), .Dimnames = list(
       NULL, c("id1", "id2", "id3", "id4")))