1
votes

hello I have two matrix

Matrix1

   C1 C2 C3 C4
R1 1  2  3  4
R2 5  6  7  8
R3 9  10 11 12
R4 13 14 15 16

and another one with the same colnames and rownames but order as I would like:

Matrix2

   C2 C1 C4 C3
R1 A  B  C  D
R3 E  F  G  H
R4 I  J  K  L
R2 M  N  O  P

and from this one I would like to order to Matrix1 in the same way and get:

   C2 C1 C4 C3
R1 1  1  4  3
R3 9  9  12 11
R4 13 13 16 15
R2 6  5  8  7

thanks for your help

2

2 Answers

2
votes

You can extract rownames and colnames from mat2 and use it to order mat1.

mat1[rownames(mat2),colnames(mat2)]

#   C2 C1 C4 C3
#R1  2  1  4  3
#R3 10  9 12 11
#R4 14 13 16 15
#R2  6  5  8  7

data

mat1 <- structure(c(1L, 5L, 9L, 13L, 2L, 6L, 10L, 14L, 3L, 7L, 11L, 15L, 
4L, 8L, 12L, 16L), .Dim = c(4L, 4L), .Dimnames = list(c("R1", 
"R2", "R3", "R4"), c("C1", "C2", "C3", "C4")))

mat2 <- structure(c("A", "E", "I", "M", "B", "F", "J", "N", "C", "G", 
"K", "O", "D", "H", "L", "P"), .Dim = c(4L, 4L), .Dimnames = list(
c("R1", "R3", "R4", "R2"), c("C2", "C1", "C4", "C3")))
1
votes

you can do this:

Matrix1 = matrix(1:16, 4, 4, dimnames = list(c('R1', 'R2', 'R3', 'R4'),
                                             c('C1', 'C2', 'C3', 'C4')))

Matrix2 = matrix(data = c('A', 'B', 'C', 'D',
                          'E', 'F', 'G', 'H',
                          'I', 'J', 'K', 'L',
                          'M', 'N', 'O', 'P'),
                 nrow = 4,
                 ncol = 4,
                 dimnames = list(c('R1', 'R3', 'R4', 'R2'),
                                 c('C2', 'C1', 'C4', 'C3')))

Matrix1[rownames(Matrix2), colnames(Matrix2)]