Skip to content

Instantly share code, notes, and snippets.

@acoppock
Created October 23, 2018 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acoppock/89483cdce68867f8ee88e1f5cd2f318b to your computer and use it in GitHub Desktop.
Save acoppock/89483cdce68867f8ee88e1f5cd2f318b to your computer and use it in GitHub Desktop.
randomizr <3's blockTools
# This script shows how to make blocks with blockTools, then randomize with randomizr
# Alex Coppock
# declaredesign.org
library(randomizr)
library(blockTools)
library(tidyverse)
# Prepare data with dplyr + tidyr -----------------------------------------
dat <-
HairEyeColor %>%
data.frame() %>%
group_by(Hair, Eye, Sex) %>%
# HairEyeColor needs to be expanded according to the frequency of each row
expand(rep_num = seq(1:Freq)) %>%
ungroup()
# Block with blockTools ---------------------------------------------------
# BlockTools requires that all variables be numeric
numeric_mat <- model.matrix( ~ Hair + Eye + Sex, data = dat)[,-1]
head(numeric_mat)
# BlockTools also requres an id variable
df_forBT <- data.frame(id_var = 1:nrow(numeric_mat), numeric_mat)
# Conducting the actual blocking: let's make trios
out <- block(df_forBT,
n.tr = 3,
id.vars = "id_var",
block.vars = colnames(numeric_mat))
# Randomize with randomizr ------------------------------------------------
dat <-
dat %>%
mutate(
# Extact the block_ids
block_id = createBlockIDs(out, df_forBT, id.var = "id_var"),
# Conduct actual random assignment with block_ra()
Z_blocked = block_ra(blocks = block_id, num_arms = 3)
)
# confirm blocks of three, one unit assigned to each condition
with(dat, table(Z_blocked, block_id))
@acoppock
Copy link
Author

This produces:

# confirm blocks of three, one unit assigned to each condition
with(dat, table(Z_blocked, block_id))
#>          block_id
#> Z_blocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#>        T1 1 1 1 1 1 1 1 1 1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
#>        T2 1 1 1 1 1 1 1 1 1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
#>        T3 1 1 1 1 1 1 1 1 1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
#>          block_id

... output truncated ...

#> Z_blocked 187 188 189 190 191 192 193 194 195 196 197 198
#>        T1   1   1   1   1   1   1   1   1   1   1   1   1
#>        T2   1   1   1   1   1   1   1   1   1   1   1   0
#>        T3   1   1   1   1   1   1   1   1   1   1   1   0

Created on 2018-10-23 by the reprex package (v0.2.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment