简体   繁体   English

根据r中的另一个矩阵对矩阵进行排序

[英]sort a matrix based on another matrix in r

I have two matrices: 我有两个矩阵:

A = matrix(c(2,1,3,6,4,3,8,1,6,2,9,5), ncol=4)
B = matrix(c(20,10,30,60,40,30,80,10,60,20,90,50), ncol=4)

Now, I have sorted the matrix A by rows: 现在,我按行对矩阵A进行了排序:

A_sorted=t(apply(A,1,sort))

2 2 6 8
1 1 4 9
3 3 5 6

Now, I want to sort the B matrix in the same order as of A, so that the new matrix 'B_sorted' would be: 现在,我想以与A相同的顺序对B矩阵进行排序,以便新的矩阵“ B_sorted”为:

20 20 60 80
10 10 40 90
30 30 50 60

I have found a similar answer from the past Sort one matrix based on another matrix but the codes from the answer do not work with a matrix of different dimensions. 我从过去发现了类似的答案基于另一个矩阵对一个矩阵进行排序,但是答案中的代码不适用于不同维度的矩阵。

We can loop through the sequence of rows with for loop and assign the rows of 'B' based on the order of 'A' rows 我们可以使用for循环遍历行的序列,并根据“ A”行的order分配“ B”行

for(i in seq_len(nrow(A))) B[i,] <- B[i,][order(A[i,])]
B
#     [,1] [,2] [,3] [,4]
#[1,]   20   20   60   80
#[2,]   10   10   40   90
#[3,]   30   30   50   60

You can create the index that sort the matrix by row with order(row(A), A) and then reorder the original matrix with it; 您可以创建使用order(row(A), A)按行对矩阵进行排序的索引,然后使用该索引对原始矩阵进行重新排序; later on add dimension to sorted data with matrix : 稍后添加维到matrix排序的数据:

matrix(B[order(row(A), A)], byrow = TRUE, ncol = ncol(B))

#     [,1] [,2] [,3] [,4]
#[1,]   20   20   60   80
#[2,]   10   10   40   90
#[3,]   30   30   50   60
t(sapply(1:NROW(A), function(i) B[i,][order(A[i,])]))
#     [,1] [,2] [,3] [,4]
#[1,]   20   20   60   80
#[2,]   10   10   40   90
#[3,]   30   30   50   60

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

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