对于R中的行和列名称进行矩阵对称 [英] Making a matrix symmetric with regard to row and column name in R

查看:571
本文介绍了对于R中的行和列名称进行矩阵对称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使我的矩阵对称于行名称和列名称,例如
,我有一个矩阵

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

我想让它像

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

这意味着矩阵对于row.names和列名称是对称的,因此矩阵也是对称的(实际上我正在处理邻接矩阵,
因此,相邻矩阵对称是相当重要的。

解决方案

更新

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



<如果您希望两者都使用Ananda的答案(尽管对于这种特殊情况,您会获得相同的结果)。






OLD



这是你的意思:

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

请注意,此矩阵是对称的,但这只是因为其中的数据允许这种可能性。可能有其他数据可能会产生与其他重新排序的对称矩阵,但这不是我的专长。这里我们在每一列中递增。


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).


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.

这篇关于对于R中的行和列名称进行矩阵对称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆