Suppose we have eight participants and their ages. We want to randomly assign participants to two treatments so that each treatment group has 4 participants.
participant_num <- c(1,2,3,4,5,6,7,8)
participant_age <- c(24,26,28,27,51,56,54,55)
How many possible randomizations of the 8 individuals?
choose(8,4) #70
## [1] 70
set.seed(113344)
group_A <- sample(participant_num,size=4,replace=FALSE)
group_A # 4, 7, 1, 6-- 3 young and 1 older
## [1] 4 7 2 1
We’ll use the package gtools (see citation in code chunk).
#install.packages("gtools")
library(gtools)
#citation("gtools")
Enumerate all possible randomizations by showing the 4 participants assigned to group A
all_rands <- combinations(8,4)
dim(all_rands) #70 by 4 -- the 4 participants assigned to group A
## [1] 70 4
head(all_rands)
## [,1] [,2] [,3] [,4]
## [1,] 1 2 3 4
## [2,] 1 2 3 5
## [3,] 1 2 3 6
## [4,] 1 2 3 7
## [5,] 1 2 3 8
## [6,] 1 2 4 5
Now let’s code young participants as 0 and older participants as 1 so we can easily use the sum within each row to assess the makeup of the treatment groups relative to age across all 70 possible randomizations.
ageclass_fun <- function(partic_num) {ifelse(partic_num < 5, 0, 1)}
age_coded_all_rands <- t(apply(all_rands, 1, ageclass_fun))
head(age_coded_all_rands) #a 70x4 matrix of 1's and 0's where a row sum of 2 reflects "balance"
## [,1] [,2] [,3] [,4]
## [1,] 0 0 0 0
## [2,] 0 0 0 1
## [3,] 0 0 0 1
## [4,] 0 0 0 1
## [5,] 0 0 0 1
## [6,] 0 0 0 1
Now do the summing and create a table showing numbers of older adults in treatment A in each possible randomization.
age_split <- apply(age_coded_all_rands, 1, sum)
age_split
## [1] 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3
## [36] 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4
table(age_split)
## age_split
## 0 1 2 3 4
## 1 16 36 16 1
Summary of table: 36/70 with two from each age class in each treatment group, 32/70 with 3 in one treatment group and 1 in the other, and 2/70 with all four in one treatment group.