Reputation: 411
I'm writing an algorithm in R to randomly pair people up but people in the pair cannot be from the same group (team).
I've started by creating an nxn matrix of all of the people. I've marked 0 to indicate people that cannot be paired together (if they are in the same team) and 1 otherwise.
The problem: I now need to sample from the list of eligible people (all of the 1s) in each row, and make a note of the pairing and make sure that the two people in that pair cannot now be paired with another person.
e.g.
Name - Team
A - 1
B - 2
C - 3
D - 4
E - 1
F - 2
G - 1
A B C D E F G
A 0 1 1 1 0 1 0
B 1 0 1 1 1 0 1
C 1 1 0 1 1 1 1
D 1 1 1 0 1 1 1
E 0 1 1 1 0 1 0
F 1 0 1 1 1 0 1
G 0 1 1 1 0 1 0
I realise that this algorithm may get stuck if we get to a stage where nobody can be matched together, so I was thinking of incorporating a timer to restart when the algorithm has been running for say 5 minutes.
Happy to consider any other matching algorithms that you think may be more suitable.
I've already had a look at similar problems on stack overflow (e.g. Sampling column values in a matrix, without replacement) but none of them seem to address the problem of not pairing people from the same group.
Thank you.
Upvotes: 4
Views: 417
Reputation: 887038
Try
(!tcrossprod(table(df1)))+0L
df1 <- structure(list(Name = c("A", "B", "C", "D", "E", "F", "G"),
Team = c(1L,
2L, 3L, 4L, 1L, 2L, 1L)), .Names = c("Name", "Team"),
class = "data.frame", row.names = c(NA, -7L))
Upvotes: 5