# [R] reordering of matrix rows to maximize the sum of the diagonal

Jonathan jonsleepy at gmail.com
Mon Apr 26 20:53:01 CEST 2010

```Hi Dennis,
Thanks for the idea, but the order of the rowSums does not
necessarily correspond to the order of rows that maximizes the "rank"
of the matrix.

Ex:
> a[1:9]<-c(1,1,30,50,1,1,1,20,1)

> a
[,1] [,2] [,3]
[1,]    1   50    1
[2,]    1    1   20
[3,]   30    1    1

> a[order(rowSums(a)),]

[,1] [,2] [,3]
[1,]    1    1   20
[2,]   30    1    1
[3,]    1   50    1

In this case, I would like to rearrange the original matrix into:

[,1] [,2] [,3]
[1,]   30    1    1
[2,]    1   50    1
[3,]    1    1   20

Best,
Jonathan

On Sat, Apr 24, 2010 at 1:24 AM, Dennis Murphy <djmuser at gmail.com> wrote:
> Hi:
>
>
> a[order(rowSums(a)), ]
>      [,1] [,2] [,3]
> [1,]    9    1    2
> [2,]    2   11    1
> [3,]    3    4   13
>
> HTH,
> Dennis
>
>
> On Fri, Apr 23, 2010 at 1:10 PM, Jonathan <jonsleepy at gmail.com> wrote:
>>
>> Hi r-help community,
>>    This question isn't so much a syntax/coding one, but here goes:
>>
>> Let's say I have matrix of arbitrary dimensions and I'd like to
>> reorder the rows in such a way that I could maximize the sum of the
>> entries along the diagonal.
>>
>> For example, for this 3x3 matrix:
>>
>>
>>     [,1] [,2] [,3]
>> [1,]    3    4   13
>> [2,]    9    1    2
>> [3,]    2   11    1
>>
>> rearranging the rows to maximize the sum along the diagonal would
>> produce this matrix:
>>
>>     [,1] [,2] [,3]
>> [1,]    9    1    2
>> [2,]    2   11    1
>> [3,]    3    4   13
>>
>>
>> I've been experimenting with some scripts of my own, but I figured I'd
>> ask if one of you R-ninjas might know of an existing function (or
>> algorithm I could look up and then code) that can do this somewhat
>> efficiently (or even just correctly!).
>>
>> Best,
>> Jonathan
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help