[R] Sorting rows of a binary matrix

David Barron mothsailor at googlemail.com
Thu Feb 22 12:17:42 CET 2007


I'm sure there are more elegant ways, but this should work:

> ix<-order(mat[,1],mat[,2],mat[,3])
> ix
[1] 1 5 3 7 2 6 4 8
> mat[ix,]
  Var1 Var2 Var3
1    0    0    0
5    0    0    1
3    0    1    0
7    0    1    1
2    1    0    0
6    1    0    1
4    1    1    0
8    1    1    1


On 22/02/07, Serguei Kaniovski <Serguei.Kaniovski at wifo.ac.at> 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]]
>
> ______________________________________________
> 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.
>


-- 
=================================
David Barron
Said Business School
University of Oxford
Park End Street
Oxford OX1 1HP



More information about the R-help mailing list