Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sorting a matrix in r

I have a matrix like below but with n rows

rm(list=ls())
set.seed(123)
mt=as.matrix(replicate(5,sample(1:3,4,replace = TRUE)))
mt
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    3    3    3    1    3
#> [2,]    3    2    1    2    3
#> [3,]    3    2    2    3    1
#> [4,]    2    2    2    1    1

To sort it row by row . I am using this code with the order function like here

od2=order(mt[1,],mt[2,],mt[3,],mt[4,])
mt[,od2]
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    1    3    3    3    3
#> [2,]    2    1    2    3    3
#> [3,]    3    2    2    1    3
#> [4,]    1    2    2    1    2

is there any way to have an adapted one for n multiple rows. I wasn’t successful with the second version of @Joshua Ulrich code in the comment. I am not familiar with do.call function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Created on 2023-04-05 with reprex v2.0.2

>Solution :

You can use asplit:

mt[,do.call(order, asplit(mt, 1))]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    3    3    3    3
#[2,]    2    1    2    3    3
#[3,]    3    2    2    1    3
#[4,]    1    2    2    1    2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading