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
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