简体   繁体   English

使矩阵关于R中的行和列名称对称

[英]Making a matrix symmetric with regard to row and column name in R

I want to make my matrix symmetric with regard to the row names and columns names, for example, I have a matrix 我想使我的矩阵关于行名和列名对称,例如,我有一个矩阵

  > ma   
     a  b  c  d
  a  1  5  9 13
  c  9 10 11 15
  b  5  6 10 14
  d 13 14 15 16

I want to make it like 我想让它像

  > ma   
     a  b  c  d
  a  1  5  9 13
  b  5  6 10 14
  c  9 10 11 15
  d 13 14 15 16

Which means the matrix is symmetric in terms of row.names and column names are equal, so as the matrix is symmetric as well (actually I am working on adjacency matrix, thus it is rather important for adjacency matrix to be symmetric. 这意味着矩阵在行名称和列名称方面是对称的,因此矩阵也是对称的(实际上我正在处理邻接矩阵,因此邻接矩阵对称是相当重要的。

Update 更新

ma[colnames(ma), ]
#    a  b  c  d
# a  1  5  9 13
# b  5  6 10 14
# c  9 10 11 15
# d 13 14 15 16

This will work assuming your matrix is square and your rownames are the same as your colnames. 假设您的矩阵是正方形并且行名与您的姓氏相同,这将起作用。 If you want both of them sorted use Ananda's answer (though for this particular case you get the same result). 如果要对它们都进行排序,请使用Ananda的答案(尽管在这种情况下,您得到的结果相同)。


OLD

Is this what you mean: 你是这个意思吗:

ma[] <- apply(ma, 2, sort)
#    a  b  c  d
# a  1  5  9 13
# c  5  6 10 14
# b  9 10 11 15
# d 13 14 15 16

Note that this matrix is symmetric, but that's only because the data in it allows the possibility. 请注意,此矩阵是对称的,但这仅仅是因为其中的数据允许这种可能性。 There may be other data that could create symmetric matrices with other re-ordering, but this is not my expertise. 可能还有其他数据可以通过其他重新排序来创建对称矩阵,但这不是我的专长。 Here we order ascending within each column. 在这里,我们在每一列中按升序排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM