[R] How to "Pack" a matrix

Gabor Grothendieck ggrothendieck at gmail.com
Tue Sep 26 20:30:22 CEST 2006


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 at 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 at myfwc.com
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list