【问题标题】:Is there any method to sort the matrix by both column and row in R?有什么方法可以按 R 中的列和行对矩阵进行排序?
【发布时间】:2020-03-22 05:44:23
【问题描述】:

你们能帮帮我吗? 我有一个这样的矩阵。第一列和第一行是 ID。

我需要像这样按列和行 ID 对其进行排序。

谢谢!

【问题讨论】:

  • mat[as.character(1:5), as.character(1:5)]

标签: r sorting matrix


【解决方案1】:

两个想法:

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

如果您想要严格的字母顺序,那么这将起作用:

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

如果名称要按数字排序,这将无法正常工作:

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, ...) 为此,您需要稍作修改:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多