Trang Q. Nguyen
Trang Q. Nguyen

Reputation: 139

Generate all vectors of certain length with 0 or 1 elements

I need to generate all possible vectors with elements 0 or 1 of a certain length.

For example, here the length is 6, I need all the vectors:

(0,0,0,0,0,0),(0,0,0,0,0,1),...,(1,1,1,1,1,1)

Searching around, I found a way to make the vector y below which contains 64 character strings "000000","000001",...,"111111", but now I am stuck not knowing how to convert each of these strings into the relevant vector.

x <- seq(0,2^6-1,1)
library(R.utils)
y <- inToBin(x)

Edit: I figured out how to do this:

z <- matrix(NA,nrow=length(y),ncol=6)
for(i in 1:length(y)){
  z[i,] <- as.numeric(strsplit(y[i],"")[[1]])
}

Upvotes: 3

Views: 516

Answers (1)

IRTFM
IRTFM

Reputation: 263362

The expand grid and combn functions are your first thought when trying to construct exhaustive examples of combinations. Here I think you want the expand.grid facility.:

 str( apply(expand.grid(0:1,0:1,0:1,0:1,0:1,0:1), 1, paste0, collapse="") )

 chr [1:64] "000000" "100000" "010000" "110000" "001000" ...

But perhaps you don't really want that and only want

apply(expand.grid(0:1,0:1,0:1,0:1,0:1,0:1), 1, list)

Or just:

expand.grid(0:1,0:1,0:1,0:1,0:1,0:1)

Upvotes: 4

Related Questions