[R] all possible combinations of list elements

Marc Schwartz MSchwartz at mn.rr.com
Wed Jan 4 02:04:14 CET 2006


On Tue, 2006-01-03 at 18:57 -0600, Eberhard F Morgenroth wrote:
> I have a list as follows
> 
> P <- list(A  = c("CS", "CX"),
>           B  = 1:4,
>           Y  = c(4, 9))
> 
> I now would like to prepare a new list where the rows of the new list
> provide all possible combinations of the elements in the orginal list.
> Thus, the result should be the following
> 
> CS	1	4
> CS	1	9
> CS	2	4
> CS	2	9
> CS	3	4
> CS	3	9
> CS	4	4
> CS	4	9
> CX	1	4
> CX	1	9
> CX	2	4
> CX	2	9
> CX	3	4
> CX	3	9
> CX	4	4
> CX	4	9
> 
> Is there a simple routine in R to create this list of all possible
> combinations? The routine will be part of a function with the list "P"
> as an input. "P" will not always have the same number of elements and
> each element in the list "P" may have different numbers of values.

See ?expand.grid

> expand.grid(P)
    A B Y
1  CS 1 4
2  CX 1 4
3  CS 2 4
4  CX 2 4
5  CS 3 4
6  CX 3 4
7  CS 4 4
8  CX 4 4
9  CS 1 9
10 CX 1 9
11 CS 2 9
12 CX 2 9
13 CS 3 9
14 CX 3 9
15 CS 4 9
16 CX 4 9

HTH,

Marc Schwartz




More information about the R-help mailing list