How to sort a matrix based on one column in R?

R ProgrammingServer Side ProgrammingProgramming

Since a matrix contain only numeric values, sorting can be also done for matrices. There might be multiple reasons to sort a matrix such as we want to convert the matrix to a data frame, the data stored in matrix needs to be sorted prior to matrix calculations so that the view of the result after calculations becomes clearer, etc. To sort a matrix based on one column, we can use order function.

Examples

set.seed(123)
M1 <-matrix(sample(1:100,20),ncol=2)
M1

Output

[,1] [,2]
[1,] 31 90
[2,] 79 69
[3,] 51 57
[4,] 14 9
[5,] 67 72
[6,] 42 26
[7,] 50 7
[8,] 43 95
[9,] 97 87
[10,] 25 36

Example

Sorting matrix M1 based on column 1 −

M1[order(M1[,1],decreasing=FALSE),]

Output

[,1] [,2]
[1,] 14 9
[2,] 25 36
[3,] 31 90
[4,] 42 26
[5,] 43 95
[6,] 50 7
[7,] 51 57
[8,] 67 72
[9,] 79 69
[10,] 97 87

Example

M1[order(M1[,1],decreasing=TRUE),]

Output

[,1] [,2]
[1,] 97 87
[2,] 79 69
[3,] 67 72
[4,] 51 57
[5,] 50 7
[6,] 43 95
[7,] 42 26
[8,] 31 90
[9,] 25 36
[10,] 14 9

Example

M2 <-matrix(sample(1:10,20,replace=TRUE),ncol=2)
M2

Output

[,1] [,2]
[1,] 1 7
[2,] 7 5
[3,] 5 6
[4,] 10 9
[5,] 7 2
[6,] 9 5
[7,] 9 8
[8,] 10 2
[9,] 7 1
[10,] 5 9

Sorting matrix M2 based on column 2 −

Example

M2[order(M2[,2],decreasing=TRUE),]

Output

[,1] [,2]
[1,] 10 9
[2,] 5 9
[3,] 9 8
[4,] 1 7
[5,] 5 6
[6,] 7 5
[7,] 9 5
[8,] 7 2
[9,] 10 2
[10,] 7 1

Example

M2[order(M2[,2],decreasing=FALSE),]

Output

[,1] [,2]
[1,] 7 1
[2,] 7 2
[3,] 10 2
[4,] 7 5
[5,] 9 5
[6,] 5 6
[7,] 1 7
[8,] 9 8
[9,] 10 9
[10,] 5 9

Example

M3 <-matrix(sample(1:50,20),ncol=2)
M3

Output

[,1] [,2]
[1,] 27 6
[2,] 25 8
[3,] 38 22
[4,] 21 48
[5,] 15 43
[6,] 41 17
[7,] 26 34
[8,] 31 4
[9,] 16 13
[10,] 30 5

Sorting matrix M3 based on column 3 −

Example

M3[order(M3[,2],decreasing=FALSE),]

Output

[,1] [,2]
[1,] 31 4
[2,] 30 5
[3,] 27 6
[4,] 25 8
[5,] 16 13
[6,] 41 17
[7,] 38 22
[8,] 26 34
[9,] 15 43
[10,] 21 48

Example

M3[order(M3[,2],decreasing=TRUE),]

Output

[,1] [,2]
[1,] 21 48
[2,] 15 43
[3,] 26 34
[4,] 38 22
[5,] 41 17
[6,] 16 13
[7,] 25 8
[8,] 27 6
[9,] 30 5
[10,] 31 4
raja
Published on 24-Aug-2020 11:46:04
Advertisements