Karl
Karl

Reputation: 1

Is there any method to sort the matrix by both column and row in R?

could you guys help me? I have a matrix like this. the first column and row are the IDs.

enter image description here

I need to sort it by column and row ID like this.

enter image description here

Thanks!

Upvotes: 0

Views: 42

Answers (1)

r2evans
r2evans

Reputation: 160417

Two thoughts:

mat <- matrix(1:25, nr=5, dimnames=list(c('4',3,5,2,1), c('4',3,5,2,1)))
mat
#   4  3  5  2  1
# 4 1  6 11 16 21
# 3 2  7 12 17 22
# 5 3  8 13 18 23
# 2 4  9 14 19 24
# 1 5 10 15 20 25

If you want a strictly alphabetic ordering, then this will work:

mat[order(rownames(mat)),order(colnames(mat))]
#    1  2  3 4  5
# 1 25 20 10 5 15
# 2 24 19  9 4 14
# 3 22 17  7 2 12
# 4 21 16  6 1 11
# 5 23 18  8 3 13

This will not work well if the names are intended to be ordered numerically:

mat <- matrix(1:30, nr=3, dimnames=list(c('2',1,3), c('4',3,5,2,1,6,7,8,9,10)))
mat
#   4 3 5  2  1  6  7  8  9 10
# 2 1 4 7 10 13 16 19 22 25 28
# 1 2 5 8 11 14 17 20 23 26 29
# 3 3 6 9 12 15 18 21 24 27 30
mat[order(rownames(mat)),order(colnames(mat))]
#    1 10  2 3 4 5  6  7  8  9
# 1 14 29 11 5 2 8 17 20 23 26
# 2 13 28 10 4 1 7 16 19 22 25
# 3 15 30 12 6 3 9 18 21 24 27

(1, 10, 2, ...) For that, you need a slight modification:

mat[order(as.numeric(rownames(mat))),order(as.numeric(colnames(mat)))]
#    1  2 3 4 5  6  7  8  9 10
# 1 14 11 5 2 8 17 20 23 26 29
# 2 13 10 4 1 7 16 19 22 25 28
# 3 15 12 6 3 9 18 21 24 27 30

Upvotes: 1

Related Questions