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.
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:
- Sort Data Frame by Multiple Columns
- Order Data Frame by Date in R
- sort, order & rank R Functions
- str_order & str_sort Functions in R
- R Programming Examples
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.
Statistics Globe Newsletter