[R] Sorting rows of a matrix independent of each other

Gabor Grothendieck ggrothendieck at gmail.com
Fri Mar 13 20:01:44 CET 2009


There is aaply in the plyer package that does not
require a transpose:

aaply(test, 1, sort)

On Fri, Mar 13, 2009 at 11:14 AM, Kevski <ps at kevski.com> wrote:
>
> Oh, this seemed so simple (and I'm sure the answer will be, as usual, so
> thanks in advance for enlightening me). I need to sort each row of a matrix
> independent of the others. For example,
>
>> test <- matrix(c(8,7,1,2,6,5,9,4,3),nrow=3)
>> test
>     [,1] [,2] [,3]
> [1,]    8    2    9
> [2,]    7    6    4
> [3,]    1    5    3
>
> I can get each row sorted well enough.
>
>> sort(test[1,])
> [1] 2 8 9
>> sort(test[2,])
> [1] 4 6 7
>> sort(test[3,])
> [1] 1 3 5
>
> Now I just need the resulting matrix:
> 2 8 9
> 4 6 7
> 1 3 5
>
> But when I try to turn this into something more automated, I only get the
> last row.
>
>> for(e in 1:3) sorted <- sort(test[e,])
>> sorted
> [1] 1 3 5
>
> I've tried various incarnations of rbind around my loop, but to no avail.
> I've search my books and the forums, and I'm sure there is some nifty R
> function out there, but I can't seem to find it and/or apply it correctly.
>
> Cheers,
> Kev-
>
> --
> View this message in context: http://www.nabble.com/Sorting-rows-of-a-matrix-independent-of-each-other-tp22498636p22498636.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list