Design and analysis of experiments with randomizr

Alexander Coppock

randomizr is a small package for r that simplifies the design and analysis of randomized experiments. In particular, it makes the random assignment procedure transparent, flexible, and most importantly reproduceable. By the time that many experiments are written up and made public, the process by which some units recieved treatments is lost or imprecisely described. The randomizr package makes it easy for even the most forgetful of researchers to generate error-free, reproduceable random assignments.

A hazy understanding of the random assignment procedure leads to two main problems at the analysis stage. First, units may have different probabilities of assignment to treatment. Analyzing the data as though they have the same probabilities of assignment leads to biased estimates of the treatment effect. Second, units are sometimes assigned to treatment as a cluster. For example, all the students in a single classroom may be assigned to the same intervention together. If the analysis ignores the clustering in the assignments, estimates of average causal effects and the uncertainty attending to them may be incorrect.

A hypothetical experiment

Throughout this vignette, we’ll pretend we’re conducting an experiment among the 592 individuals in the built-in HairEyeColor dataset. As we’ll see, there are many ways to randomly assign subjects to treatments. We’ll step through five common designs, each associated with one of the five randomizr functions: simple_ra(), complete_ra(), block_ra(), cluster_ra(), and block_and_cluster_ra().

We first need to transform the dataset, which has each row describe a type of subject, to a new dataset in which each row describes an individual subject.

Typically, researchers know some basic information about their subjects before deploying treatment. For example, they usually know how many subjects there are in the experimental sample (N), and they usually know some basic demographic information about each subject.

Our new dataset has 592 subjects. We have three pretreatment covariates, Hair, Eye, and Sex, which describe the hair color, eye color, and gender of each subject.

We now need to create simulated potential outcomes. We’ll call the untreated outcome Y0 and we’ll call the treated outcome Y1. Imagine that in the absence of any intervention, the outcome (Y0) is correlated with out pretreatment covariates. Imagine further that the effectiveness of the program varies according to these covariates, i.e., the difference between Y1 and Y0 is correlated with the pretreatment covariates.

If we were really running an experiment, we would only observe either Y0 or Y1 for each subject, but since we are simulating, we generate both. Our inferential target is the average treatment effect (ATE), which is defined as the average difference between Y0 and Y1.

We are now ready to allocate treatment assignments to subjects. Let’s start by contrasting simple and complete random assignment.

Simple random assignment

Simple random assignment assigns all subjects to treatment with an equal probability by flipping a (weighted) coin for each subject. The main trouble with simple random assignment is that the number of subjects assigned to treatment is itself a random number - depending on the random assignment, a different number of subjects might be assigned to each group.

The simple_ra() function has one required argument N, the total number of subjects. If no other arguments are specified, simple_ra() assumes a two-group design and a 0.50 probability of assignment.

Complete random assignment

Complete random assignment is very similar to simple random assignment, except that the researcher can specify exactly how many units are assigned to each condition.

The syntax for complete_ra() is very similar to that of simple_ra(). The argument m is the number of units assigned to treatment in two-arm designs; it is analogous to simple_ra()’s prob. Similarly, the argument m_each is analogous to prob_each.

If you only specify N, complete_ra() assigns exactly half of the subjects to treatment.

Simple and Complete random assignment compared

When should you use simple_ra() versus complete_ra()? Basically, if the number of units is known beforehand, complete_ra() is always preferred, for two reasons: 1. Researchers can plan exactly how many treatments will be deployed. 2. The standard errors associated with complete random assignment are generally smaller, increasing experimental power. See this guide on EGAP for more on experimental power.

Since you need to know N beforehand in order to use simple_ra(), it may seem like a useless function. Sometimes, however, the random assignment isn’t directly in the researcher’s control. For example, when deploying a survey exeriment on a platform like Qualtrics, simple random assignment is the only possibility due to the inflexibility of the built-in random assignment tools. When reconstructing the random assignment for analysis after the experiment has been conducted, simple_ra() provides a convenient way to do so.
To demonstrate how complete_ra() is superior to simple_ra(), let’s conduct a small simulation with our HairEyeColor dataset.

The standard error of an estimate is defined as the standard deviation of the sampling distribution of the estimator. When standard errors are estimated (i.e., by using the summary() command on a model fit), they are estimated using some approximation. This simulation allows us to measure the standard error directly, since the vectors simple_ests and complete_ests describe the sampling distribution of each design.

sd(simple_ests)

0.6

sd(complete_ests)

0.59

In this simulation complete random assignment led to a 2% decrease in sampling variability. This decrease was obtained with a small design tweak that costs the researcher essentially nothing.

Block random assignment

Block random assignment (sometimes known as stratified random assignment) is a powerful tool when used well. In this design, subjects are sorted into blocks (strata) according to their pre-treatment covariates, and then complete random assignment is conducted within each block. For example, a researcher might block on gender, assigning exactly half of the men and exactly half of the women to treatment.

Why block? The first reason is to signal to future readers that treatment effect heterogeneity may be of interest: is the treatment effect different for men versus women? Of course, such heterogeneity could be explored if complete random assignment had been used, but blocking on a covariate defends a researcher (somewhat) against claims of data dredging. The second reason is to increase precision. If the blocking variables are predicitive of the outcome (i.e., they are correlated with the outcome), then blocking may help to decrease sampling variability. It’s important, however, not to overstate these advantages. The gains from a blocked design can often be realized through covariate adjustment alone.

Blocking can also produce complications for estimation. Blocking can produce different probabilities of assignment for different subjects. This complication is typically addressed in one of two ways: “controlling for blocks” in a regression context, or inverse probabilitity weights (IPW), in which units are weighted by the inverse of the probability that the unit is in the condition that it is in.

The only required argument to block_ra() is blocks, which is a vector of length N that describes which block a unit belongs to. blocks can be a factor, character, or numeric variable. If no other arguments are specified, block_ra() assigns an approximately equal proportion of each block to treatment.

block_ra() provides a number of ways to adjust the number of subjects assigned to each conditions. The prob_each argument describes what proportion of each block should be assigned to treatment arm. Note of course, that block_ra() still uses complete random assignment within each block; the appropriate number of units to assign to treatment within each block is automatically determined.

For finer control, use the block_m_each argument, which takes a matrix with as many rows as there are blocks, and as many columns as there are treatment conditions. Remember that the rows are in the same order as sort(unique(blocks)), a command that is good to run before constructing a block_m_each matrix.

In the example above, the different blocks have different probabilities of assignment to treatment. In this case, people with Black hair have a 30/108 = 27.8% chance of being treated, those with Brown hair have 100/286 = 35.0% change, etc. Left unadressed, this discrepancy could bias treatment effects. We can see this directly with the declare_ra() function.

declaration <-declare_ra(blocks = hec$Hair, block_m_each = block_m_each)
# show the probability that each unit is assigned to each conditionhead(declaration$probabilities_matrix)

prob_0

prob_1

0.72

0.28

0.72

0.28

0.72

0.28

0.72

0.28

0.72

0.28

0.72

0.28

# Show that the probability of treatment is different within blocktable(hec$Hair, round(declaration$probabilities_matrix[,2], 3))

0.278

0.282

0.315

0.35

Black

108

0

0

0

Brown

0

0

0

286

Red

0

71

0

0

Blond

0

0

127

0

There are two common ways to address this problem: LSDV (Least-Squares Dummy Variable, also known as “control for blocks”) or IPW (Inverse-probability weights).

The following code snippet shows how to use either the LSDV approach or the IPW approach. A note for scrupulous readers: the estimands of these two approaches are subtly different from one another. The LSDV approach estimates the average block-level treatment effect. The IPW approach estimates the average individual-level treatment effect. They can be different. Since the average block-level treatment effect is not what most people have in mind when thinking about causal effects, analysts using this approach should present both. The obtain_condition_probabilities() function used to calculate the probabilities of assignment is explained below.

A note for blockTools users: that package also has an assignment function. My preference is to extract the blocking variable, then conduct the assignment with block_ra(), so that fewer steps are required to reconstruct the random assignment or generate new random assignments for a randomization inference procedure.

Clustered assignment

Clustered assignment is unfortunate. If you can avoid assigning subjects to treatments by cluster, you should. Sometimes, clustered assignment is unavoidable. Some common situations include:

Housemates in households: whole households are assigned to treatment or control

Students in classrooms: whole classrooms are assigned to treatment or control

Residents in towns or villages: whole communities are assigned to treatment or control

Clustered assignment decreases the effective sample size of an experiment. In the extreme case when outcomes are perfectly correlated with clusters, the experiment has an effective sample size equal to the number of clusters. When outcomes are perfectly uncorrelated with clusters, the effective sample size is equal to the number of subjects. Almost all cluster-assigned experiments fall somewhere in the middle of these two extremes.

The only required argument for the cluster_ra() function is the clusters argument, which is a vector of length N that indicates which cluster each subject belongs to. Let’s pretend that for some reason, we have to assign treatments according to the unique combinations of hair color, eye color, and gender.

Blocked and clustered assignment

The power of clustered experiments can sometimes be improved through blocking. In this scenario, whole clusters are members of a particular block – imagine villages nested within discrete regions, or classrooms nested within discrete schools.

As an example, let’s group our clusters into blocks by size using dplyr

Calculating probabilities of assignment

All five random assignment functions in randomizr assign units to treatment with known (if sometimes complicated) probabilities. The declare_ra() and obtain_condition_probabilities() functions calculate these probabilities according to the parameters of your experimental design.

In order to calculate the probabilities of assignment, we call the declare_ra() function with the same exact arguments as we used for the block_ra() call. The declaration object contains a matrix of probabilities of assignment:

The prob_mat objects has N rows and as many columns as there are treatment conditions, in this case 2.

In order to use inverse-probability weights, we need to know the probability of each unit being in the condition that it is in. For each unit, we need to pick the appropriate probability. This bookkeeping is handled automatically by the obtain_condition_probabilities() function.

Best practices

Random assignment procedure = Random assignment function

Random assignment procedures are often described as a series of steps that are manually carried out be the researcher. In order to make this procedure reproducible, these steps need to be translated into a function that returns a different random assignment each time it is called.

For example, consider the following procedure for randomly allocating school vouchers.

Every eligible student’s names is put on a list

Each name is assigned a random number

Balls with the numbers associated with all students are put in an urn.

Then the urn is “shuffled”

Students names are drawn one by one from the urn until all slots are given out.

If one sibling in a family wins, all other siblings automatically win too.

If we write such a procedure into a function, it might look like this:

This assignment procedure is complicated by the sibling rule, which has two effects: first, students are cluster-assigned by family, and second, the probability of assignment varies student to student. Obviously, families who have two children in the lottery have a higher probability of winning the lottery because they effectively have two “tickets.” There may be better ways of running this assignment procedure (for example, with cluster_ra()), but the purpose of this example is to show how complicated real-world procedures can be written up in a simple function. With this function, the random assignment procedure can be reproduced exactly, the complicated probabilities of assignment can be caluculated, and the analysis is greatly simplified.

Check probabilities of assignment directly

For many designs, the probability of assignment to treatment can be calculated analytically. For example, in a completely randomized design with 200 units, 60 of which are assigned to treatment, the probability is exactly 0.30 for all units. However, in more complicated designs (such as the schools example described above), analytic probabilities are difficult to calculate. In such a situation, an easy way to obtain the probabilities of assignment is through simulation.

Call your random assignment function an approximately infinite number of times (about 10,000 for most purposes).

Count how often each unit is assigned to each treatment arm.

Z_matrix <-replicate(1000, school_ra(200))
plot(rowMeans(Z_matrix))

This plot shows that the students who have a sibling in the lottery have a higher probability of assignment. The more simulations, the more precise the estimate of the probability of assignment.

Save your random assignment

Whenever you conduct a random assignment for use in an experiment, save it! At a minimum, the random assignment should be saved with an id variable in a csv.