I have a matrix in R like this:
A B C D E F
A 2 5 0 1 3 6
B 5 0 0 1 5 9
C 0 0 0 0 0 1
D 6 1 1 3 4 4
E 3 1 5 2 1 6
F 0 0 1 1 7 9
mat = structure(c(2L, 5L, 0L, 6L, 3L, 0L, 5L, 0L, 0L, 1L, 1L, 0L, 0L,
0L, 0L, 1L, 5L, 1L, 1L, 1L, 0L, 3L, 2L, 1L, 3L, 5L, 0L, 4L, 1L,
7L, 6L, 9L, 1L, 4L, 6L, 9L), .Dim = c(6L, 6L), .Dimnames = list(
c("A", "B", "C", "D", "E", "F"), c("A", "B", "C", "D", "E",
"F")))
The matrix is not symmetric.
I want to reorder the rows and columns according to the following criteria:
NAME TYPE
A Dog
B Cat
C Cat
D Other
E Cat
F Dog
crit = structure(list(NAME = c("A", "B", "C", "D", "E", "F"), TYPE = c("Dog",
"Cat", "Cat", "Other", "Cat", "Dog")), .Names = c("NAME", "TYPE"
), row.names = c(NA, -6L), class = "data.frame")
I am trying to get the matrix rows and columns to be re-ordered, so that each category is grouped together:
A F B C E D
A
F
B
C
E
D
I am un-able to find any reasonable way of doing this.
In case it matters, or makes things simpler, I can get rid of the category 'Others' and just stick with 'Cat' and 'Dog'.
I need to find a way to write code for this re-ordering to happen as the matrix is quite big.