2

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.

Frank
  • 66,179
  • 8
  • 96
  • 180
DotPi
  • 3,977
  • 6
  • 33
  • 53

1 Answers1

3

In base, just index by order:

mat[order(crit$TYPE), order(crit$TYPE)]
#
#   B C E A F D
# B 0 0 5 5 9 1
# C 0 0 0 0 1 0
# E 1 5 1 3 6 2
# A 5 0 3 2 6 1
# F 0 1 7 0 9 1
# D 1 1 4 6 4 3

It orders on an alphabetical sort of crit$TYPE, so Cat (B, C, and E) comes before Dog (A and F). If you want to set the order, use factor levels:

mat[order(factor(crit$TYPE, levels = c('Dog', 'Cat', 'Other'))), 
    order(factor(crit$TYPE, levels = c('Dog', 'Cat', 'Other')))]
# 
#   A F B C E D
# A 2 6 5 0 3 1
# F 0 9 0 1 7 1
# B 5 9 0 0 5 1
# C 0 1 0 0 0 0
# E 3 6 1 5 1 2
# D 6 4 1 1 4 3
alistaire
  • 42,459
  • 4
  • 77
  • 117