How to Sort a Matrix in R (With Examples)


You can use the following methods to sort a matrix by a particular column in R:

Method 1: Sort Matrix by One Column Increasing

sorted_matrix <- my_matrix[order(my_matrix[, 1]), ]

Method 2: Sort Matrix by One Column Decreasing

sorted_matrix <- my_matrix[order(my_matrix[, 1], decreasing=TRUE), ]

The following examples show how to use each method in practice with the following matrix:

#create matrix
my_matrix <- matrix(c(5, 4, 2, 2, 7, 9, 12, 10, 15, 4, 6, 3), ncol=2)

#view matrix
my_matrix

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

Example 1: Sort Matrix by One Column Increasing

The following code shows how to sort the matrix by increasing values based on the first column:

#sort matrix by first column increasing
sorted_matrix <- my_matrix[order(my_matrix[, 1]), ]

#view sorted matrix
sorted_matrix

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

Notice that the matrix is now sorted by increasing values based on the first column.

We could just as easily sort by increasing values based on the second column by changing the 1 to a 2:

#sort matrix by second column increasing
sorted_matrix <- my_matrix[order(my_matrix[, 2]), ]

#view sorted matrix
sorted_matrix

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

The matrix is now sorted by increasing values based on the second column.

Example 2: Sort Matrix by One Column Decreasing

The following code shows how to sort the matrix by decreasing values based on the first column:

#sort matrix by first column decreasing
sorted_matrix <- my_matrix[order(my_matrix[, 1], decreasing=TRUE), ]

#view sorted matrix
sorted_matrix

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

Notice that the matrix is now sorted by decreasing values based on the first column.

Related: The Complete Guide to sort(), order(), and rank() in R

Additional Resources

The following tutorials explain how to perform other common sorting operations in R:

How to Sort Values Alphabetically in R
How to Sort a Data Frame by Date in R
How to Sort by Multiple Columns in R

Leave a Reply

Your email address will not be published.