Created
October 23, 2018 21:14
-
-
Save acoppock/89483cdce68867f8ee88e1f5cd2f318b to your computer and use it in GitHub Desktop.
randomizr <3's blockTools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This produces:
Created on 2018-10-23 by the reprex package (v0.2.1)