1

I'm trying to get permutations of a partial set of list elements. I can get regular permutations with

my_list <- list('A' = c("A"), 'B'= c('B', 'B'), "C" = c('C', "C", "C"))
combinat::permn(my_list)

However, I need only 2 of the possible 3 elements e.g. combinat::permn(my_list)[[1]][1:2] would be one of the desired results

combinat::permn(my_list)[[1]][1:2]
$A
[1] "A"

$B
[1] "B" "B"

combinat::permn does not allow for these 'partial' permutations. What would be a good way to get partial permutations?

Xlrv
  • 469
  • 1
  • 6
  • 16

2 Answers2

1

We can use combn

combn(my_list, 2, simplify = FALSE)

-output

[[1]]
[[1]]$A
[1] "A"

[[1]]$B
[1] "B" "B"


[[2]]
[[2]]$A
[1] "A"

[[2]]$C
[1] "C" "C" "C"


[[3]]
[[3]]$B
[1] "B" "B"

[[3]]$C
[1] "C" "C" "C"
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You will need to use one of the packages that are able to generate permutations of length n chosen m at a time (See this How to generate permutations or combinations of object in R? for more information). You can then loop over the rows and subset the orginal list:

library(gtools)

apply(permutations(length(my_list), 2), 1, function(x) {
    my_list[x]
})

[[1]]
[[1]]$A
[1] "A"

[[1]]$B
[1] "B" "B"


[[2]]
[[2]]$A
[1] "A"

[[2]]$C
[1] "C" "C" "C"


[[3]]
[[3]]$B
[1] "B" "B"

[[3]]$A
[1] "A"


[[4]]
[[4]]$B
[1] "B" "B"

[[4]]$C
[1] "C" "C" "C"


[[5]]
[[5]]$C
[1] "C" "C" "C"

[[5]]$A
[1] "A"


[[6]]
[[6]]$C
[1] "C" "C" "C"

[[6]]$B
[1] "B" "B"
Joseph Wood
  • 7,077
  • 2
  • 30
  • 65