问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/22050666/making-a-matrix-symmetric-with-regard-to-row-and-column-name-in-r