How to Order a Matrix by Column in R Programming (Example Code)
This page illustrates how to order a matrix by its first variable in the R programming language.
Creation of Example Data
set.seed(98356) # Set random seed example_matrix <- matrix(round(rnorm(30), 1), ncol = 5) # Creating matrix example_matrix # Showing matrix in RStudio console # [,1] [,2] [,3] [,4] [,5] # [1,] -1.4 -1.3 0.6 0.5 -0.1 # [2,] -0.2 0.9 -0.3 0.0 0.0 # [3,] 0.0 -1.5 1.3 0.0 0.1 # [4,] -1.8 0.4 -1.3 -1.1 0.3 # [5,] 0.4 -1.1 -0.8 0.0 1.1 # [6,] 0.3 1.4 0.3 1.5 -0.2 |
set.seed(98356) # Set random seed example_matrix <- matrix(round(rnorm(30), 1), ncol = 5) # Creating matrix example_matrix # Showing matrix in RStudio console # [,1] [,2] [,3] [,4] [,5] # [1,] -1.4 -1.3 0.6 0.5 -0.1 # [2,] -0.2 0.9 -0.3 0.0 0.0 # [3,] 0.0 -1.5 1.3 0.0 0.1 # [4,] -1.8 0.4 -1.3 -1.1 0.3 # [5,] 0.4 -1.1 -0.8 0.0 1.1 # [6,] 0.3 1.4 0.3 1.5 -0.2
Example: Ordering Matrix by Its First Variable
example_matrix[order(example_matrix[ , 1]), ] # Using order() function # [,1] [,2] [,3] [,4] [,5] # [1,] -1.8 0.4 -1.3 -1.1 0.3 # [2,] -1.4 -1.3 0.6 0.5 -0.1 # [3,] -0.2 0.9 -0.3 0.0 0.0 # [4,] 0.0 -1.5 1.3 0.0 0.1 # [5,] 0.3 1.4 0.3 1.5 -0.2 # [6,] 0.4 -1.1 -0.8 0.0 1.1 |
example_matrix[order(example_matrix[ , 1]), ] # Using order() function # [,1] [,2] [,3] [,4] [,5] # [1,] -1.8 0.4 -1.3 -1.1 0.3 # [2,] -1.4 -1.3 0.6 0.5 -0.1 # [3,] -0.2 0.9 -0.3 0.0 0.0 # [4,] 0.0 -1.5 1.3 0.0 0.1 # [5,] 0.3 1.4 0.3 1.5 -0.2 # [6,] 0.4 -1.1 -0.8 0.0 1.1