Trying to build an R function to randomly pair groups together each week but keep the new group sizes the same

Viewed 88

if we have data:

group group_size
a 2
b 3
c 1
d 4
e 2
f 4
g 1
h 3
i 1
j 3
k 1
l 1
  • Code for input data:
df <- data.frame(group = c("a","b","c","d","e","f","g","h","i","j","k","l"),
                 group_size = c(2,3,1,4,2,4,1,3,1,3,1,1))

and I want to randomly pair or trio groups into larger groups that are all the same size how would I do this in R? For my results - I would want all of the groups to be matched up with another group randomly and have each of the 4-5 new groups be of equal size. I need to redo this every week randomly, so I want to make sure the results can be randomized everytime.

Thanks.

sample desired output:

new_grp members new_grp_size
group 1 a,c,e 5
group 2 b,l,g 5
group 3 d,k 5
group 4 j,h 6
group 5 i,f 5

notice all groups are as close to the same size as they can get.

1 Answers

Simple approach adapted from CrossValidated: Partition a vector into equally sized groups. You can generate a new grouping by adjusting the seed.

Code

group_size <- 5

set.seed(2021)
sample_groups <- sample(groups, length(groups))

f <- approxfun(
    c(0, cumsum(sample_groups)/sum(sample_groups)), 
    c(0, seq_along(sample_groups))
) 

i <- f(seq(0, 1, length.out = group_size + 1))
j <- rep(0, length(sample_groups))
j[round(1 + i[-length(i)])] <- 1
grouping <- cumsum(j)

Result

tibble(
    group = names(sample_groups),
    n = sample_groups,
    grouping = grouping
) %>%
    group_by(
        grouping
    ) %>%
    summarise(
        n = sum(n),
        groups = paste(group, collapse = ", ")
    )
# A tibble: 5 × 3
  grouping     n groups 
     <dbl> <dbl> <chr>  
1        1     5 g, f   
2        2     4 j, l   
3        3     7 d, h   
4        4     5 k, c, b
5        5     5 i, a, e

Data

library(tidyverse)
groups <- c(
    "a" = 2,
    "b" = 3,
    "c" = 1,
    "d" = 4,
    "e" = 2,
    "f" = 4,
    "g" = 1,
    "h" = 3,
    "i" = 1,
    "j" = 3,
    "k" = 1,
    "l" = 1
)
Related