3.1 C
London
Friday, December 20, 2024
HomeStatistics TutorialRHow to Sort a Matrix in R (With Examples)

How to Sort a Matrix in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 

Method 2: Sort Matrix by One Column Decreasing

sorted_matrix TRUE), ]

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

#create matrix
my_matrix 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 #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 #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 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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories