-1

I'm trying to generate permutations by taking 1 value from 3 different lists

l <- list(A=c(1:13), B=c(1:5), C=c(1:3))

Desired result => Matrix of all the permutations where the first value can be 1-13, second value can be 1-5, third value can be 1-3

I tried using permn from the combinat package, but it seems to just rearrange the 3 lists.

> permn(l)
[[1]]
[[1]]$A
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13

[[1]]$B
[1] 1 2 3 4 5

[[1]]$C
[1] 1 2 3


[[2]]
[[2]]$A
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13

[[2]]$C
[1] 1 2 3

[[2]]$B
[1] 1 2 3 4 5
....

Expected output

     [,1] [,2] [,3]
[1,]    1    1    3
[2,]    1    2    1
[3,]    1    1    2
[4,]    1    1    3
and so on...
DLee
  • 7,856
  • 4
  • 19
  • 23
  • What is your expected output – akrun Aug 10 '16 at 17:19
  • Updated above. Ideally just a matrix with 3 columns and the (13 x 5 x 3) 195 possible permutations – DLee Aug 10 '16 at 17:26
  • @akrun I don't know if Richard downvoted your answer or not, but that has nothing to do with the fact that this is a dupe of a dupe of a dupe of a dupe. Why would you reopen it? – David Arenburg Aug 10 '16 at 18:04
  • @akrun I don't get it. Are you saying this is not a dupe? The voting issue seems like a sideshow. Generally, while votes are an individual's choice, inevitably based on some subjective factors; dupes are something worth figuring out together. – Frank Aug 10 '16 at 18:04
  • @akrun Ok, but that doesn't justify reopening. If you have an issue with someone, accusing them in the comments and abusing -- yes, the word fits here -- closure/reopening is not really the right way to resolve it. – Frank Aug 10 '16 at 18:08

2 Answers2

0

We can use expand.grid. It can directly be applied on the list

expand.grid(l)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You can create a data frame using do.call and expand.grid, if you really need a matrix, then use as.matrix on the result:

> l <- list(A=c(1:13), B=c(1:5), C=c(1:3))
> out <- do.call(expand.grid, l)
> head(out)
  A B C
1 1 1 1
2 2 1 1
3 3 1 1
4 4 1 1
5 5 1 1
6 6 1 1
> tail(out)
     A B C
190  8 5 3
191  9 5 3
192 10 5 3
193 11 5 3
194 12 5 3
195 13 5 3
> tail(as.matrix(out))
        A B C
[190,]  8 5 3
[191,]  9 5 3
[192,] 10 5 3
[193,] 11 5 3
[194,] 12 5 3
[195,] 13 5 3
> 
Greg Snow
  • 48,497
  • 6
  • 83
  • 110