[R] Sorting rows of a binary matrix

Adrian Dusa dusa.adrian at gmail.com
Thu Feb 22 14:00:09 CET 2007


Hello Serguei,

Is this what you need?

myfunc <- function(x) {
    create <- function(idx) {
        rep.int(c(rep.int(0,2^(idx-1)), rep.int(1,2^(idx-1))),
                2^x/2^idx)
        }
    sapply(rev(seq(x)), create)
    }

> myfunc(3)
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    1
[3,]    0    1    0
[4,]    0    1    1
[5,]    1    0    0
[6,]    1    0    1
[7,]    1    1    0
[8,]    1    1    1

For numerical values only, this is faster than expand.grid().
Alternatively (for multiple values in separate varaibles), you could use the 
function createMatrix() in package QCA.

HTH,
Adrian

On Thursday 22 February 2007 12:50, Serguei Kaniovski wrote:
> Hallo,
>
> The command:
>
> x <- 3
> mat <- as.matrix(expand.grid(rep(list(0:1), x)))
>
> generates a matrix with 2^x columns containing the binary representations
> of the decimals from 0 to (2^x-1), here from 0 to 7. But the rows are not
> sorted in this order.
>
> How can sort the rows the ascending order of the decimals they represent,
> preferably without a function which converts binaries to decimals (which I
> have)? Alternatively, generate a matrix that has the rows sorted that way?
>
> Thanks,
> Serguei
> 	[[alternative HTML version deleted]]

-- 
Adrian Dusa
Romanian Social Data Archive
1, Schitu Magureanu Bd
050025 Bucharest sector 5
Romania
Tel./Fax: +40 21 3126618 \
          +40 21 3120210 / int.101



More information about the R-help mailing list