On Thu, 22 Feb 2007, 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
And, for multiple bases:
myfunc <- function(cols, bases) {
create <- function(idx) {
rep.int(c(sapply(seq_len(bases)-1, function(x)
rep.int(x, bases^(idx-1, bases^cols/bases^idx)
}
sapply(rev(seq_len(cols)), create)
}
# For 3 columns in base 2
myfunc(3,
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,]000
[2,]00
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
1000
5001
3010
7011
2100
6101
4110
8111
On 22/02/0
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