I want to create a list for my classroom of every possible group of 4 students. If I have 20 students, how I can I create this, by group, in R where my rows are each combination
Here's an example for smaller numbers. I don't think this will scale well for 20 students
total_students = 4
each_group = 2
total_groups = total_students/each_group
if (total_students %% each_group == 0) {
library(arrangements)
group_id = rep(1:total_groups, each = each_group)
#There is room to increase efficiency here by generating only relevant permutations
temp = permutations(1:total_students, total_students)
temp = unique(t(apply(temp, 1, function(i) {
x = group_id[i]
match(x, unique(x))
})))
dimnames(temp) = list(COMBO = paste0("C", 1:NROW(temp)),
Student = paste0("S", 1:NCOL(temp)))
} else {
cat("Total students not multiple of each_group")
temp = NA
}
#> Warning: package 'arrangements' was built under R version 3.5.3
temp
#> Student
#> COMBO S1 S2 S3 S4
#> C1 1 1 2 2
#> C2 1 2 1 2
#> C3 1 2 2 1
Created on 2019-09-02 by the reprex package (v0.3.0)
The total number of possible ways is given by following function (from here)
foo = function(N, k) {
#N is total number or people, k is number of people in each group
if (N %% k == 0) {
m = N/k
factorial(N)/(factorial(k)^m * factorial(m))
} else {
stop("N is not a multiple of n")
}
}
foo(4, 2)
#[1] 3
foo(20, 4)
#[1] 2546168625
For groups of 4 people from a total of 20 people, the number of possible arrangements is massive.