Reputation: 21
I am trying to create a list of all possible ways to split n individuals into groups of variable size. For example, lets say I have 3 individuals, There are 5 possible ways to split them up:
I have written a code determine how the groups could be split:
inds<-1:3
out<-list()
out[[1]]<-matrix(rep(1,length(inds)),nrow=length(inds))
for(i in 1:length(inds)) {
eg <- expand.grid(rep(list(inds), i))
out[[i]]<-unique(t(apply(unique(as.matrix(eg[which(rowSums(eg)==length(inds)),])),1,sort)))
}
out
which results in a list of group numbers and sizes:
[[1]]
[,1]
[1,] 3
[[2]]
[,1] [,2]
2 1 2
[[3]]
Var1 Var2 Var3
1 1 1 1
But I'm not sure how to generate each combination within those potential splits. Ideally, I would like an output which shows all possible ways n individuals could be split up:
Option Group Individuals
1 1 1,2,3
2 1 1,2
2 2 3
3 1 1,3
3 2 2
4 1 2,3
4 2 1
5 1 1
5 2 2
5 3 3
Any help would be greatly appreciated!
Upvotes: 2
Views: 153
Reputation: 16099
Using combn
takes you most of the way:
combinations <- function(group_size, N) {
apply(combn(N, m = group_size), 2, paste0, collapse = ",")
}
all_combinations <- function(N) {
lapply(seq_len(N), combinations, N = N)
}
all_combinations(3)
# [[1]]
# [1] "1" "2" "3"
#
# [[2]]
# [1] "1,2" "1,3" "2,3"
#
# [[3]]
# [1] "1,2,3"
all_combinations(4)
# [[1]]
# [1] "1" "2" "3" "4"
#
# [[2]]
# [1] "1,2" "1,3" "1,4" "2,3" "2,4" "3,4"
#
# [[3]]
# [1] "1,2,3" "1,2,4" "1,3,4" "2,3,4"
#
# [[4]]
# [1] "1,2,3,4"
Upvotes: 1