1

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.

ToBeGeek
  • 1,105
  • 4
  • 12
  • 20
  • 1
    Do you mean something like `ma[order(rownames(ma)), order(colnames(ma))]`? – A5C1D2H2I1M1N2O1R2T1 Feb 26 '14 at 19:01
  • Image we have an adjacency matrix for a graph, rows and columns represent nodes in the graph, suppose we sort the matrix with rownames as the same order as columns, we got a symmetric matrix naturally. – ToBeGeek Feb 26 '14 at 19:49

1 Answers1

2

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.

BrodieG
  • 51,669
  • 9
  • 93
  • 146
  • Sorry, my friend, I am talking about making it symmetric with regard to column names and rows names, so the colnames should be a,b,c,d, my row names should also be a,b,c,d. Not only sort the values in the matrix – ToBeGeek Feb 26 '14 at 19:48
  • @ToBeGeek, did this answer your previous question? – BrodieG Feb 27 '14 at 16:34
  • Yes, it does, I am posting another question how to generate strings like a1, a2, a3, a4 .... – ToBeGeek Feb 27 '14 at 16:53
  • @ToBeGeek, if it does answer your question, please consider marking it as answered. Thanks. – BrodieG Feb 27 '14 at 16:54
  • are you good in network science and statistics, I have small paid project, but need to be done quickly. – ToBeGeek Feb 27 '14 at 16:58