SStatistics, Built

Stage III · Master's

Part 35 of 65

What If? Experiments and Potential Outcomes

Master'sstarts at this level57 min of film16 chaptersprerequisites: Part 13, Part 23

What does it mean for one thing to cause another, and why does randomization let us find out?

The 1954 Salk vaccine trial ran two designs side by side. The randomized, placebo-controlled one found 28 against 71 cases of paralytic polio per 100,000; the observed-control one found 25 against 54, because consenting families differed from the rest. Potential outcomes make the question precise: each unit has an outcome under treatment and one under control, and only one is ever seen. In the World's clinic both are known, so the science table shows what an assignment hides, and the naive difference splits into the effect on the treated plus selection bias. A coin removes the bias. Fisher tests the sharp null by re-randomizing; Neyman gives the difference in means its variance and a conservative estimate of it. The part then works through what trials meet in practice: blocking, Lin's adjustment, cluster randomization, noncompliance and the complier effect, interference in an epidemic, subgroups by star sign in ISIS-2, boundaries for interim looks, surrogates that failed in CAST, and transport to the island. It ends by asking what can be learned when no coin is available.

What you need. Designed experiments from Part 13 and regression with robust standard errors from Part 23.

Hook
the Salk polio trial, 1954
Mathematics
potential outcomes, randomization and Neyman inference, Lin's adjustment, noncompliance and LATE, interference, sequential trials
Built
a trial with both outcomes visible

What you will be able to do

Bachelor's

  • Write a science table for a small study, compute its average effect, and show which half an assignment hides.
  • Decompose a difference in means into the effect on the treated plus selection bias, and say why a coin makes the second term zero on average.

Master's

  • Carry out Fisher's randomization test of the sharp null and invert it for a constant effect.
  • Derive Neyman's variance of the difference in means and explain why its estimator is conservative.
  • Derive the Wald estimator of the complier average effect under monotonicity and exclusion.

PhD

  • Define direct, indirect, total and overall effects under partial interference and say which of them a two-stage design identifies.
  • State what Lin's interacted estimator guarantees asymptotically without a model for the outcomes, and Freedman's three critiques of ANCOVA that it answers.

Practice

  • Analyse a cluster-randomized trial at the level that was randomized, and compute the design effect before planning one.
  • Plan interim analyses with a Pocock or O'Brien-Fleming boundary instead of repeated tests at 1.96, and treat an unplanned subgroup finding or a surrogate endpoint with the caution of ISIS-2 and CAST.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 18 min · Master's 54 min · PhD 57 min · Practice 32 min.

  1. 0The Salk trialBachelor's4 min
  2. 1Potential outcomesBachelor's4 min
  3. 2Estimands and SUTVAMaster's4 min
  4. 3Why randomization worksBachelor's4 min
  5. 4Fisher's sharp nullMaster's4 min
  6. 5Neyman's varianceMaster's4 min
  7. 6Blocking and pairingMaster's3 min
  8. 7AdjustmentMaster's3 min
  9. 8Cluster randomizationPractice3 min
  10. 9NoncomplianceMaster's4 min
  11. 10InterferencePhD4 min
  12. 11SubgroupsBachelor's3 min
  13. 12Sequential trialsPractice4 min
  14. 13SurrogatesPractice3 min
  15. 14External validityPractice3 min
  16. Recap, problems, and the road aheadAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

The Salk trialBachelor's4 min

In the spring of 1954, the United States ran the largest public-health experiment in its history. Jonas Salk had made a killed-virus polio vaccine, and nearly two million schoolchildren, the polio pioneers, took part in testing it, under the direction of Thomas Francis at the University of Michigan. Polio was terrifying: in 1952 the country had over fifty-seven thousand cases, many of them children left paralysed. But it was also rare and erratic, with epidemics that came and went from year to year, so a drop in cases after vaccination would not by itself identify a vaccine effect. The vaccine had to be tested against a control group in the same year. The question was how to choose the controls.

The National Foundation for Infantile Paralysis, which had funded the vaccine, proposed an observed-control design: vaccinate the second-graders whose parents consented, and compare them with the first- and third-graders, who were not offered the vaccine. No placebo, and the doctors diagnosing polio would know who had been vaccinated. Francis, and many state health officers, insisted on a randomized design instead. Among children whose parents consented, a random draw decided who got the vaccine and who got an injection of salt water that looked identical, and neither the families nor the diagnosing doctors knew which was which. The compromise was to run both: the observed-control design in some states, the randomized one in others.

The results, as Paul Meier summarized them in 1972, in cases of paralytic polio per hundred thousand children. In the randomized areas: twenty-eight among the vaccinated, seventy-one among the placebo group, and forty-six among the children whose parents refused. In the observed-control areas: twenty-five among vaccinated second-graders, fifty-four among the first- and third-grade controls, and forty-four among second-graders who did not consent. The randomized comparison estimates forty-three paralytic cases prevented per hundred thousand. The textbook sample sizes shown here are rounded. The observed-control comparison shows only twenty-nine. The observed-control risk difference is about a third smaller. These were different areas, so that gap alone does not identify the exact selection bias.

Why the difference? Consent was not random. The families who volunteered their children were, on average, wealthier and better educated. And polio was, paradoxically, a disease of hygiene: children from cleaner homes met the virus later in childhood, without their mothers' antibodies, and suffered worse infections. So the vaccinated second-graders were drawn from the families most at risk, while their controls included everyone. The comparison mixed the vaccine's effect with the difference between the kinds of family. The randomized areas illustrate the selection problem: children whose parents refused had forty-six cases per hundred thousand, far fewer than the seventy-one among the consenting children who got placebo.

There was a second problem. Many cases of polio were mild, and the diagnosis was a judgement. A doctor who knew that a child had been vaccinated might be readier to call the same symptoms something else. The placebo, and the blinding of families and doctors, closed that path as well. On the twelfth of April 1955, Francis announced the result: the vaccine was safe, effective and potent. The randomized half of the trial is the part that statisticians still cite.

But what does it mean to say the vaccine prevented forty-three cases per hundred thousand? It means: compared with what would have happened to the same children without it. That comparison can never be observed; each child was either vaccinated or not. Randomization lets us estimate it anyway. This part makes that precise, with the language of potential outcomes, and then follows experiments into the places where they become difficult.

Numbers: 43 vs 29 per 100,000

1Potential outcomesBachelor's4 min

The language comes from Jerzy Neyman's master's thesis of 1923. Writing about field trials, he imagined, for each plot of land, the yield it would give under each variety of seed, only one of which could be sown. The thesis was written in Polish and was not translated into English until 1990. Donald Rubin reinvented and extended the idea from 1974 onward, for observational studies and for people, and in 1986 Paul Holland named it the Rubin causal model and stated its central difficulty.

For each unit i, say a patient, there are two potential outcomes: the outcome if treated, Y i of one, and the outcome if not, Y i of zero. Both are fixed properties of the patient, defined before any treatment is given. The causal effect of the treatment on this patient is their difference, tau i. What we observe depends on the assignment Z i: the treated outcome if Z is one, the untreated outcome if Z is zero. In Neyman's design-based view, the table of all the potential outcomes, which Rubin calls the science, is fixed. The only randomness is in who gets treated.

This part's patients come from the World. Two thousand adults with untreated high blood pressure enrol in a trial of a new drug. The outcome is their systolic pressure after twelve weeks. Each has a pressure they would have without the drug, and a pressure they would have with it. Because the World is a simulation, we know both, for every patient. No real trial ever has this table; we will use it to check every method against the truth.

Here is the science table for the first eight patients, with their ages. In blue, the pressure each would have at twelve weeks without the drug. In red, with it. And in gold, each patient's own causal effect: the drug lowers the pressure of patient two by four points, of patient four by fifteen. The effects differ from person to person.

Now run the trial. A coin decides each patient's arm. For the treated patients we see the pressure with the drug, and the pressure they would have had without it disappears. For the controls, the reverse. Half of the science table is now missing, and every single individual effect is gone, because each needs both columns.

Over all two thousand patients, the individual effects form a distribution. On average the drug lowers the pressure at twelve weeks by millimetres of mercury. But the effects vary, with a standard deviation of nearly five, because the drug works better at higher pressures and greater ages. And for about four percent of patients, the drug would make things slightly worse. A real trial can estimate the average; as we will see, it cannot tell us who those four percent are.

Holland called this the fundamental problem of causal inference: we never observe both potential outcomes for the same unit. Causal inference is therefore a missing-data problem, with half of the science always missing, and Part 41 will treat missing data in general. Holland also insisted on no causation without manipulation: a potential outcome needs a treatment that could, at least in principle, be applied; the effect of a person's sex or race is a harder notion. The way forward is to give up on individual effects, aim at averages over units, and let the design of the study tell us which missing outcomes look like which observed ones.

Numbers: mean τ −7.83, SD 4.75, 4.3% harmed

2Estimands and SUTVAMaster's4 min

Estimands, and the stable unit treatment value assumption. Because individual effects are out of reach, we choose an average to estimate: an estimand. The sample average treatment effect averages tau over the units in the study. The average effect on the treated averages it over those who actually received the treatment, which matters when the treated are chosen rather than random. The conditional average effect averages within a kind of unit, say patients of a given age: the basis of personalized medicine, and of Part 62. And the population average treatment effect refers to some larger population. Direct generalization needs representative effects; otherwise transport requires additional measured covariates and assumptions, as chapter fourteen explains.

In the World these are just numbers. The sample average effect in the trial is minus millimetres. Among all islanders who would have been eligible, it is minus . They differ because younger people were likelier to enrol: the trial's patients average years, the eligible islanders . Since the drug works better in older and sicker patients, these are two different, equally honest estimands, and a study should say which it is after.

Writing Y i of one and Y i of zero hides an assumption. In general a unit's outcome could depend on everyone's treatment. Rubin's stable unit treatment value assumption, SUTVA, says it depends only on its own. That has two parts. No interference: my outcome does not depend on whether you were treated. Vaccines, which protect the neighbours of the vaccinated, break it, and chapter ten deals with them. And no hidden versions of the treatment: there is one Y i of one, not one for each dose, surgeon or brand. Without SUTVA, each unit has two to the n potential outcomes, one for every assignment of the whole study, so learning requires a design and restrictions on which assignments affect which outcomes. Chapter ten gives an example.

Hidden versions matter most when the treatment is not something we do. What is the effect of obesity on mortality? Losing weight by diet, by surgery, by exercise and by illness are different interventions, each with its own potential outcomes and its own effect. Miguel Hernán and Sarah Taubman argued in 2008 that such questions have no single answer until the intervention is specified. The remedy, which Part 36 will turn into a method, is to name the trial you would run if you could: the target trial.

For a yes-or-no outcome there are several estimands. With our treated-minus-control convention, the risk difference is negative for cases prevented. The risk ratio is the proportion of risk that remains. The odds ratio, the natural parameter of logistic regression, has a strange property: it is not collapsible, so the odds ratio in a whole population need not be any average of the odds ratios in its subgroups, even without confounding. For the Salk trial, the treated-minus-control risk difference was minus forty-three per hundred thousand, and the risk ratio point three nine: the vaccine prevented about sixty percent of paralytic cases.

Numbers: SATE −7.83 vs PATE −9.93

3Why randomization worksBachelor's4 min

Here is the whole argument. The difference in average outcomes between treated and untreated is the average treated outcome among the treated minus the average untreated outcome among the untreated. Add and subtract what the treated would have had without treatment. The difference splits into the average effect on the treated, plus a selection bias: how the treated would have differed from the untreated even without treatment. If the assignment is independent of the potential outcomes, the selection bias is zero and the effect on the treated equals the average effect. A coin achieves that independence by construction, because it knows nothing about the patients. Nothing else is guaranteed to.

Watch it happen on the World's patients. Suppose that instead of a trial, doctors prescribe the drug as they see fit. A sensible doctor prescribes it to the patients whose pressure is highest: the chance of a prescription rises steeply with the baseline reading. In the trial, a coin gives every patient the same one-half chance.

The results. When the doctor chooses, the treated patients started at an average of millimetres, the untreated at . Comparing their twelve-week pressures, the drug seems to lower pressure by only points. With the coin it lowers it by . The truth, known in the World, is an average effect of points, and among the patients the doctor treated, . So the doctor's comparison is the effect on the treated, minus nine and a half, plus a selection bias of over seven points: the treated would have had higher pressures anyway. The bias swamps most of the effect, and its interval is narrow and wrong.

In the design-based view the argument is even simpler. Under complete randomization, every patient has the same chance of treatment. Then the expected difference in means is exactly the sample average treatment effect: each unit's treated outcome appears in the treated mean with probability one half, and likewise its untreated outcome. The expectation is over the possible assignments, with the science held fixed. It assumes SUTVA, and nothing at all about how the outcomes are distributed: no normality, no linearity, no model.

Here the doctor's rule used only the baseline reading, which we recorded, so we could adjust for it. Real doctors also use what no data set records: how the patient looks, what they say, their history. A coin balances those unrecorded differences too, on average, which no adjustment can promise. Part 36 asks what can be done when there is no coin, and we must hope we have recorded enough.

One caution. Randomization does not make the two groups identical; it makes them exchangeable, alike in distribution. Any one draw can be unbalanced by chance, but that is chance, not bias, and it averages out. How large the chance imbalance is, is exactly what Neyman's variance measures, and what blocking reduces. And whether chance alone could explain what we saw is Fisher's question, next.

Numbers: −2.21 vs −8.41; bias +7.37

4Fisher's sharp nullMaster's4 min

Fisher's way round the missing half of the science was to test a hypothesis that fills it in. His null hypothesis is sharp: the treatment does nothing to anyone, so each patient's two potential outcomes are equal. Under that null the science is completely known: whatever we observed for a patient is what they would have had either way. So we can compute the test statistic, say the difference in means, for every assignment the coin might have produced, as in Parts 13 and 16. The p-value is the share of possible assignments giving a statistic at least as extreme as the one observed. It is exact for any sample size, and needs no model for the outcomes.

Try it on a pilot study: twelve of the World's patients, six assigned to the drug and six to control. By the luck of the draw, the drug group's pressures at twelve weeks are higher, by points. There are nine hundred and twenty-four ways to choose six of twelve. Under the sharp null, each would have produced its own difference, from the same twelve numbers.

Here are all nine hundred and twenty-four. The observed difference sits in the middle of them. The share at least as far from zero is , so nothing in this pilot is surprising if the drug does nothing. That is not evidence that it does nothing. The patients' pressures differ from one another by ten or twenty points, so this particular twelve-patient draw gives little evidence about an eight-point average effect.

Fisher's test also gives an interval. Any constant-effect hypothesis, that the drug changes everyone's pressure by exactly tau nought, is also sharp. It too fills in the science: subtract tau nought from the treated outcomes to get their untreated ones. Test each tau nought in turn, and keep those not rejected at ten percent. For the pilot, the interval runs from minus to plus points on our half-point grid. We enumerate all assignments at each grid value. This set targets a common constant effect; it is not a general confidence interval for the heterogeneous average effect in our World.

With all two thousand patients there are about ten to the six hundred possible assignments, so we sample ten thousand of them at random instead. The observed difference is minus points. The largest of the ten thousand null differences is only , and their standard deviation is half a point. None of the ten thousand sampled assignments is as extreme. The plus-one Monte Carlo p-value is one over ten thousand and one, strong evidence against the sharp null. This is simulation resolution, not a proven upper bound on the exact randomization p-value.

Fisher's null says the treatment affects no one. Neyman's says the effects average to zero. These are different questions: a drug that helps some patients and harms others equally has a zero average effect, but is far from null in Fisher's sense. The two men quarrelled about it, bitterly, at the Royal Statistical Society in 1935. Modern work, such as Jason Wu and Peng Ding's of 2021, shows how to studentize a randomization test so that it is exact for Fisher's null and asymptotically valid for Neyman's. Neyman's approach comes next.

Numbers: p = 0.82 (12); MC p = 1/10,001 (2,000)

5Neyman's varianceMaster's4 min

Neyman asked a different question from Fisher. Not whether the effect is zero, but how precisely the difference in means estimates the average effect, over repeated randomizations of the same fixed patients. It is unbiased, as we saw. Its variance, which Neyman derived by treating the treated group as a sample drawn without replacement from the patients, is S one squared over n one, plus S nought squared over n nought, minus S tau squared over n. The S's are the variances, across the patients, of the treated outcomes, the untreated outcomes, and the individual effects. The first two can be estimated from the two arms. The third cannot, because no patient shows us their effect. So the usual estimate drops it, and is too large on average: conservative.

If every patient had the same effect, S tau would be zero and the usual estimate would be exactly unbiased. When effects vary, it overstates the variance. The subtracted term reflects a finite population: a patient in the treated group is, by that fact, absent from the control group, and the two arms' errors partly cancel. If instead we want the average effect in a superpopulation from which the patients were sampled independently and identically, the extra sampling variation exactly restores the missing term, and the usual estimate is right. The conservative formula is the correct one for the population average.

In the World we can compute every term. The patients' treated and untreated outcomes vary with standard deviations of about ten; their individual effects, with a standard deviation of . The true standard deviation of the estimate, with a thousand patients per arm, is ; the conservative formula gives . Re-randomizing the same two thousand patients four thousand times gives , matching the true value. Here the effects vary much less than the outcomes do, so the conservative formula is only three percent too large.

The randomization distribution of the estimate, over four thousand draws of the coin. It is close to normal, with Neyman's standard deviation, as a finite-population central limit theorem predicts when neither arm is dominated by a few extreme units. Ninety percent intervals built from the conservative standard error cover the trial's average effect percent of the time: slightly above ninety percent in this example. A conservative variance supports asymptotic coverage under regularity; it does not by itself guarantee finite-sample normal-interval coverage.

The variance of the effects cannot be estimated, but it can be bounded, because we do know the distributions of the treated and untreated outcomes separately. Its smallest value consistent with those distributions comes from pairing the sorted treated outcomes with the sorted untreated ones. Peter Aronow, Donald Green and Donald Lee used this in 2014 to sharpen Neyman's variance estimate while retaining asymptotic validity under their regularity conditions. The lesson is more general: some features of the science, such as the exact share of patients harmed, are not generally identified by a parallel-arm randomized trial alone.

Numbers: 0.446 vs 0.458; 91.1%

6Blocking and pairingMaster's3 min

Part 13 blocked a field trial on the soil gradient. The same idea works for patients. A patient's baseline pressure strongly predicts their pressure twelve weeks later, with correlation . So sort the two thousand patients by baseline, cut them into ten blocks of two hundred, and randomize a hundred to each arm within every block. Then the arms cannot differ much in baseline by bad luck, because every block is split exactly in half.

The blocked estimate is the average of the ten within-block differences, weighted by the blocks' sizes. Its variance is the weighted sum of the blocks' Neyman variances, since each block is randomized separately. The differences between blocks, the high-pressure patients against the low, no longer enter at all. Roughly, the variance shrinks by the share of the outcome's variation that the blocks explain.

Fifteen hundred randomizations of each design on the World's patients. Complete randomization: a standard deviation of . Ten blocks: , which is a variance cut by two fifths, as if the trial had been sixty percent larger. Pairing the sorted patients two by two gains a little more. All three are unbiased; these baseline blocks improve precision in this example before any outcome is seen.

In a matched-pair design, the estimate is the average of the within-pair differences. Its variance is estimated from the spread of those differences. As Kosuke Imai showed in 2008, this is again conservative, by the variation in the pairs' true average effects. With one treated and one control unit per pair, there is no way to estimate the variance within a pair, Small blocks of four or more allow separate within-arm variance estimates; matched pairs instead use variation across pair differences.

A related design is rerandomization: draw the assignment, check the balance of the covariates, and if it is poor, draw again. Kari Lock Morgan and Rubin formalized it in 2012, accepting only draws whose Mahalanobis imbalance is below a threshold. Xinran Li, Ding and Rubin worked out its asymptotic theory in 2018: valid, and more precise, provided the analysis takes the acceptance rule into account. It is blocking for continuous covariates, in effect.

The rule of thumb is old: block what you can, and randomize what you cannot, in the words of George Box, William Hunter and Stuart Hunter. But often the covariates are only used after the trial, in the analysis. Is that as good?

Numbers: SD 0.448 → 0.351 → 0.342

7AdjustmentMaster's3 min

The usual way to use baseline covariates after a trial is Fisher's analysis of covariance: regress the outcome on the treatment indicator and the covariates. The coefficient on treatment is the adjusted estimate. The hope is that the covariates soak up outcome noise, as blocking would have. But nothing in the randomization says that the outcomes follow this linear model with a common slope and constant variance.

On the World's trial, with two thousand patients and equal arms, adjust for baseline pressure and age. Over six hundred randomizations, the unadjusted estimate has a standard deviation of . Both adjusted estimates have about . The variance falls by nearly two fifths, the same gain blocking achieved. Here the baseline covariates improve precision. Lin's result describes the asymptotic comparison under suitable conditions.

In 2008 David Freedman, analysing regression adjustment entirely within Neyman's framework, with no model for the outcomes, published three uncomfortable results. First, the adjusted estimate is biased, though only by something of order one over n. Second, when the arms are of unequal size and the treatment effect varies with the covariate, adjustment can actually make the estimate less precise. Third, the conventional regression standard error, which assumes a common slope and constant variance, can be wrong, even in very large samples.

Winston Lin, then a graduate student at Berkeley, answered in 2013. Centre the covariates, and interact them with the treatment indicator. That is the same as fitting a separate regression in each arm and comparing their predictions at the average covariate. And use Part 23's sandwich standard errors, the HC2 version. Lin proved that this estimate is, asymptotically, never less precise than the unadjusted difference in means, and that its sandwich standard error is consistent or conservative, all within Neyman's framework, with a fixed number of covariates, stable treatment fractions and regular finite-population moments. Interactions and robust errors address the efficiency and variance problems. Small finite-sample bias can still remain.

A design in Freedman's spirit: two hundred units, only fifty of them treated, with a treatment effect that grows with the covariate, and noise that grows with it too. Four thousand randomizations. Both adjustments improve on the unadjusted estimate here, Lin's by more. But ANCOVA's conventional standard error, , understates its real variability, , and its ninety percent intervals cover only percent of the time. Lin's sandwich error matches its variability, and covers percent.

The practical rules that came out of this exchange: choose the covariates before seeing any outcomes, and write them into the protocol, so that adjustment cannot become a fishing expedition. Interact them with treatment, and use sandwich standard errors. In small trials, adjust for a few strong predictors of the outcome only. The American Food and Drug Administration's 2023 guidance emphasizes prespecified prognostic covariates and appropriate standard errors. Interactions are allowed, rather than universally required.

Numbers: ANCOVA 84.8% vs Lin 90.6%

8Cluster randomizationPractice3 min

Some treatments can only be given to groups: a teaching method to a school, clean water to a village, a hygiene protocol to a hospital ward. Others could be given to individuals, but if neighbours share information, randomizing groups keeps the controls uncontaminated. So we randomize clusters: whole schools, villages or hospitals. The unit of randomization is then the cluster, and that fact must carry through to the analysis.

The World has four hundred schools, from Parts 23 and 25, with about sixty pupils each. A tutoring programme is randomized to half of them. In the World's science, it raises every pupil's score by twenty points, a fifth of a standard deviation. And schools differ: pupils in the same school resemble each other, through shared school effects and background. The unadjusted model's intraclass correlation includes both sources.

The mean of m correlated pupils varies more than the mean of m independent ones, by a factor of one plus m minus one times the intraclass correlation. That factor is Kish's design effect, from Part 18. Including school and pupil background variation, the unadjusted intraclass correlation is about point one seven. With about sixty pupils per school, it is about . So the trial's twenty-four thousand pupils carry information on the scale of only a few thousand independent ones. This equal-size formula is an approximation for these varying school sizes. The correlation looks small; its consequence is not.

Re-randomize the programme across the same four hundred schools a thousand times, and analyse each trial two ways. Treating the pupils as independent, the standard error averages points, and ninety percent intervals cover the true effect only percent of the time. Treating each school's mean as one observation, the standard error is , and the coverage is percent. The pupil-level standard error is about three times too small: roughly the square root of the design effect. School-level and pupil-level averages are different estimands in general; the constant treatment effect makes their targets equal here.

Jerome Cornfield wrote in 1978 that randomizing by cluster and then analysing as if individuals had been randomized is an exercise in self-deception. Valid analyses use the cluster means, or cluster-robust standard errors from Part 23, or the mixed models of Part 25. And at the design stage, the number that matters is the number of clusters, not of people; with only a handful of clusters, conventional cluster-robust approximations can be unreliable. Small-sample corrections, design-based randomization tests or a suitable wild cluster bootstrap need careful assessment.

Numbers: approximate deff 11.1; 35.6% vs 90.3%

9NoncomplianceMaster's4 min

In a real trial, the coin's assignment Z and the treatment actually taken, D, can differ. Some patients assigned the drug never take it; some assigned to control obtain it elsewhere. Z is random; D is not. It is chosen, by the patients, for reasons that may be related to their health. Different analyses target different effects. Intention to treat preserves randomization; a complier effect needs further assumptions.

Potential outcomes handle this by giving each patient two potential treatments too: what they would take if assigned to control, and if assigned to the drug. That sorts patients into principal strata. Compliers take the drug exactly when assigned it: percent of the World's patients. Never-takers never take it: percent. Always-takers get it regardless: percent. Defiers would do the opposite of their assignment; we assume there are none. The strata are different people. The never-takers tend to feel well, with lower pressure even untreated; the always-takers are the sickest. Individual stratum membership is only partly observed. Under monotonicity, a treated control is an always-taker and an untreated assigned patient is a never-taker; the other two observed groups mix strata.

One randomization of the World's trial, with real compliance. The intention-to-treat analysis compares the arms as randomized: minus . It is unbiased, but for the effect of being assigned the drug, diluted by everyone who did not take it. The as-treated analysis compares those who took the drug with those who did not: minus . The naive per-protocol analysis keeps observed adherers, a mixture of principal strata: minus . Both compare groups formed by the patients' choices, and both are biased. The instrumental variable estimate divides the intention-to-treat effect by the estimated first-stage treatment contrast: minus , against the compliers' true average effect of minus .

Why the ratio works. The intention-to-treat effect on the outcome averages over the strata. For never-takers and always-takers, the assignment does not change what they take, so, if the assignment has no effect except through the drug, their contribution is zero. Only compliers contribute, with their average effect, weighted by their share. The intention-to-treat effect on the treatment taken is exactly that share. So the ratio is the compliers' average causal effect, which Guido Imbens and Joshua Angrist called in 1994 the local average treatment effect. For the World's trial, minus five point six two over point six four nine, which is minus eight point six six.

The derivation used four assumptions. The assignment is randomized, which the trial guarantees. Exclusion: being assigned the drug changes the outcome only through taking it, which a placebo and blinding make plausible. Monotonicity: no one does the opposite of their assignment. And there must be some compliers; when there are few, the ratio becomes unstable, the weak-instrument problem of Part 37.

The local average treatment effect is the effect for compliers, a group whose full membership we cannot list from one assignment. The intention-to-treat effect answers the policy question: what happens if we offer this drug to such patients? The local effect answers a scientific one: what does the drug do for those who take it only when it is offered? Report both; and never report the as-treated comparison alone.

Numbers: ITT −5.62; IV −8.66; truth −8.13

10InterferencePhD4 min

A vaccine protects the person vaccinated, and also the people that person would otherwise have infected. So my chance of infection depends on whether you were vaccinated, and SUTVA fails. The same happens with classroom peers, with job-training programmes whose graduates compete for the same jobs, in social networks, and on online platforms where sellers and buyers interact. A workable compromise, which Michael Sobel called partial interference in 2006, assumes that units affect each other only within groups, such as towns, and not across them.

The World has an epidemic in its two hundred towns, with a hundred residents each in the study. A resident's chance of infection is the town's attack rate, times a factor for their own vaccination, times a factor for the share of their town that is vaccinated. Attack rates average about fifteen percent, higher in bigger towns. So the vaccine has a direct effect, through my own vaccination, and a spillover effect, through my neighbours'. With nobody vaccinated, percent of residents are infected; with everybody, .

To learn both effects, randomize twice. Michael Hudgens and Elizabeth Halloran set out the two-stage design in 2008. First, each town is randomly given a strategy: vaccinate thirty percent of its residents, or seventy. Then, within each town, a lottery decides which residents receive the vaccine.

Four effects can now be estimated, each a comparison of average infection rates. The direct effect compares vaccinated and unvaccinated residents within towns of the same strategy. The indirect, or spillover, effect compares unvaccinated residents of thirty-percent towns with unvaccinated residents of seventy-percent towns: protection from the neighbours alone. The total effect combines the two. And the overall effect compares whole towns under the two strategies, which is what a health ministry choosing a policy wants to know.

One run of the two-stage trial, with the truth computed from the World's potential outcomes. The direct effect is about eight points in the thirty-percent towns, and smaller, about six, in the seventy-percent towns, where the unvaccinated are already protected by their neighbours. The spillover effect is about three to four points: an unvaccinated person is noticeably safer in a well-vaccinated town. The overall effect of the higher coverage policy is about five points of infection risk for the average resident.

An ordinary individually randomized trial would vaccinate a random half of everyone. It estimates a direct effect, about points here, at fifty percent coverage. It says nothing about the spillover, which is the main argument for vaccinating whole populations. Worse, its direct effect is specific to its own coverage: in a population with different coverage, the vaccine's direct effect is different.

When the interference runs through a social network rather than fixed groups, the approach generalizes through exposure mappings, such as treated with k treated friends. Peter Aronow and Cyrus Samii showed in 2017 how to estimate effects of such exposures with Part 18's Horvitz–Thompson estimators, using each unit's known probability of each exposure under the design. Online marketplaces use switchback designs, randomizing over time, and cluster designs over geography. The lesson is to define the estimand for the interference you believe in, and randomize at the level it implies.

Numbers: direct 8.1, indirect 3.3, overall 5.4

11SubgroupsBachelor's3 min

The second International Study of Infarct Survival, ISIS-2, randomized seventeen thousand one hundred and eighty-seven patients with a suspected heart attack to aspirin or placebo, among other comparisons. Five weeks later, eight hundred and four of the aspirin patients had died of vascular causes, nine point four percent, against a thousand and sixteen on placebo, eleven point eight. A drug costing pennies cut deaths by about a fifth to a quarter: one of the great trials. When the paper went to The Lancet, the reviewers asked for analyses by subgroup.

The investigators, led by Richard Peto and Rory Collins, obliged, and added a subgroup analysis of their own, to make a point: by the patients' astrological sign. For patients born under Gemini or Libra, aspirin appeared slightly harmful, with a nine percent increase in deaths, not significant. For everyone else, a highly significant twenty-eight percent reduction. Should Geminis and Librans be denied aspirin? Of course not. Then why believe any other subgroup found the same way?

Simulate it. A trial the size of ISIS-2, in which aspirin lowers everyone's risk by the same two point four points. Split the patients into twelve star signs completely at random, about seven hundred per arm in each. In percent of such trials, at least one sign shows no benefit at all, or harm. And in percent, at least one sign's effect differs from the effect estimated in all other signs significantly at five percent: a publishable interaction, made of noise.

Here is one simulated trial, sign by sign. The true effect, the dashed line, is identical in all twelve. The estimates scatter from harm to five points of benefit, and some signs show no benefit. Each would make a headline.

The arithmetic: a subgroup with a twelfth of the patients has a standard error about the square root of twelve times larger. Comparing two subgroups multiplies it by root two again. For two equally sized subgroups, an interaction half the size of the overall effect needs about sixteen times the total sample size for comparable power. That is a separate calculation from splitting into twelve groups. Trials sized for a main effect can have very low power for interactions. And twelve looks is Part 33's multiplicity problem: something will turn up.

The rules trialists adopted: pre-specify a few subgroups, with a scientific reason, before seeing the data. Test whether the effect differs between subgroups, rather than whether it is significant within each one. And, in Salim Yusuf and colleagues' advice of 1991, believe the overall effect for everyone unless the evidence of a difference is strong. Real heterogeneity does exist, as the World's drug shows, and Part 62 estimates it with the care it needs.

Numbers: 58% / 44%

12Sequential trialsPractice4 min

A large trial runs for years, with patients enrolling throughout. If the drug clearly works, it is unethical to keep giving placebo; if it clearly harms, unethical to keep giving the drug. So independent data monitoring committees look at the accumulating data at planned interim analyses. But every look is another chance for random noise to cross the significance line.

How bad is it? Twenty thousand trials of a drug that does nothing, each tested at the usual five percent level after every equally spaced batch of patients. With one look, five percent of them declare success. With two, eight percent; five looks, fourteen; ten, nineteen; twenty, twenty-four. Peter Armitage and his colleagues published this table in 1969. By the law of the iterated logarithm, a trial that looks forever is certain eventually to cross: Part 33's forking paths, unfolding in time.

The cure is to raise the bar at each look, so that the chance of ever crossing it, under the null, is five percent in total. Stuart Pocock proposed in 1977 a constant bar: with five looks, a z of at every one. Peter O'Brien and Thomas Fleming proposed in 1979 a bar that starts very high, at the first look, and falls to at the last, barely above the fixed design's one point nine six. Both are computed by numerical integration of a joint normal reference model. The z statistics are Brownian motion divided by the square root of information; the canonical model is exact here and often asymptotic in real trials.

Two simulated trials against the O'Brien–Fleming boundary. In red, a drug with a real effect: its z statistic climbs, and crosses the boundary at look , so the trial stops early and the drug reaches patients sooner. In blue, a drug that does nothing: its z statistic wanders, never comes near the high early boundaries, and the trial runs to its planned end.

What does looking cost? Take an effect that the fixed design, with one analysis at the end, detects eighty percent of the time. Pocock's constant bar has power of only percent with the same maximum size, though when the drug works it tends to stop early, using on average percent of the planned patients. O'Brien and Fleming's bar keeps almost all the power, percent, because it spends almost nothing early, and still stops early often enough to save a fifth of the patients. That is why it became the standard.

Real committees cannot always look at exactly planned times. Gordon Lan and David DeMets solved that in 1983 with alpha-spending functions: decide in advance how much of the five percent may have been spent by each fraction of the information. One spending function mimics O'Brien and Fleming, spending almost nothing early; another mimics Pocock. At each look, the boundary is chosen to spend the increment under the canonical model. Timing must be fixed or depend on information in a way that preserves that null model; outcome-driven looks are not automatically licensed. For five equal looks the O'Brien–Fleming-type function gives boundaries of four point eight eight down to two point oh three, close to the original.

Two cautions. A trial stopped early for benefit tends to overstate the effect, because it stopped at a lucky high point: Part 33's winner's curse, in time. Trials also use futility boundaries, stopping when success has become unlikely. And a real monitoring committee weighs safety and outside evidence as well as the boundary. Part 58 goes further, with e-values and always-valid inference that allow looking at any time, as often as you like.

Numbers: 14.1%; Pocock 2.413; OBF 4.56 → 2.04

13SurrogatesPractice3 min

The outcomes that matter, strokes, heart attacks, deaths, take years and thousands of patients to count. Blood pressure, cholesterol, tumour size and viral load change within weeks. A surrogate endpoint is such an early measurement, standing in for the outcome that matters, so that trials can be smaller and faster. The hope is that a drug that improves the surrogate improves the outcome.

The cautionary tale is the Cardiac Arrhythmia Suppression Trial. After a heart attack, patients with frequent irregular heartbeats are more likely to die suddenly. The drugs encainide and flecainide suppressed those irregular beats superbly, and were widely prescribed on that basis. CAST randomized patients whose arrhythmias the drugs had suppressed to continue them or to switch to placebo. The trial was stopped early: after an average of ten months, sixty-three of the patients on the drugs had died, against twenty-six on placebo. The surrogate improved, and the patients died.

Ross Prentice set out criteria in 1989, the year CAST's first results appeared. First, the treatment must change the surrogate. Second, the surrogate must predict the outcome. Third, and crucially, once the surrogate is known, the treatment must tell us nothing more about the outcome: this is a statistical conditional-independence requirement. It is not by itself an identified causal mediation statement. Failure can reflect another pathway, confounding after conditioning on the surrogate, or model misspecification. Encainide and flecainide, it turned out, could themselves provoke fatal arrhythmias.

Two invented drugs for the World's patients, each lowering twelve-week pressure by about eight points. A patient's five-year risk of stroke rises with their twelve-week pressure. Drug A acts only through pressure. Drug B has, in addition, an off-target harm, as CAST's drugs did.

A trial of each, with stroke counted. The surrogate cannot tell them apart: both lower pressure by about eight points. The outcome can: drug A cuts strokes from to percent; drug B raises them, from to . These linear-regression diagnostics are inspired by Prentice's conditions, rather than complete tests of them. Drug B retains a strong treatment coefficient after pressure adjustment. Drug A's small coefficient does not prove conditional independence. We know their mechanisms because we specified this toy model.

The lesson is that a surrogate is valid for a mechanism, not for every drug that moves it. Thomas Fleming and David DeMets, in a 1996 paper titled Surrogate end points in clinical trials: are we being misled?, collected the failures. Modern validation uses meta-analyses of many trials, asking whether the effects on the surrogate predict the effects on the outcome across drugs, as in Marc Buyse and colleagues' work of 2000. Prentice's conditional-independence criterion and causal mediation are distinct. A causal interpretation needs additional assumptions, because the surrogate itself is not randomized; Part 36 develops that point.

Numbers: CAST 63 vs 26; drug B 8.4% vs 4.9%

14External validityPractice3 min

Randomization gives internal validity: the right answer for the patients in the trial. But trial patients are volunteers, usually younger and healthier than the patients who will eventually take the drug, and they live near hospitals that run trials. If the effect varies between kinds of patient, the answer for them is not the answer for everyone. External validity is the problem of carrying a trial's result to a target population.

In the World, younger patients were likelier to enrol. The eligible islanders are much older: most are over sixty-five. Since the drug works better in older and sicker patients, the average effect among the eligible islanders is minus , against minus in the trial. A perfectly run trial answers the wrong population's question.

The method stacks the trial patients and a sample of the target population, and models the probability of being in the trial given covariates. It assumes that, given those covariates, trial membership tells us nothing more about the effect: all the effect modifiers are measured. And it needs overlap: every target covariate pattern needs a positive probability of trial participation. Each trial patient is weighted by the inverse odds of participation, so that the weighted trial looks like the target. With constant randomized treatment probabilities and a correctly estimated participation density ratio, the weighted difference consistently estimates the target average effect. Elizabeth Stuart and colleagues proposed propensity scores for this in 2011, and Issa Dahabreh and colleagues worked out its theory in 2019.

The trial, analysed as usual, estimates minus , close to its own patients' average effect. Now weight it to twenty thousand of the eligible islanders, using age, baseline pressure, sex and body-mass index. The transported estimate is minus , most of the way to the island's true minus ; this remaining gap alone does not diagnose bias. We have not computed a transported interval, and cannot declare it within uncertainty. The price is precision: the weights are uneven, and uneven weights reduce the effective sample size; that number alone is not a confidence interval.

The weakness is overlap. Islanders over eighty are a large share of the target, and almost absent from the trial. The few who did enrol carry enormous weights, and if none had, no weighting could recover their effect. An unmeasured effect modifier that also predicts participation can break exchangeability without an observed warning. Misspecifying the participation model can also bias this estimator. The design answer is a pragmatic trial, which enrols the kinds of patients who will actually be treated, in the places they will be treated.

So internal validity comes from the coin. External validity needs assumptions about what was measured, exactly as observational studies always do. Which is where Part 36 begins.

Numbers: −8.05 → −9.07 (truth −9.93)

Recap, problems, and the road aheadAll tracks3 min

Part thirty-five in twelve lines. The Salk trial ran two designs, and the randomized comparison avoids the selection bias that threatens the observed-control comparison. A causal effect compares potential outcomes, and the science table is always half missing. Estimands must be named, and SUTVA rules out interference and hidden versions. When a doctor chooses, selection bias swallows most of the effect; a coin removes it. Fisher's sharp null gives exact tests; Neyman's conservative variance gives intervals for the average effect. Blocking and pairing cut the variance by two fifths. Regression adjustment helps, provided we interact and use sandwich errors, as Lin showed against Freedman's warning. Randomizing schools means analysing schools. With noncompliance, intention to treat and the local average treatment effect are honest; as-treated is not. Vaccination strategies with spillovers can be studied with two-stage designs; subgroups need suspicion; interim looks need boundaries. Surrogates can mislead, and trials must be transported to the people who will use them.

A promise for later. This part showed that randomization identifies average causal effects with no model for the outcomes. It assumed that we can randomize, and, apart from chapter nine, that patients do as they are assigned. Part 36 asks what can be learned when no one randomized at all: unconfoundedness, propensity scores, causal diagrams, and how sensitive the conclusions are to what was not measured.

Where it comes back. Part 36 estimates causal effects without randomization, framed as target trials. Part 37 uses natural experiments and instruments, the LATE's home. Part 40 analyses survival endpoints. Part 41 handles patients who drop out. Part 49 finds the most efficient estimator of an average effect. Part 58 makes sequential testing valid at any time. Part 62 estimates heterogeneous effects, interference and mediation. And Part 63 asks what counterfactual fairness means.

Six problems, with full solutions in the README. The unbiasedness of the difference in means; Neyman's variance; the conservativeness of its estimate; the local average treatment effect; the false-positive rate of two looks; and the design effect. Pause here if you want to try them.

The books this part follows: Imbens and Rubin's Causal Inference; Peng Ding's First Course in Causal Inference; Rosenbaum's Design of Observational Studies and Gerber and Green's Field Experiments; and Jennison and Turnbull on group sequential methods; with the papers from Neyman to Dahabreh.

Thirty-five parts of sixty-five. We know what a causal effect is, and why a coin lets us measure it. But most questions about causes, smoking and cancer, schooling and income, policy and growth, can never be put to a coin. Part 36: causes without experiments.

Where it goes next. Unconfoundedness replaces the coin in Part 36; instruments and the LATE return in Part 37; survival endpoints in Part 40; dropout in Part 41; efficient estimation of average effects in Part 49; anytime-valid monitoring in Part 58; interference and heterogeneity in Part 62.

Key results

The part's results in one place, for revision.

Selection bias\(\displaystyle \mathbb E[Y\mid D=1]-\mathbb E[Y\mid D=0]=\underbrace{\mathbb E[Y(1)-Y(0)\mid D=1]}_{\text{ATT}}+\underbrace{\mathbb E[Y(0)\mid D=1]-\mathbb E[Y(0)\mid D=0]}_{\text{selection bias}}\)
Fisher's exact p-value\(\displaystyle p=\frac{\#\{z:\ |T(z)|\ge|T(z^{\text{obs}})|\}}{\binom{n}{n_1}}\quad\allowbreak \text{under }Y_i(1)=Y_i(0)\text{ for }\allowbreak \text{every }i\)
Neyman's variance\(\displaystyle \operatorname{Var}(\hat\tau)=\frac{S_1^2}{n_1}+\frac{S_0^2}{n_0}-\frac{S_\tau^2}{n}\ \le\ \frac{S_1^2}{n_1}+\frac{S_0^2}{n_0}\)
Design effect\(\displaystyle \operatorname{deff}=1+(\bar m-1)\,\rho_{\text{ICC}}\)
Complier average effect\(\displaystyle \frac{\mathbb E[Y\mid Z=1]-\mathbb E[Y\mid Z=0]}{\mathbb E[D\mid Z=1]-\mathbb E[D\mid Z=0]}=\mathbb E\bigl[Y(1)-Y(0)\mid\text{complier}\bigr]\)

Try it

Lab 35 · One science table, four thousand coins

Fix both potential outcomes of 200 patients, assign 100 to treatment by a coin four thousand times, and compare the spread of the difference in means with Neyman's exact variance and with the conservative estimate a real trial can compute; then let a doctor choose who is treated and measure the selection bias.

Figure produced by Lab 35: One science table, four thousand coins
Produced by the lab below, seed 0, in 1.3 s.
python -m videos.stats.labs 35 needs numpy, scipy, matplotlib · download lab35.py · source on GitHub
average effect in this table (SATE), SD of the effects        -8.03, 4.53 mm Hg
mean of 4,000 randomized estimates                            -8.01   (unbiased: -8.03)
SD of the estimates                                           1.485   (Neyman's exact 1.492)
root mean estimated variance                                  1.526   (conservative 1.526)
90% interval covers the SATE                                  90.6%   (at least 90%)
doctor treats the 100 highest baselines: difference in means  1.79
  = effect on the treated + selection bias                    -10.26 + 12.05
Fisher's test when the drug does nothing: share of p <= 0.1   11.7%   (theory 10%)

Over the coin the difference in means is unbiased with exactly Neyman's variance; the variance a trial can estimate is larger by S_tau^2/n, which no trial can see. Without the coin the same subtraction measures mostly who was chosen.
The code (107 lines; it asserts its own result)
"""Lab 35: re-randomize a trial whose science table is known, and check Neyman's variance and Fisher's test."""

import numpy as np
from scipy import stats

from videos.coursekit import labs
from explainer.stats.kit import causal

TITLE = "One science table, four thousand coins"
GOAL = ("Fix both potential outcomes of 200 patients, assign 100 to treatment by a coin four thousand times, and compare "
        "the spread of the difference in means with Neyman's exact variance and with the conservative estimate a "
        "real trial can compute; then let a doctor choose who is treated and measure the selection bias.")
TASKS = [
    "Set the effect's SD to 0 (a constant effect). Check that the conservative variance becomes exact and coverage falls to 90%.",
    "Block on the baseline: sort by y0's baseline covariate, randomize within ten blocks, and use causal.blocked. How much smaller is the SD?",
    "Enumerate all 924 assignments of 12 patients with causal.fisher_test (reps=None) under the sharp null. Is the p-value exactly uniform on its grid?",
]

N, N1 = 200, 100


def science(rng, sd_tau):
    """Potential outcomes (systolic pressure, mm Hg): a baseline, an untreated outcome, an effect that varies."""
    base = rng.normal(150, 12, N)
    y0 = 0.7 * (base - 150) + 148 + rng.normal(0, 8, N)
    tau = -8 - 0.25 * (base - 150) * (sd_tau / 4.75) + rng.normal(0, 0.77 * sd_tau, N)  # sicker patients gain more
    return base, y0, y0 + tau


def rerandomize(y0, y1, rng, reps):
    est, se, cover = np.empty(reps), np.empty(reps), 0
    sate = float(np.mean(y1 - y0))
    for r, z in enumerate(causal.complete_assignments(N, N1, rng, reps)):
        d = causal.diff_means(np.where(z, y1, y0), z)
        est[r], se[r] = d["est"], d["se"]
        cover += d["lo"] <= sate <= d["hi"]
    return est, se, cover / reps


def run(seed=0):
    rng = np.random.default_rng(seed)
    reps = 4000
    lab = labs.Lab()
    base, y0, y1 = science(rng, 4.75)
    v = causal.neyman_true_var(y0, y1, N1)
    est, se, cover = rerandomize(y0, y1, rng, reps)
    lab.row("average effect in this table (SATE), SD of the effects", f"{v['ate']:.2f}, {np.sqrt(v['S_tau2']):.2f} mm Hg")
    lab.row("mean of 4,000 randomized estimates", f"{est.mean():.2f}   (unbiased: {v['ate']:.2f})")
    lab.row("SD of the estimates", f"{est.std(ddof=1):.3f}   (Neyman's exact {np.sqrt(v['true']):.3f})")
    lab.row("root mean estimated variance", f"{np.sqrt(np.mean(se ** 2)):.3f}   (conservative {np.sqrt(v['conservative']):.3f})")
    lab.row("90% interval covers the SATE", f"{cover:.1%}   (at least 90%)")
    sd = est.std(ddof=1)
    assert abs(est.mean() - v["ate"]) < 4 * sd / np.sqrt(reps), "the difference in means is unbiased over the coin"
    assert abs(sd / np.sqrt(v["true"]) - 1) < 0.05, "its variance is S1^2/n1 + S0^2/n0 - S_tau^2/n"
    assert abs(np.mean(se ** 2) / v["conservative"] - 1) < 0.02, "the estimator's expectation drops the last term"
    assert v["conservative"] > v["true"] and cover > 0.885, "so intervals are conservative"

    # a doctor instead of a coin: treat the 100 patients with the highest baseline pressure
    zd = base >= np.sort(base)[N - N1]
    naive = causal.diff_means(np.where(zd, y1, y0), zd)["est"]
    att = float(np.mean((y1 - y0)[zd]))
    bias = float(y0[zd].mean() - y0[~zd].mean())
    lab.row("doctor treats the 100 highest baselines: difference in means", f"{naive:.2f}")
    lab.row("  = effect on the treated + selection bias", f"{att:.2f} + {bias:.2f}")
    assert abs(naive - (att + bias)) < 1e-9 and bias > 5, "the identity is exact, and the bias is large"

    # Fisher: under the sharp null the randomization p-value is uniform
    pv = []
    for _ in range(300):
        z = np.zeros(N, bool)
        z[rng.choice(N, N1, replace=False)] = True
        pv.append(causal.fisher_test(y0, z, reps=199, rng=rng)["p"])  # outcome y0 for everyone: no effect at all
    size = float(np.mean(np.array(pv) <= 0.1))
    lab.row("Fisher's test when the drug does nothing: share of p <= 0.1", f"{size:.1%}   (theory 10%)")
    assert abs(size - 0.1) < 0.06
    lab.note = ("Over the coin the difference in means is unbiased with exactly Neyman's variance; the variance a trial "
                "can estimate is larger by S_tau^2/n, which no trial can see. Without the coin the same subtraction "
                "measures mostly who was chosen.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    grid = np.linspace(est.min(), est.max(), 200)
    ax[0].hist(est, bins=50, density=True, color=labs.BLUE, alpha=0.6, label="4,000 re-randomizations")
    ax[0].plot(grid, stats.norm.pdf(grid, v["ate"], np.sqrt(v["true"])), color=labs.GREEN, label="normal, Neyman's exact SD")
    ax[0].plot(grid, stats.norm.pdf(grid, v["ate"], np.sqrt(v["conservative"])), color=labs.RED, ls="--",
               label="normal, conservative SD")
    ax[0].axvline(v["ate"], color=labs.GOLD, label="the SATE")
    ax[0].axvline(naive, color=labs.ORANGE, ls=":", label="the doctor's comparison")
    ax[0].set(title="The difference in means over the coin", xlabel="estimated effect (mm Hg)", ylabel="density",
              ylim=(0, 1.75 * stats.norm.pdf(0, 0, np.sqrt(v["true"]))))
    ax[0].legend(loc="upper center", ncol=2)
    sds = np.array([0.0, 2.0, 4.75, 8.0, 12.0])
    ratio_th, ratio_mc = [], []
    for s in sds:
        _, a0, a1 = science(rng, s)
        w = causal.neyman_true_var(a0, a1, N1)
        z = rng.permuted(np.tile(np.arange(N) < N1, (8000, 1)), axis=1)  # 8,000 coins at once
        e = (z @ a1) / N1 - (~z @ a0) / (N - N1)
        ratio_th.append(np.sqrt(w["conservative"] / w["true"]))
        ratio_mc.append(np.sqrt(w["conservative"]) / e.std(ddof=1))
    ax[1].plot(sds, ratio_th, "o-", color=labs.GOLD, label="theory: conservative SD / exact SD")
    ax[1].plot(sds, ratio_mc, "s", color=labs.BLUE, label="conservative SD / simulated SD (8,000 coins)")
    ax[1].axhline(1, color=labs.MUTED, ls="--")
    ax[1].set(title="How conservative, as effects vary more", xlabel="SD of the individual effects (mm Hg)",
              ylabel="ratio of standard deviations", ylim=(0.97, 1.25))
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Set the effect's SD to 0 (a constant effect). Check that the conservative variance becomes exact and coverage falls to 90%.
  2. Block on the baseline: sort by y0's baseline covariate, randomize within ten blocks, and use causal.blocked. How much smaller is the SD?
  3. Enumerate all 924 assignments of 12 patients with causal.fisher_test (reps=None) under the sharp null. Is the p-value exactly uniform on its grid?

Problems, with solutions

Try each problem before opening its solution.

  1. Unbiasedness. Show that under complete randomization \(E(\bar Y_1 - \bar Y_0) = \bar\tau\), with the science fixed.

    Solution

    Under complete randomization P(Z_i = 1) = n₁/n.

    • Ȳ₁ = Σ Z_i Y_i(1)/n₁, so E Ȳ₁ = Σ (n₁/n) Y_i(1)/n₁ = Ȳ(1). Likewise E Ȳ₀ = Ȳ(0).
    • Hence E(Ȳ₁ − Ȳ₀) = τ̄.
  2. Neyman's variance. Derive \(\mathrm{Var}(\bar Y_1 - \bar Y_0) = S_1^2/n_1 + S_0^2/n_0 - S_\tau^2/n\).

    Solution

    Ȳ₁ is the mean of a simple random sample of n₁ from the n values Y_i(1), so Var Ȳ₁ = (1 − n₁/n) S₁²/n₁; likewise Var Ȳ₀ = (1 − n₀/n) S₀²/n₀.

    • The covariance uses Cov(Z_i, Z_j) = −n₁n₀/(n²(n − 1)) for i ≠ j. It gives Cov(Ȳ₁, Ȳ₀) = −S₁₀/n, where S₁₀ is the finite-population covariance of Y(1) and Y(0).
    • Summing, with S_τ² = S₁² + S₀² − 2S₁₀: Var(Ȳ₁ − Ȳ₀) = S₁²/n₁ + S₀²/n₀ − S_τ²/n.
  3. Conservativeness. Show that \(E(s_1^2/n_1 + s_0^2/n_0)\) exceeds the true variance by \(S_\tau^2/n\).

    Solution

    Within-arm sample variances are unbiased for the finite-population variances under SRS: E s₁² = S₁² and E s₀² = S₀².

    • So E(s₁²/n₁ + s₀²/n₀) = S₁²/n₁ + S₀²/n₀ = Var + S_τ²/n ≥ Var, with equality if and only if τ is constant.
  4. LATE. Under randomization, exclusion and monotonicity, show that \(\mathrm{ITT}_Y/\mathrm{ITT}_D\) is the compliers' average effect.

    Solution
    • By randomization, ITT_Y = Σ_strata π_g E[Y(D(1)) − Y(D(0)) | g]. Exclusion lets Y depend on Z only through D.
    • For never- and always-takers D(1) = D(0), so their terms vanish; defiers are absent by monotonicity. That leaves ITT_Y = π_c E[Y(1) − Y(0) | complier].
    • Similarly ITT_D = E[D(1) − D(0)] = π_c. So the ratio is the compliers' average effect.
  5. Two looks. Show that \(K\) looks at \(|z| > 1.96\) give a false-positive rate above 5% for \(K = 2\), and find it.

    Solution

    Z₁ = S_n/√n and Z₂ = S_{2n}/√(2n) are bivariate normal with correlation √(1/2).

    • The false-positive rate is P(|Z₁| > 1.96 or |Z₂| > 1.96) = 1 − P(|Z₁| ≤ 1.96, |Z₂| ≤ 1.96).
    • Numerically this is 0.083, above 0.05 because the two events are not nested (the kit's crossing_probs gives about 0.083; the simulation 8.2%).
  6. Design effect. Show that the design effect of equal clusters of size \(m\) with correlation \(\rho\) is \(1 + (m-1)\rho\).

    Solution

    For a cluster mean of m units with common variance σ² and pairwise correlation ρ:

    • Var = m⁻²(mσ² + m(m − 1)ρσ²) = (σ²/m)(1 + (m − 1)ρ).
    • Relative to m independent units, the factor is 1 + (m − 1)ρ.

Notes and sources

Where it comes back

  • Part 36: causal effects without randomization; target trials; mediation.
  • Part 37: instruments and natural experiments, the LATE's home.
  • Part 40: survival endpoints in trials.
  • Part 41: missing outcomes and dropout.
  • Part 49: efficient estimation of average effects.
  • Part 58: anytime-valid sequential inference.
  • Part 62: heterogeneous effects, interference and mediation.
  • Part 63: counterfactual fairness.

The sequential teaching calculations use smooth Gauss–Legendre continuation quadrature, checked at 80 and 160 nodes. Canonical normal/Brownian assumptions underlie the boundaries. Alpha spending does not authorize arbitrary outcome-driven analysis times. All Board repetitions are independent trial-level indicators; the plotted Monte Carlo scale uses the nominal reference probability. Transport uses a working participation model and gives a point estimate plus a weight effective sample size, without a transported confidence interval.

Glossary

  • Potential outcomes: Y_i(1), Y_i(0), the outcomes unit i would have under each treatment.
  • Science table: all units' potential outcomes; half is always missing.
  • Fundamental problem of causal inference: no unit reveals both.
  • SATE / ATT / CATE / PATE: the average effect in the sample / among the treated / given covariates / in a population.
  • SUTVA: no interference and no hidden versions of treatment.
  • Selection bias: E[Y(0) | Z = 1] − E[Y(0) | Z = 0].
  • Sharp null: Y_i(1) = Y_i(0) for every i (Fisher); the weak null is τ̄ = 0 (Neyman).
  • Randomization distribution: a statistic's values over all assignments.
  • Neyman variance: S₁²/n₁ + S₀²/n₀ − S_τ²/n; the usual estimate drops the last term.
  • Blocking / pairing / rerandomization: designs that restrict covariate imbalance; blocking still permits within-block imbalance.
  • Lin estimator: the treatment-by-centred-covariate interacted regression with HC2 SEs.
  • Design effect: 1 + (m − 1)ρ for equal cluster sizes and exchangeable correlations; ICC ρ.
  • Principal strata: compliers, never-takers, always-takers, defiers.
  • ITT / LATE (CACE): the effect of assignment / of treatment among compliers.
  • Interference; direct / indirect / total / overall effects: Hudgens–Halloran's decomposition under two-stage randomization.
  • Group-sequential boundary; alpha spending: interim thresholds preserving the overall size.
  • Surrogate endpoint; Prentice criteria: an early outcome standing in for the one that matters; statistical conditions require validation and do not by themselves identify causal mediation.
  • Transportability: carrying an effect to a target population; positivity.

Sources

  • Salk. T. Francis et al., Am. J. Public Health 45 (1955); P. Meier, in Statistics: A Guide to the Unknown (1972); D. Freedman, R. Pisani & R. Purves, Statistics, ch. 1.
  • Potential outcomes.
    • J. Neyman (1923), trans. D. Dabrowska & T. Speed, Stat. Sci. 5 (1990).
    • D. Rubin, J. Educ. Psychol. 66 (1974), JASA 75 (1980); P. Holland, JASA 81 (1986).
    • M. Hernán & S. Taubman, Int. J. Obes. 32 (2008); S. Greenland, J. Robins & J. Pearl, Stat. Sci. 14 (1999).
  • Randomization inference.
    • R. A. Fisher, The Design of Experiments (1935); J. Neyman, JRSS Suppl. 2 (1935) and the discussion.
    • J. Wu & P. Ding, JASA 116 (2021); P. Aronow, D. Green & D. Lee, Ann. Stat. 42 (2014).
  • Design.
    • K. Imai, Stat. Med. 27 (2008); K. Morgan & D. Rubin, Ann. Stat. 40 (2012); X. Li, P. Ding & D. Rubin, PNAS 115 (2018).
    • G. Box, W. Hunter & J. S. Hunter, Statistics for Experimenters (1978).
  • Adjustment.
    • D. Freedman, Adv. Appl. Math. 40 (2008), Ann. Appl. Stat. 2 (2008); W. Lin, Ann. Appl. Stat. 7 (2013).
    • FDA, Adjusting for Covariates in Randomized Clinical Trials (2023).
  • Clusters. J. Cornfield, Am. J. Epidemiol. 108 (1978); L. Kish, Survey Sampling (1965).
  • Noncompliance. G. Imbens & J. Angrist, Econometrica 62 (1994); J. Angrist, G. Imbens & D. Rubin, JASA 91 (1996); C. Frangakis & D. Rubin, Biometrics 58 (2002).
  • Interference.
    • M. Sobel, JASA 101 (2006); M. Hudgens & M. E. Halloran, JASA 103 (2008).
    • P. Aronow & C. Samii, Ann. Appl. Stat. 11 (2017).
  • Subgroups.
    • ISIS-2 Collaborative Group, Lancet 332 (1988).
    • S. Yusuf, J. Wittes, J. Probstfield & H. Tyroler, JAMA 266 (1991); P. Rothwell, Lancet 365 (2005).
  • Sequential.
    • P. Armitage, C. McPherson & B. Rowe, JRSS A 132 (1969); S. Pocock, Biometrika 64 (1977); P. O'Brien & T. Fleming, Biometrics 35 (1979).
    • K. Lan & D. DeMets, Biometrika 70 (1983); C. Jennison & B. Turnbull (1999).
  • Surrogates.
    • CAST Investigators, NEJM 321 (1989); D. Echt et al., NEJM 324 (1991).
    • R. Prentice, Stat. Med. 8 (1989); T. Fleming & D. DeMets, Ann. Intern. Med. 125 (1996); M. Buyse et al., Biostatistics 1 (2000).
  • Transport.
    • E. Stuart, S. Cole, C. Bradshaw & P. Leaf, JRSS A 174 (2011); I. Dahabreh, S. Robertson, E. Tchetgen Tchetgen, E. Stuart & M. Hernán, Biometrics 75 (2019).
    • D. Westreich et al., Am. J. Epidemiol. 186 (2017).
About this partfrom its README

Part 35 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the fifteenth part of Stage III, Master's. Part 34 made predictions honest, and ended with a model that predicted well and would have advised badly. This part asks what a causal effect is, and why randomization lets us measure one:

  • potential outcomes, and the World's clinic trial, in which both outcomes of every patient are known;
  • Fisher's and Neyman's randomization inference;
  • design and analysis: blocking, adjustment, clusters;
  • noncompliance, interference, subgroups, sequential monitoring, surrogates and transport.

The part builds:

  • the World's clinic trial (World.trial) and its epidemic (World.epidemic, World.infected);
  • statkit.causal (I);
  • an instrument, the science table (ScienceTable). It shows each unit's Y(0), Y(1) and τ, and the grey patches an assignment puts over the half it hides.

It opens with the 1954 Salk vaccine trial (Francis 1955; Meier 1972). In cases of paralytic polio per 100,000:

  • the randomized placebo-controlled design: 28 vaccinated vs 71 placebo (and 46 among children whose parents refused), an estimated 43 cases prevented per 100,000;
  • the observed-control design: 25 vs 54, an observed difference of 29. These different areas do not by themselves identify the exact bias. Consenting families were wealthier, and their children more at risk of polio.

From there the part covers:

  • Potential outcomes (Neyman 1923; Rubin 1974; Holland 1986).

    • The science table of eight of the World's patients; the trial's 2,000 individual effects have mean −7.83 mm Hg and SD 4.75, and 4.3% would be harmed.
    • The fundamental problem; well-defined interventions, including the scope of Holland’s manipulation criterion.
  • Estimands and SUTVA.

    • SATE, ATT, CATE, PATE. The trial's SATE is −7.83 against −9.93 among the 87,406 eligible islanders: the trial's patients average 58 years, the islanders 69.
    • Interference and hidden versions; ill-defined interventions (Hernán & Taubman 2008).
    • Risk difference, risk ratio and non-collapsible odds ratios; Salk's risk ratio is 0.39.
  • Why randomization works.

    • Difference in means = ATT + selection bias.
    • When doctors prescribe by pressure, the treated start at 152.3 against 145.3. The naive estimate is −2.21; the ATT is −9.58 and the selection bias +7.37. A coin gives −8.41.
  • Fisher's sharp null.

    • 12 patients, all 924 assignments: the observed +1.7 has p = 0.82, and exact enumeration on a half-point grid gives [−10.0, 13.5]. This targets a common constant effect; it is not a generally valid interval for the heterogeneous SATE.
    • All 2,000 patients by Monte Carlo: −7.21 against a sampled absolute null maximum of 2.12. Zero extreme draws out of 10,000 gives the plus-one Monte Carlo p-value 1/10,001, rather than a certified bound on the exact p-value.
    • Fisher vs Neyman nulls (Wu & Ding 2021).
  • Neyman's variance. S₁²/n₁ + S₀²/n₀ − S_τ²/n.

    • S_τ = 4.75; the true SD is 0.446, the conservative one 0.458, and 4,000 re-randomizations give 0.439.
    • 90% coverage is 91.1%.
    • The superpopulation view; Aronow, Green & Lee's bounds.
  • Blocking and pairing.

    • Ten blocks on baseline pressure (correlation 0.70 with Y(0)) take the SD from 0.448 to 0.351; matched pairs give 0.342.
    • Imai's pair variance; rerandomization (Morgan & Rubin 2012; Li, Ding & Rubin 2018).
  • Adjustment.

    • On the trial, adjusting for baseline and age takes the SD from 0.428 to 0.336.

    • Freedman's (2008) three critiques.

    • Lin's (2013) interacted regression with HC2, on a design with n = 200, 50 treated and heterogeneous, heteroskedastic effects:

      Estimate SD Mean SE 90% coverage
      ANCOVA 0.50 0.43 84.8%
      Lin 0.39 0.41 90.6%
      unadjusted 1.04
  • Cluster randomization. The World's 400 schools (24,157 pupils, unadjusted model ICC 0.171, mean size 60.4) give an approximate design effect of 11.1. The ICC includes shared school background and independent pupil background; 0.145 is the residual ICC conditional on those covariates. The design-effect formula is exact for equal sizes and an approximation here. Over 1,000 re-randomizations of the programme (true effect +20):

    Analysis SE 90% coverage
    pupil level 1.25 35.6%
    school level 4.17 90.3%

    Cornfield's 'self-deception'.

  • Noncompliance.

    • Compliance types: 64.5% compliers, 30.0% never-takers (lower Y(0)), 5.5% always-takers (higher).

    • One trial gives:

      Analysis Estimate
      intention to treat −5.62
      as treated −5.97
      per protocol −6.96
      IV (Wald), −5.62 / 0.649 −8.66
      true complier effect −8.13
    • LATE derived (Imbens & Angrist 1994; Angrist, Imbens & Rubin 1996).

  • Interference. The World's epidemic in 200 towns, with infection risk r_j(1 − 0.6v)(1 − 0.6s_j): 16.3% with no one vaccinated, 2.7% with everyone.

    • Hudgens & Halloran's two-stage design (30% vs 70%), estimates with the truth in brackets: direct 8.1 (7.9) and 6.5 (5.7) points, indirect 3.3 (3.8), total 9.7 (9.5), overall 5.4 (5.4).
    • An individually randomized trial sees only a 7.0-point direct effect.
    • Exposure mappings (Aronow & Samii 2017).
  • Subgroups.

    • ISIS-2: 804/8,587 (9.4%) vs 1,016/8,600 (11.8%). For Gemini and Libra, a 9% (SD 13) increase; for the other signs, a 28% (SD 5) reduction.
    • Twelve random 'signs' in a trial with one true effect: in 58% of trials some sign shows no benefit, and in 44% some subgroup-versus-complement interaction is 'significant'.
  • Sequential trials.

    • Peeking at 1.96 gives false-positive rates of 8.2%, 10.7%, 14.1%, 19.5% and 24.2% for 2, 3, 5, 10 and 20 looks.
    • Boundaries with K = 5: Pocock 2.413; O'Brien–Fleming 4.562 → 2.040; Lan–DeMets OBF-type spending 4.875 → 2.030.
    • Against an effect with 80% fixed-design power, Pocock has 71% power using 71% of the information; O'Brien–Fleming has 79% using 80%.
  • Surrogates.

    • CAST: 63 vs 26 deaths.
    • Prentice-inspired linear regression diagnostics, with two drugs that each lower pressure by about 8 points:
      • drug A: stroke 3.8% vs 5.3%, and the adjusted treatment coefficient is small (t = −0.09);
      • drug B: stroke 8.4% vs 4.9%, and the adjusted treatment coefficient is large (t = 4.8). A small coefficient does not establish conditional independence or causal surrogacy. The mechanisms are known because the example is simulated.
    • Fleming & DeMets (1996); Buyse et al. (2000).
  • External validity.

    • Inverse odds of participation weighting on age, pressure, sex and BMI moves the estimate from −8.05 to −9.07. The truth for the island is −9.93. The effective sample size is 988.
    • Positivity: over-80s are 21% of the island and 2.4% of the trial. Pragmatic trials.

Data:

  • the patients, schools and epidemic are the World's;
  • the Salk numbers use a rounded textbook summary, rather than exact participant counts; ISIS-2 and CAST totals match the primary reports;
  • the subgroup, Freedman and sequential examples are seeded simulations.

Built in this part:

  • statkit.causal (I) (explainer/stats/kit/causal.py), checked in tests/test_stats_kit_causal.py:
    • Randomization inference: Neyman's estimator with its exact and conservative variances (checked by enumeration); Fisher's exact and Monte Carlo randomization tests and their inversion.
    • Design and adjustment: blocked and paired estimators; ANCOVA and Lin's estimator with HC2; cluster-level analysis and the design effect.
    • Noncompliance and interference: the Wald/IV estimator with a delta-method SE; Hudgens–Halloran effects.
    • Sequential designs: crossing probabilities by numerical integration, with Pocock, O'Brien–Fleming and Lan–DeMets boundaries checked against published values; the peeking simulator.
    • Surrogates and transport: Prentice's criteria; inverse-odds transport.
  • The World gains trial, epidemic and infected(), and the Museum SALK, ISIS2 and CAST.
  • The science table (ScienceTable in explainer/stats/viz.py).

The Coverage Board gains eleven rows:

Method Setting Achieved Verdict
doctor chooses, difference in means World trial, n = 2,000 0.0% broken
randomized, Neyman 90% CI World trial 90.9% kept
ANCOVA, conventional SE Freedman's design, n = 200, 50 treated 84.8% broken
Lin, HC2 SE same 90.6% kept
pupil-level CI, school-randomized World schools 35.6% broken
school-level CI World schools 90.3% kept
as-treated comparison (for the complier effect) World trial 0.0% broken
IV (Wald) estimate World trial 91.2% kept
peeking at 1.96, 5 looks (size, 5%) null trials 14.1% broken
Pocock boundary null trials 5.05% kept
O'Brien–Fleming null trials 5.03% kept
Chapter notes
# Chapter Numbers
0 The Salk trial 43 vs 29 per 100,000
1 Potential outcomes mean τ −7.83, SD 4.75, 4.3% harmed
2 Estimands and SUTVA SATE −7.83 vs PATE −9.93
3 Why randomization works −2.21 vs −8.41; bias +7.37
4 Fisher's sharp null p = 0.82 (12); MC p = 1/10,001 (2,000)
5 Neyman's variance 0.446 vs 0.458; 91.1%
6 Blocking and pairing SD 0.448 → 0.351 → 0.342
7 Adjustment ANCOVA 84.8% vs Lin 90.6%
8 Cluster randomization approximate deff 11.1; 35.6% vs 90.3%
9 Noncompliance ITT −5.62; IV −8.66; truth −8.13
10 Interference direct 8.1, indirect 3.3, overall 5.4
11 Subgroups 58% / 44%
12 Sequential trials 14.1%; Pocock 2.413; OBF 4.56 → 2.04
13 Surrogates CAST 63 vs 26; drug B 8.4% vs 4.9%
14 External validity −8.05 → −9.07 (truth −9.93)
15 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: the Salk trial (1954) (Francis 1955; Meier 1972).
  2. Potential outcomes (Neyman 1923; Rubin 1974); Holland's fundamental problem (ScienceTable, revealed in the World).
  3. Estimands and SUTVA.
  4. Why randomization works. Selection bias measured (Board).
  5. Fisher's sharp null. Randomization inference.
  6. Neyman's variance. The conservative estimator, derived (Board).
  7. Blocking and pairing.
  8. Adjustment. Freedman (2008) and Lin (2013) (Board).
  9. Cluster randomization (Board).
  10. Noncompliance. Principal strata; LATE (Imbens & Angrist 1994), derived.
  11. Interference. Exposure mappings; two-stage designs.
  12. Subgroups. ISIS-2 (1988).
  13. Sequential trials. Group-sequential boundaries (Pocock 1977; O'Brien–Fleming 1979; Lan–DeMets 1983) as the cure for peeking (Board; Part 58 goes further).
  14. Surrogates. CAST (1989); Prentice (1989).
  15. External validity. Transporting a trial (Stuart et al. 2011; Dahabreh et al. 2019).
  16. Outro.

Built: the World's clinic; statkit.causal (I).

Build the film

python -m videos.stats.stats35.compute        # the part's numbers, into .cache/stats35
python tools/build.py stats35                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats35 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats35. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
OMP_NUM_THREADS=1 python -m videos.stats.stats35.compute   # once (under a minute)
python tools/build.py stats35 -q l                         # fast 480p preview
python tools/build.py stats35                              # 1080p30 -> renders/stats35.mp4
python tools/qa_scene.py stats35 Neyman
python tools/lecture_length.py stats35 --floor 50