Alif Effendi
Alif Effendi

Reputation: 11

How to sort every column in ascending order in R

M = matrix(data = c(6,34,923,5,0, 112:116, 5,9,34,76,2, 545:549), nrow = 4)

I want it to ascend into and become like this

Ascend for each column and this is the expected output enter image description here

Upvotes: 1

Views: 42

Answers (1)

Josh White
Josh White

Reputation: 1039

I'm assuming that you meant nrow = 5 cause that corresponds to the matrix you've shown. Then all you need to do is simply use apply() to sort each column

M = matrix(data = c(6,34,923,5,0, 112:116, 5,9,34,76,2, 545:549), nrow = 5)
apply(M, 2, sort)

     [,1] [,2] [,3] [,4]
[1,]    0  112    2  545
[2,]    5  113    5  546
[3,]    6  114    9  547
[4,]   34  115   34  548
[5,]  923  116   76  549

Upvotes: 2

Related Questions