Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse lexicographic order after using expand.grid

Tags:

r

permutation

I'm trying to generate the following matrix, based on a multinomial framework. For example, if I had three columns, I'd get:

0 0 0
1 0 0
0 1 0
0 0 1
1 1 0
1 0 1
0 1 1
1 1 1

But, I want many more columns. I know I can use expand.grid, like:

u <- list(0:1)
expand.grid(rep(u,3))

But, it returns what I want in the wrong order:

0 0 0
1 0 0
0 1 0
1 1 0
0 0 1
1 0 1
0 1 1
1 1 1

Any ideas? Thanks.

like image 201
Scott Avatar asked Oct 06 '22 11:10

Scott


1 Answers

You can reorder your rows to match your expected output:

u <- list(0:1)
g <- expand.grid(rep(u,3))
g <- g[order(rowSums(g)), ]
like image 103
flodel Avatar answered Oct 19 '22 15:10

flodel