I have been using the marvellous function combn from the package utils. This function creates all the possible combinations without repetition Combn description. I am going to introduce one use of the function that I need to do, but it is not defined in the combn function. I would love to introduce it with a nice example. Nevertheless, the actual goal that we want to achieve is more complicated and it will be performed with more data.
We want to play a game that only 3 people can play. However we are 4 people. We want to know all the possible groups for playing the game. The names of the participants are Alex, David, John and Zoe. The possible combinations would be:
names <- c("Alex","David","John","Zoe")
people.per.group <- 3
combn(names,people.per.group)
#Output
[,1] [,2] [,3] [,4]
[1,] "Alex" "Alex" "Alex" "David"
[2,] "David" "David" "John" "John"
[3,] "John" "Zoe" "Zoe" "Zoe"
However, we have problems because Alex does not have a good relationship with John. So that, we do not want to include both of them in the group. So that we can create groups for the people that we can only chose one of them.
# Alex --> Group 1
# David --> Group 2
# John --> Group 1
# Zoe --> Group 3
only.one.per.group <- c(1,2,1,3)
I am looking for a function that allow me to do the same as combn but limiting the combinations by the variable only.one.per.group. Naming the function that I am looking forward to use var.combn, the code would be:
names <- c("Alex","David","John","Zoe")
only.one.per.group <- c(1,2,1,3)
people.per.group <- 3
var.combn(names,people.per.group,only.one.per.group)
#Output
[,1] [,2]
[1,] "Alex" "David"
[2,] "David" "John"
[3,] "Zoe" "Zoe"
I have been looking for a similar function for quite a long time. So, it would be super useful if you could tell me a function for doing it, or any way that pops into your mind to do it.
I hope that you enjoyed the example and I would love to get any ideas of how to do it.
Here is a different way of doing it
Find all possible group combinations:
All possible groups:
Find groups that satisfy conditions:
Result: