Re: [R] How to "Pack" a matrix

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue 26 Sep 2006 - 18:30:22 GMT

It looks like your example only reorders the columns but your discussion refers to ordering rows too. I have only addressed the columns part but it is hopefully clear how to extend this or use other objective functions. We generate every permutation of the rows and define an objective function f which is smaller for more desirable column permutations and then use brute force to find the minimizer:

library(combinat)

mat <- structure(c(1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0), .Dim = c(6, 6), .Dimnames = list(c("site1", "site2", "site3", "site4", "site5", "site6"), c("sp1", "sp2", "sp3", "sp4", "sp5", "sp6")))

f <- function(p) sum(mat[,p] * (row(mat) + col(mat))) perms <- permn(ncol(mat))
mat[,perms[[which.min(sapply(perms, f))]]]

On 9/26/06, Guenther, Cameron <Cameron.Guenther@myfwc.com> wrote:
> Hello,
> Suppose I have a matrix a where
>
> a= sp1 sp2 sp3 sp4 sp5 sp6
> site1 1 0 1 1 0 1
> site2 1 0 1 1 0 1
> site3 1 1 1 1 1 1
> site4 0 1 1 1 0 1
> site5 0 0 1 0 0 1
> site6 0 0 1 0 1 0
>
> And I want to pack that matrix so that the upper left corner contains
> most of the ones and the bottom right corner contains most of the zeros
> so that matrix b is
>
> b= sp3 sp6 sp4 sp1 sp2 sp5
> site1 1 1 1 1 0 0
> site2 1 1 1 1 0 0
> site3 1 1 1 1 1 1
> site4 1 1 1 0 1 0
> site5 1 1 0 0 0 0
> site6 1 0 0 0 0 1
>
> Can any of you help me with some code to accomplish this? I have tried
> different forms of order and can't seem to figure it out. Basically I
> want to order the matrix by both the rows and columns.
>
> Thank you for your help.
> Cam
>
> Cameron Guenther, Ph.D.
> Associate Research Scientist
> FWC/FWRI, Marine Fisheries Research
> 100 8th Avenue S.E.
> St. Petersburg, FL 33701
> (727)896-8626 Ext. 4305
> cameron.guenther@myfwc.com
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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.
>



R-help@stat.math.ethz.ch 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. Received on Wed Sep 27 04:42:19 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 26 Sep 2006 - 19:30:06 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.