Derek Lee Derek Lee - 3 months ago 7
R Question

Generating Permutations of Values Within Multiple Lists

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...

Answer

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

expand.grid(l)