lundi 18 décembre 2023

Distributing random numbers with multiple conditions

My students handed in group projects. Now they are supposed to give feedback to other student's works. Each student should give feedback to two other student projects. I want to assign these projects randomly. Two conditions have to be met:

  1. A student should not give feedback to their own project.
  2. A student should not give feedback to the same project twice.
#Example Data
group <- c(1,1,1,2,2,3,3,3,4,4)
name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")
feedback1 <- c(1,1,1,2,2,3,3,3,4,4)
feedback2 <- c(1,1,1,2,2,3,3,3,4,4)
df <- data.frame(group, name, feedback1, feedback2)

As you can see, the groups are not the same size (some groups have 2 members, some have 3). I created a loop that checks if someone is about to give feedback to himself. If so, a random number is chosen from all the group numbers, until a fitting number is chosen. One occurrence of the chosen number is then removed from the group numbers and the next student is checked.

# Fill feedback1
for (i in 1:nrow(df)) {
  while (df$feedback1[i] == df$group[i]) {
    df$feedback1[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback1[i], group)]
}

This works so far:


   group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4

If I add the second condition ("students should not give feedback to the same groups") the loop fails to work:

# Fill feedback2
group <- c(1,1,1,2,2,3,3,3,4,4)

for (i in 1:nrow(df)) {
  while (df$feedback2[i] == df$group[i] & df$feedback1[i] == df$feedback2[i] ) {
    df$feedback2[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback2[i], group)]
}

I do not get an error message, but df$feedback2 just stays the same for all students:

 group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4
  1. What is the mistake in my second loop for feedback2?
  2. What would be (in general) a better way to do approach the problem?

Best regards




Aucun commentaire:

Enregistrer un commentaire