Generating an ordered run of binary events in R

I needed to generate a sequence of possible binary events in an ordered fashion. For example, I needed to generate the following sequence for three binary variables: 000, 100, 010, 001, 110, 101, 011, 111

I tried to accomplish this in R using the following command:

> expand.grid( rep( list( 0:1 ), 3 ) )
Var1 Var2 Var3
1 0 0 0
2 1 0 0
3 0 1 0
4 1 1 0
5 0 0 1
6 1 0 1
7 0 1 1
8 1 1 1

but notice that the results is not ordered for my need. So here is my little function to generate what I want to do:

expand.grid.binary <- function(N){
## generates an ORDERED sequence of N-binary events
## with all the possible combinations
## expand.grid( rep( list( 0:1 ), N ) ) does not order the results desirably

f <- function(n, r){

v <- t( combn( n, r) )
ind <- cbind( row=rep( 1:nrow(v), ncol(v) ), column=as.vector(v) ) out <- matrix( 0, nrow=nrow(v), ncol=n )
out[ind] <- 1
return(out)

}

out <- do.call( “rbind”, sapply( 0:N, f, n=N ) )
return(out)
}

> expand.grid.binary(3)
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 1 0 0
[3,] 0 1 0
[4,] 0 0 1
[5,] 1 1 0
[6,] 1 0 1
[7,] 0 1 1
[8,] 1 1 1

The next step is how to generalize this to situations when the variables are non-binary. Any ideas?

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s