I have a list of elements and I want an object that gives me all possible ways of splitting these elements into a given number of groups of the same size.
For exampl
Here is a brute-force-and-dirty solution, which may work for different number of groups, but you really should test it before use. Moreover, as it uses permn, it will be unusable very fast depending on the size of your vector :
library(combinat)
split.groups <- function(x, nb.groups) {
length.groups <- length(x)/nb.groups
perm <- permn(x)
perm <- lapply(perm, function(v) {
m <- as.data.frame(matrix(v, length.groups, nb.groups))
m <- apply(m,2,sort)
m <- t(m)
m <- m[order(m[,1]),]
rownames(m) <- NULL
m})
unique(perm)
}
Which gives, for example :
R> split.groups(1:4, 2)
[[1]]
[,1] [,2]
[1,] 1 2
[2,] 3 4
[[2]]
[,1] [,2]
[1,] 1 4
[2,] 2 3
[[3]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
Or :
R> split.groups(1:6, 3)
[[1]]
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[[2]]
[,1] [,2]
[1,] 1 2
[2,] 3 6
[3,] 4 5
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 3
[3,] 4 5
[[4]]
[,1] [,2]
[1,] 1 2
[2,] 3 5
[3,] 4 6
[[5]]
[,1] [,2]
[1,] 1 6
[2,] 2 5
[3,] 3 4
[[6]]
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 4
[[7]]
[,1] [,2]
[1,] 1 5
[2,] 2 3
[3,] 4 6
[[8]]
[,1] [,2]
[1,] 1 5
[2,] 2 4
[3,] 3 6
[[9]]
[,1] [,2]
[1,] 1 6
[2,] 2 4
[3,] 3 5
[[10]]
[,1] [,2]
[1,] 1 4
[2,] 2 3
[3,] 5 6
[[11]]
[,1] [,2]
[1,] 1 4
[2,] 2 6
[3,] 3 5
[[12]]
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
[[13]]
[,1] [,2]
[1,] 1 3
[2,] 2 5
[3,] 4 6
[[14]]
[,1] [,2]
[1,] 1 3
[2,] 2 6
[3,] 4 5
[[15]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
[3,] 5 6