I have a sequence which varies in length e.g. something like:
items <- 1:4
I want to split it into every possible combination of n number of sets. So say n is two, I want to return:
Set A Set B
----- -----
1 2 3 4
1 2 3 4
1 2 3 4
1 3 2 4
etc. The arrangement within sets doesn’t matter i.e. the set {1, 2, 3} is the same as {2, 1, 3}. Sets cannot be empty.
Best I could come up with (using permn from the package combinat) is:
n <- 2
r <- 1:length(items)
arrangements <- NULL
for (i in 1:(n-1)) {
A <- r[(1:i)]
B <- r[-(1:i)]
arrangements <- c(arrangements, apply(do.call(rbind, permn(1:length(items))), 1, function(z) list(z[A], z[B])))
}
Which is fairly useless because it returns sets that are equal i.e. {1, 2, 3} and {2, 1, 3} and isn’t flexible enough to handle different values of n. Anyone have any ideas how I can do this? Thanks.
There is a ‘sets’ package:
It includes pairings like ( {1,2,3,4}, {} ) which is correct from a set theory viewpoint, but you may want to eliminate them as “degenerate”. (The way is now clear to generalize this to larger N by working recursively on the Set_B result.)