1

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.

user2797174
  • 167
  • 2
  • 11

3 Answers3

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    @user2797174 `apply/sapply/lapply` are all loops. If you want to check some comparisons, you can look at [here](https://stackoverflow.com/questions/45933130/apply-vs-for-loop-in-r) or [here](https://stackoverflow.com/questions/42393658/lapply-vs-for-loop-performance-r) – akrun Oct 27 '17 at 15:59
2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
Psidom
  • 209,562
  • 33
  • 339
  • 356
1
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
d.b
  • 32,245
  • 6
  • 36
  • 77