Sort Matrix According to First Column in R (Example)

 

In this article, I’ll illustrate how to order a matrix by its first variable in the R programming language.

The table of content is structured as follows:

You’re here for the answer, so let’s get straight to the example…

 

Creation of Example Data

As a first step, we’ll have to create some data that we can use in the examples later on:

my_mat <- matrix(c(8, 5, 3, 6, 1,               # Create example matrix
                   3, 4, 5, 3, 4,
                   4, 7, 5, 4, 3),
                 ncol = 3)
my_mat                                          # Print example matrix
#      [,1] [,2] [,3]
# [1,]    8    3    4
# [2,]    5    4    7
# [3,]    3    5    5
# [4,]    6    3    4
# [5,]    1    4    3

The previous output of the RStudio console illustrates the structure of the example data: It’s a numeric matrix consisting of five rows and three columns. The matrix is not ordered yet.

 

Example: Sorting Matrix by First Column Using order() Function

In this section, I’ll show how to reorder a matrix by its first column using the order function in R.

Have a look at the following R code:

my_mat_sort <- my_mat[order(my_mat[ , 1]), ]    # Apply order function
my_mat_sort                                     # Print sorted matrix
#      [,1] [,2] [,3]
# [1,]    1    4    3
# [2,]    3    5    5
# [3,]    5    4    7
# [4,]    6    3    4
# [5,]    8    3    4

As you can see, our new matrix object is ordered numerically by the first column.

 

Video, Further Resources & Summary

Do you want to learn more about matrices in R? Then you could watch the following video of my YouTube channel. I illustrate the topics of this article in the video.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Besides that, you might want to have a look at the related tutorials of my homepage:

 

In this post, I explained how to rearrange a data matrix in the R programming language. Don’t hesitate to let me know in the comments section, in case you have additional questions. Furthermore, please subscribe to my email newsletter in order to get regular updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top