Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort matrix rows by row means

Tags:

r

matrix

I have a matrix m :

m <- matrix(c(1, 8, 3, 1, 2, 4, 9, 0, 0), nrow = 3, byrow = TRUE)
m

     [,1] [,2] [,3]
[1,]    1    8    3
[2,]    1    2    4
[3,]    9    0    0

I calculate the rowMeans(m) :

r.mean <- rowMeans(m)
r.mean

[1] 4.000000 2.333333 3.000000

How can I use r.mean to sort my matrix m from the maximum mean to the minimum :

     [,1] [,2] [,3]
[1,]    1    8    3
[2,]    9    0    0
[3,]    1    2    4
like image 985
Bilal Avatar asked Oct 18 '25 15:10

Bilal


1 Answers

like this?

m[ order(rowMeans(m)), ]
     [,1] [,2] [,3]
[1,]    1    2    4
[2,]    9    0    0
[3,]    1    8    3

From the maximum mean to the minimum, by adding , decreasing = T

m[ order(rowMeans(m), decreasing = T), ]
     [,1] [,2] [,3]
[1,]    1    8    3
[2,]    9    0    0
[3,]    1    2    4
like image 199
Eric Fail Avatar answered Oct 21 '25 06:10

Eric Fail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!