根据每行中列的相对顺序对矩阵中的行进行排序

Cod*_*Guy 2 r matrix

我在R中有一个矩阵,有N行和6列.我想按行的最大值对行进行排序.

具体来说,我想首先确定第1列中具有最高值(针对该行)的所有行,并且这些行应首先出现在矩阵中.接下来,我想识别第2列中具有最高值的所有行(对于该行),并且这些行应该出现在矩阵的下一行中.等等.

我怎样才能做到这一点?


示例案例:假设我有矩阵

1 2 3 4 5 6
3 5 4 4 3 5
7 1 2 3 2 4
Run Code Online (Sandbox Code Playgroud)

然后排序的结果将第一行放在最后,因为它的最高值是在最后一列.它会将第3行放在第一行,因为它的最高值位于第一列.它会将中间行放在中间,因为它的最高值是在第二列.结果:

7 1 2 3 2 4
3 5 4 4 3 5
1 2 3 4 5 6
Run Code Online (Sandbox Code Playgroud)

the*_*ail 6

使用max.colorder:

mat[ order(max.col(mat, "first")), ]

#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    7    1    2    3    2    4
#[2,]    3    5    4    4    3    5
#[3,]    1    2    3    4    5    6
Run Code Online (Sandbox Code Playgroud)

哪里mat是:

mat <- structure(c(1L, 3L, 7L, 2L, 5L, 1L, 3L, 4L, 2L, 4L, 4L, 3L, 5L, 
3L, 2L, 6L, 5L, 4L), .Dim = c(3L, 6L))
Run Code Online (Sandbox Code Playgroud)

它有效,因为它计算:

\ 1.每行中最大值的列位置:

max.col(mat, "first")
#[1] 6 2 1
Run Code Online (Sandbox Code Playgroud)

\ 2.基于这些最大值的行的顺序:

order(max.col(mat, "first"))
#[1] 3 2 1
Run Code Online (Sandbox Code Playgroud)