[R] enumerates all possible combinations

From: ken knoblauch <knoblauch_at_lyon.inserm.fr>
Date: Fri 26 Jan 2007 - 16:13:01 GMT


does expand.grid do what you want?

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

   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

> Hi all R users,
> I want to create a matrix having n columns and 2^n rows, and all its
> entries
> are only 0 or 1. In each row, column i is 0 means dimension i is
> chosen, 0
> means not. The matrix will contains all the possible combination of
> those n
> dimensions.
>
> Here is an example, if n = 3, the matrix will look like:
> 0 0 0
> 0 0 1
> 0 1 0
> 1 0 0
> 0 1 1
> 1 0 1
> 1 1 1
>
>
> I know I can use n "for" loops to do this, but is there a better way?
> Thanks,
> -zm
>
> [[alternative HTML version deleted]]
>
>



R-help@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. Received on Sat Jan 27 03:17:33 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 26 Jan 2007 - 17:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.