Eberhard F Morgenroth
2006-Jan-04 00:57 UTC
[R] all possible combinations of list elements
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. Thanks, Eberhard Morgenroth ____________________________________________________________________ Eberhard Morgenroth, Assistant Professor of Environmental Engineering University of Illinois at Urbana-Champaign 3219 Newmark Civil Engineering Laboratory, MC-250 205 North Mathews Avenue, Urbana, IL 61801, USA Email: emorgenr at uiuc.edu http://cee.uiuc.edu/research/morgenroth
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