简体   繁体   中英

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_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:

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(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; later on add dimension to sorted data with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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