简体   繁体   English

根据行名和列名排列矩阵

[英]Arrange a matrix with regard to the rownames and colnames

Image we have a matrix, M*N, M rows and N columns, like 图像我们有一个矩阵,M * N,M行和N列,例如

  b a d c e
a 2 1 4 3 5
b 3 2 5 4 6
c 1 3 3 2 4

I want to write a function, where take the above matrix, return the following matrix: 我想编写一个函数,在上面的矩阵中返回以下矩阵:

  a b c d e
a 1 2 3 4 5
b 2 3 4 5 6
c 3 1 2 3 4

Where the first part of the matrix M*M, 3*3 in this case is symmetric in terms of rownames and colnames, and 3*5 in total, the rest 3*2 matrix is pushed afterwards. 如果矩阵M * M的第一部分,在这种情况下3 * 3就行名和共名而言是对称的,总共3 * 5,则其余3 * 2矩阵将被推入。

For an N x M matrix where N <= M and all row names are contained in col names, this will bring the columns with names existing in row names to the front in the same order as the row names, and leave the rest of the columns in their original order after that: 对于N <= M并且所有行名都包含在列名中的N x M矩阵,这会将具有行名中存在的名称的列以与行名相同的顺序排到最前面,而其余的保留此后按原始顺序排列列:

mat_ord <- function(mx) mx[, c(rownames(mx), setdiff(colnames(mx), rownames(mx)))]
mat_ord(mx)

produces: 生产:

  a b c d e
a 1 2 3 4 5
b 2 3 4 5 6
c 3 1 2 3 4    

To see the difference, consider mx2 which has rows and columns ordered differently than mx: 要了解差异,请考虑mx2 ,其行和列的排序方式与mx不同:

  e a b d c
b 6 2 3 5 4
a 5 1 2 4 3
c 4 3 1 3 2    

And with mat_ord(mx2) we get: 并通过mat_ord(mx2)得到:

  b a c e d
b 3 2 4 6 5
a 2 1 3 5 4
c 1 3 2 4 3

UPDATE: this sorts rows and columns while ensuring symmetry on first N cols/rows: 更新:这将对行和列进行排序,同时确保前N个列/行的对称性:

mat_ord2 <- function(mx) mx[sort(rownames(mx)), c(sort(rownames(mx)), sort(setdiff(colnames(mx), rownames(mx))))]
mat_ord2(mx2)

produces: 生产:

  a b c d e
a 1 2 3 4 5
b 2 3 4 5 6
c 3 1 2 3 4

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

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