Reputation: 167
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.
Upvotes: 1
Views: 1934
Reputation: 214917
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
Upvotes: 2
Reputation: 886998
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
Upvotes: 2
Reputation: 32548
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
Upvotes: 1