Stage II · Bachelor's: Methods
Part 20 of 65The Analysis
What does a complete, honest statistical analysis look like, from the question to the report?
The question is how blood pressure depends on salt. Trials find 2 to 3 mm Hg of systolic pressure per gram of sodium; in NHANES 2017-2018 the crude slope is -0.14. The part introduces no new method and takes the question through every stage: the estimand, the survey's design and weights, a cleaning log that runs from 5,533 adults to 3,071, exploration, and a model written down before the results are seen. The weighted regression gives +0.07 mm Hg per gram with an interval from -0.50 to +0.63 on 15 degrees of freedom. Checks, four standard errors and a specification curve of 64 analyses do not move it; what matters is that one day's recall is a noisy measure of usual intake. The same code then runs on the World, where the effect is 1.5: the one-day recall averages 0.23 and covers the truth 0% of the time, and a randomized trial of 400 recovers it. The part ends with a one-page report, a reproducible pipeline, six problems across Stages I and II, and the BSc.
What you need. Stages I and II of this series; this part is their capstone.
- Hook
- a public health survey
- Mathematics
- a complete, reproducible analysis: question, design, cleaning, EDA, model, checks, inference, report, ethics
- Built
- the capstone report; the BSc problem set
What you will be able to do
Bachelor's
- State an estimand: the population, the outcome, the exposure, the contrast and what is held fixed.
- Read a coefficient with its design-based interval, and say what it does and does not show about cause.
Master's
- Fit a survey-weighted regression with linearized standard errors and the design's degrees of freedom.
- Compute the attenuation of a slope from the reliability of its exposure, and correct it by regression calibration.
PhD
- Explain why a regression on the true exposure can still miss a structural effect when diagnosis changes the exposure and the treatment, and name the design that identifies it.
Practice
- Keep a decision log of every cleaning step, with its reason and its count.
- Write a one-page report whose every number can be rebuilt from raw data, code and seeds.
- Run a specification curve and report the choices that move the answer.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 22 min · Master's 52 min · PhD 52 min · Practice 32 min.
- 0Salt and blood pressure: a questionBachelor's3 min
- 1From question to estimandBachelor's4 min
- 2The design and its weightsMaster's4 min
- 3CleaningPractice5 min
- 4ExplorationBachelor's4 min
- 5A first modelBachelor's4 min
- 6Checking itMaster's4 min
- 7UncertaintyMaster's3 min
- 8SensitivityMaster's5 min
- 9Causal or not?Bachelor's4 min
- 10The same pipeline on the WorldMaster's4 min
- 11CommunicatingPractice2 min
- 12Reproducibility and ethicsPractice3 min
- 13The BSc problem setBachelor's
- The BSc, 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.
Salt and blood pressure: a questionBachelor's3 min
This is the last part of the bachelor's degree, and it introduces no new method. Instead we take one question all the way through, the way a working statistician would. The question is about salt. American dietary guidelines say adults should eat less than two thousand three hundred milligrams of sodium a day. In our weighted analytic sample, untreated adults average about three and a half thousand. On any given day, three in four are over the guideline. The reason for the guideline is blood pressure: salt is thought to raise it, and high pressure causes strokes and heart attacks. So, how does blood pressure depend on salt? And how much can a national survey tell us about that?
Our data come from NHANES, the National Health and Nutrition Examination Survey. Its ancestor began in 1959, and since 1971 it has combined a home interview with a physical examination in a mobile centre that travels the country. We use the 2017 to 2018 cycle: nine thousand two hundred and fifty-four people interviewed, eight thousand seven hundred and four examined. The protocol called for three blood-pressure readings by a trained examiner, though some participants have fewer. And each was asked to recall everything they had eaten and drunk the day before, from which sodium is computed; most were asked again, by telephone, three to ten days later. The files are public: anyone can download them from the CDC, and anyone can check every number in this part.
Here is a first look: three thousand and seventy-one adults not taking blood-pressure medicine, seven hundred of them shown, with their systolic pressure against the sodium they ate the day before. The dashed line is the guideline. A straight line through the cloud slopes very slightly down: minus point one four millimetres of mercury per gram. More salt, a hair lower pressure. Yet randomized trials, in which people were assigned diets with different amounts of salt, find that each gram of sodium raises pressure by two to three millimetres. Is the survey wrong, or the trials, or the question? Finding out is the whole of this part.
We'll go through every stage an analysis really has, in order: from the question, through what exactly we're estimating, the survey's design, cleaning, exploration, a model and its checks, uncertainty and sensitivity, the causal question, a check on the World, the report, and reproducibility. Every decision will be made on screen and written into a log. We present an illustrative analysis plan before showing the result. This is a teaching sequence, not a claim of time-stamped preregistration. And then the identical code will run on the World, where we built the effect of salt ourselves and know the answer.
Numbers: mean 3,551 mg; 76% over 2,300; 9,254 interviewed, 8,704 examined; crude slope −0.14 (3,071 adults)
1From question to estimandBachelor's4 min
A question in words isn't yet something a computer can estimate. An estimand pins it down, in five parts. The population: American adults aged twenty and over, living at home rather than in prisons, nursing homes or the military, in 2017 and 2018. That's about two hundred and thirty-six million people, and it's what NHANES samples. The outcome: systolic blood pressure, the higher of the two numbers. The exposure: usual daily sodium intake, the long-run average, which is what could plausibly affect blood pressure. The contrast: how much higher mean pressure is per extra gram a day. And what is held fixed: age, sex, body mass index and total energy intake, so that people are compared with others like them.
The phrase depends on hides two different questions. The descriptive one: among adults alike in age, sex, size and energy intake, how much higher is mean blood pressure in those who eat a gram more sodium? That's a fact about the population as it is, and a good survey can estimate it. The causal one: if every adult ate a gram less, how much would mean pressure fall? That's what a guideline needs, and it's a question about a world that hasn't happened. A descriptive slope becomes causal only with adequate confounding control, a well-defined intervention and a suitable model. We'll estimate the first, and argue about the second in chapter nine.
Notice a gap already. The estimand is about usual intake, a long-run average. The data record one day, yesterday, reconstructed from memory in an interview. People eat very differently from day to day: for the two thousand six hundred and fifty-nine adults with two reliable recalls, the correlation between their first and second day is only point three two. So the exposure is measured with a great deal of noise, and Part 12 taught us what noise in x does to a slope: under a classical additive-error model it attenuates the slope; correlated recall errors and noisy covariates can behave differently. Write that down now; chapter eight measures how much.
Before fitting anything, we write down the plan. The sample: adults over twenty, not pregnant, and not taking blood-pressure medicine, because treatment changes pressure; this exclusion also changes the target population and can introduce selection bias. The outcome: the mean of the second and third readings. The exposure: sodium on the first recall day, for reliable recalls with plausible energy totals. The model: weighted least squares on sodium, age, sex, BMI and energy. The weights and standard errors follow the survey's design. Secondary analyses are listed in advance. And the last line matters most: the primary result is reported whatever it shows, and anything we change later is labelled as a change.
Why so formal? Because each line is a fork in Part 10's garden of paths. Medicine users in or out, energy in the model or not, weights or not, a spline for age, which readings, one recall day or two: six reasonable choices, sixty-four analyses. Choosing after seeing results can inflate false positives, even without deliberate cherry-picking. It does not guarantee that these sixty-four choices can produce any desired answer. So we choose first, and in chapter eight we'll show all sixty-four anyway. Prospective registration is required by many trial journals and regulators, with rules depending on the trial. A survey analysis can also register its plan. Our displayed teaching plan is not evidence of registration.
Numbers: 236 million adults; two recalls r = 0.32 (2,659); 2⁶ = 64 analyses
2The design and its weightsMaster's4 min
Chapter one's population is two hundred and thirty-six million people; NHANES examines about five thousand adults every two years. How it picks them is Part 18 in action. First it chooses counties, the primary sampling units, grouped into strata and drawn with probability proportional to size, because a mobile examination centre must park somewhere. Within each county it chooses neighbourhoods, within them households, and within households people, with some groups deliberately chosen at higher rates. None of this is a simple random sample, and the analysis has to know it.
The public files describe the design in a disguised form: fifteen strata, each with two pseudo-PSUs, thirty in all. They're called masked variance units: built so that standard errors come out right, while the actual counties stay secret, since in a small county knowing the location, age and sex could identify a person. For standard errors, what counts is the number of PSUs minus the number of strata: fifteen degrees of freedom. Five thousand people, but in thirty clusters, and people in the same cluster resemble each other. That will matter in chapter seven.
Here's what higher rates means. In cream, the share of each group in the sample of adults; in blue, its share of the population. Black adults are twenty-four percent of the sample but eleven percent of the population; Asian adults, fourteen percent against six; Hispanic adults are oversampled too; and so are older people, thirty-nine percent of the sample, twenty-nine of the population. It's deliberate: without oversampling there would be too few people in these groups to say anything about their health. White adults, sixty-two percent of the population, are a third of the sample.
Each person carries a weight: one over their probability of selection, as in Part 18's Horvitz–Thompson estimator, then adjusted for people who refused the interview or the exam, and post-stratified so that totals by age, sex and race match the Census. The median adult weight is about twenty-six and a half thousand: that person speaks for twenty-six thousand Americans. The range is large, from under five thousand for the most oversampled to over four hundred thousand. And the weights add up to the population, two hundred and thirty-six million adults.
Does weighting matter? For the mean systolic pressure of American adults, the unweighted average of the sample is a hundred and twenty-seven point one. Weighted, it is a hundred and twenty-three point nine. Mainly, the sample is older and includes more Black adults than the population, and both groups have higher blood pressure on average, so the raw mean overstates the nation's by three point three, more than six standard errors. For a national mean, weighting is not optional. For a regression slope the argument is subtler, and chapter five will make it.
And the design changes the uncertainty. The design-based standard error of that mean, computed by linearization across the strata and PSUs, is point four nine. Using the weighted population variance as an equal-size simple-random-sample reference gives point two six. The ratio of variances, the design effect, is three point six: clustering, as in Part 18, plus unequal weights, which Kish showed cost precision too. For this mean, four thousand nine hundred and forty-eight examined adults are worth about thirteen hundred and sixty-five chosen at random. For this mean the naive interval is too narrow; stratification can also reduce variance for other outcomes.
Numbers: 15 strata, 30 PSUs; Black 24% vs 11%, Asian 14% vs 6%, 60+ 39% vs 29%; weights 4,580–419,763, median 26,549; 127.1 vs 123.9; SE 0.49 vs 0.26 (weighted population SRS reference), deff 3.6
3CleaningPractice5 min
Cleaning starts with the codebook, because the numbers in a survey file aren't all measurements. The variable D R 1 D R S T Z rates each dietary recall: one means reliable, four thousand seven hundred and forty-two adults. Two means the interviewer judged it unreliable. Five means the recall wasn't done. Treat those codes as numbers and you'd be averaging nonsense. Age is top-coded: three hundred and eighty-two adults appear as eighty, meaning eighty or older, to protect the oldest from identification. And eighty-seven diastolic readings are zero, which happens when the examiner hears the pulse all the way down. It's a code for a measurement problem, not a blood pressure. We use only systolic pressure, but it's a warning to read the codebook first.
Next, the outcome. Most adults have three systolic readings; seventy have two, thirty-five one, and two hundred and sixty-six none at all. Our rule, written in the plan: average the second and later readings, and if there's only one, use it. Why skip the first? Here the first reading is only half a millimetre higher than the later ones on average, but in many surveys it runs higher: people are nervous, or still settling, the white-coat effect. Clinical guidelines average later readings for the same reason. Adults with no reading have no outcome, and leave the sample. Whether that's harmless depends on why they're missing, the question of Part 41.
Some recalls fall outside our chosen plausibility bounds; that does not prove they are impossible. Fifty-seven adults report under five hundred kilocalories for the whole day, sixty-seven over five thousand. One reports no sodium at all, and the largest value is nearly twenty-six thousand milligrams, about sixty-five grams of salt in a day. The temptation is to delete whatever looks odd. The rule we use, fixed in advance, drops days with energy outside five hundred to five thousand kilocalories as implausible, and keeps everything else, however surprising. Deleting values because they're inconvenient is how analyses quietly produce the answer someone wanted.
Here is the whole decision log as a funnel. Five thousand five hundred and thirty-three examined adults of eighteen and over. Two hundred and sixty-eight are under twenty, outside the estimand; fifty-five are pregnant; two hundred and sixty-two have no pressure reading; four hundred have no reliable first recall; a hundred and nineteen have implausible energy; thirty-nine have no BMI. And the largest single step comes last: one thousand three hundred and nineteen adults are taking blood-pressure medicine. That leaves three thousand and seventy-one in the primary analysis. Every step is in the code, with its reason, and anyone can rerun it.
That last step deserves a pause. Twenty-four percent of American adults take medicine for blood pressure. Their pressure may reflect treatment as well as diet, so our plan studies adults not currently taking medication. Exclusion does not itself eliminate confounding. But dropping them is not just cleaning: it changes the estimand. Our population is now American adults not taking blood-pressure medicine, a younger and healthier group. Operationally, the rule means no recorded current medication use. Skipped medication items are treated as no reported use, and adults with unknown pregnancy status are retained unless a positive test is recorded. Those assumptions and the exclusions belong in the report; they do not establish every person's true eligibility.
So the rules of cleaning. Read the codebook before the data. Never edit the raw file: do every step in code, starting from the original download, so the whole chain can be rerun. Log each exclusion, with its reason and its count. Fix the rules before fitting, and never drop points afterwards because they pull the line the wrong way. And when a step changes who is in the population, it changes the question, and the report must say so.
Numbers: codes 4,742 / 33 / 490; 382 at 80; 87 diastolic zeros; first reading +0.6; 57 under 500 kcal, 67 over 5,000; funnel 5,533 → 3,071
4ExplorationBachelor's4 min
Exploration means looking at the data before any model, to learn their shapes and find surprises. First the outcome, weighted to the population. The median systolic pressure is a hundred and eighteen; one adult in ten is below a hundred and three, one in ten above a hundred and forty-one. The distribution is skewed to the right, with a long tail of high pressures, even among people not being treated. Since 2017 American guidelines call a systolic pressure of a hundred and thirty or more high; twenty-four percent of these untreated adults are above it.
Then the exposure. On the recall day the median adult ate three point two six grams of sodium, and the mean is three point five five. The spread is wide: a tenth ate under one point six, a tenth over five point eight. Seventy-six percent were above the guideline that day. But remember chapter one's warning: much of this spread is day-to-day variation, not a difference between people. A histogram of usual intake would be narrower.
Now relationships. On the left, mean systolic pressure by decade of age, men in blue, women in red. It rises steadily with age; men are higher until their fifties, and women overtake them after seventy. On the right, mean sodium by age. Men report more sodium than women in this sample, and both eat less as they age. Put those together: older people have higher pressure and eat less salt. So in the raw data, age alone produces a negative relationship between salt and pressure. That's the crude slope of minus point one four from the hook: a confounder pushing in the opposite direction from the effect we're looking for.
Next, sodium against total energy on the same day. The correlation is point seven five. People who eat more food eat more salt, about one and a half grams per thousand kilocalories. And energy intake goes with body size, physical activity and sex, which have their own links to pressure. That's why nutritional epidemiologists, following Walter Willett, adjust for energy, so that the question becomes the saltiness of the diet rather than its size. The cost: once energy is held fixed, much less of the variation in sodium is left to learn from, and a lot of what's left is day-to-day noise.
And the relationship itself, without assuming a straight line: mean pressure in each tenth of the sodium distribution. The lowest tenth averaged one point two grams and a hundred and twenty millimetres. The highest averaged seven point three grams and a hundred and twenty-two. Across a six-fold range of sodium there is no visible trend, only noise. The bars now use design-based standard errors, with the other PSUs retained as zero domain contributions. They describe an unadjusted association; they do not bound a causal effect.
What did we learn? Pressure is skewed, rises with age, and differs between men and women. Sodium is skewed, noisy, falls with age, and tracks energy. The confounders push in different directions, so the raw picture can't answer the question; a model must compare like with like. And one discipline: we looked at everything, but we don't change the plan because of what we saw. If we did, the plan would no longer protect us.
Numbers: median 118 (103–141), 24% ≥ 130; sodium median 3.26, mean 3.55; r(sodium, energy) = 0.75; deciles 120 → 122
5A first modelBachelor's4 min
Here is the model from the plan: systolic pressure as a linear function of sodium, age, sex, body mass index and energy, plus an error. It's fitted by Part 12's least squares, with each adult's squared residual weighted by their survey weight. The coefficient on sodium, beta one, is chapter one's estimand: the difference in mean pressure per gram a day, among adults alike in the other four. We're assuming each relationship is a straight line and that sodium's slope is the same for everyone. Those are assumptions to check, which is chapter six.
Chapter two said weighting a mean isn't optional. For a regression slope the argument is subtler. Under a correct conditional-mean model and sampling independent of the residual given its predictors, unweighted regression can estimate the same coefficients. Whether weights improve precision depends on the variance and sampling models. But if the slope differs between groups, an unweighted fit targets a sample-distribution projection, influenced by group frequencies and covariate variation. The weighted fit estimates the slope you'd get by fitting the whole population: a well-defined descriptive estimand even when the model is wrong. William DuMouchel and Greg Duncan made this argument in 1983, and Gary Solon and colleagues revisited it in 2015. We chose weights in the plan, and chapter eight shows the answer both ways.
And here is the fit, on three thousand and seventy-one adults, with design-based standard errors and intervals from the t distribution with fifteen degrees of freedom. Age: plus point four zero millimetres a year. Women: five lower than men of the same age and size. BMI: plus point five two per unit. Energy: nothing to speak of. And sodium: plus point zero seven millimetres per gram, with a standard error of point two seven, and an interval from minus point five to plus point six.
Reading the coefficients as a reader would: ten years of age go with four millimetres more, precisely estimated. Five units of BMI, roughly the difference between a normal weight and obesity at a given height, go with two point six more. Women average five less than men like them. And a gram of sodium a day goes with seven hundredths of a millimetre, with a p-value of point eight one. The recall-day coefficient is compatible with zero and with a range of small positive or negative associations. It is not the usual-intake causal effect.
Let's put it on a line with the trials. In gold, the survey's slope and its ninety-five percent interval. In green, the range randomized trials have found: two to three millimetres per gram. The honest reading is not no effect. It's an interval that runs up to plus point six three, and does not overlap the displayed trial effects. Those trials and this recall-day regression target different quantities. This is not a formal contradiction: different exposures, populations and interventions can give different slopes. The next chapters examine measurement error, model assumptions and confounding.
We followed the plan, and the primary result goes in the report as it came out. A null result from three thousand people measured this carefully is information, not a failure. But before anyone believes it, three questions. Is the model wrong in some way that hides the effect? Are the intervals right? And does the answer depend on the choices we made, and on how badly one day's recall measures the usual diet?
Numbers: age +0.40, female −4.97, BMI +0.52, energy +0.07, sodium +0.07 [−0.50, +0.63], p = 0.81
6Checking itMaster's4 min
Part 12's checks, in order. First, residuals against fitted values. With three thousand points a raw scatter is a blur, so each dot is the average residual of a hundred and fifty adults with similar fitted values, with rough two-standard-error bars. There's no strong pattern: on average the model's straight lines fit. The highest bins dip below zero, which could mean the relationship with age isn't straight. We'll look directly.
Next, a normal quantile plot of the residuals. They bend upward on the right: a long right tail, skewness about one, the same tail we saw in chapter four. Does it matter? Normal individual residuals are not required for a design-based slope interval. Its approximation depends on the sampled PSUs and regularity, not merely the number of people; thirty masked PSUs are a modest basis. For predicting one person's pressure, it would: a normal interval would miss the high values. Modelling log pressure would tame the tail, but then the estimand becomes a percent change, and the plan asked for millimetres.
The model forced age to be a straight line. Replace it with a restricted cubic spline, a smooth curve built from cubic pieces joined at four knots and kept straight beyond the outer ones. The spline is flat in the twenties and thirties and climbs steeply after that, and the design-based Wald F test on the two extra terms, using fifteen denominator degrees of freedom, gives a p-value of about point zero two two. But what happens to sodium's slope? It moves from point zero seven to point zero four. This particular age adjustment barely changes the sodium coefficient; it does not establish that all model misspecification is harmless. That's the purpose of a check: not to make the model perfect, but to see whether its flaws change the answer.
The model also assumed sodium's slope is the same at every age. Let it vary, with an interaction between sodium and age. The interaction comes out negative, minus point zero four per year, with a p-value of two percent. Taken at face value, salt goes with higher pressure at thirty and lower pressure at seventy, which is the opposite of what trials find: older people are more sensitive to salt, not less. This wasn't in the plan. It's one of many things we could have tried, and a p-value of two percent after a search is weak evidence. The report mentions it, labelled exploratory, with chapter nine's likely explanation: older people with high pressure have often been told to cut their salt.
Finally, influence: Part 12's Cook's distance measures how much the fit would move if each adult were left out. Big survey weights can make a few people very influential. As a check, not a new analysis, drop the thirty most influential adults, one percent of the sample. Sodium's slope goes from plus point zero seven to minus point zero two, well within one standard error. Removing this influential subset changes the estimate little. That check does not rule out every influential group or model problem.
So: the residuals show no systematic pattern; the tail does not itself require normality for design-based inference; the spline suggests curvature but barely moves sodium; an interaction turned up that we didn't plan, and it's reported with that label; and no few people drive the result. These checks leave the main recall-day estimate similar. They cannot prove the model correct or explain every difference from trials.
Numbers: skewness 1.05; spline Wald F₂,₁₅ = 4.98, p = 0.022, sodium +0.04; interaction −0.041 (SE 0.016); top 1% dropped: −0.02
7UncertaintyMaster's3 min
The slope for sodium was plus point zero seven. How uncertain is it? There are four answers on offer. The model-based standard error treats the weights as if they were precisions and the errors as independent with variance inversely proportional to those weights: point two three. Part 12's sandwich, robust to unequal variances but still treating people as independent: point three one. The design-based standard error, the same sandwich but with scores summed within each PSU, so that people in the same cluster count together: point two seven. And a bootstrap that resamples whole PSUs within strata, Rao and Wu's method, a thousand times: point two seven again.
Here are the thousand bootstrap slopes. In each replicate, every stratum keeps one of its two PSUs, drawn at random with replacement, and the weights are rescaled to make up for the one left out. That mimics drawing the survey again. In gold, a normal curve with the linearized standard error. The two methods agree closely, which is reassuring: one rests on a Taylor expansion, the other on resampling, and with only fifteen strata neither is guaranteed.
As intervals: model-based, sandwich, and design-based with the normal multiplier. And the design-based one with t, not z. Fifteen degrees of freedom means a multiplier of two point one three instead of one point nine six, which is Part 11's small-sample lesson reappearing: the standard error itself is estimated from only thirty PSUs. The plan chose that last interval, minus point five oh to plus point six three. It reflects our chosen design approximation, though the independent-unit sandwich interval is wider here. Each is compatible with zero; that is not proof of a zero effect.
Compare a plain mean: average pressure in the same population, a hundred and twenty point four. As a simple random sample, its standard error would be point three three. By design, point five four, and the bootstrap agrees. A design effect of two point seven for the mean, but only about one point four for the slope. That's typical: whole clusters differ in their average pressure, perhaps through geography or income, but within-cluster differences, which drive a slope, are less affected. Clustering can affect means and slopes differently; the direction depends on the outcome and covariate patterns.
One caution about all of these intervals. They measure one thing: the luck of which people the survey happened to draw. They say nothing about two other problems, which may be far larger. One is the noise in a single day's recall, which biases the slope rather than just spreading it. The other is who eats salt, and why. As Part 11 put it, an interval is only as honest as its assumptions, and the next two chapters examine those.
Numbers: SEs 0.229 / 0.311 / 0.266 / 0.272; t₁₅ = 2.13; mean 120.4, SE 0.54 vs 0.33
8SensitivityMaster's5 min
The plan promised all sixty-four analyses. Here they are: a specification curve, as Uri Simonsohn and colleagues called it. Each dot is one analysis's sodium slope, sorted from smallest to largest, with design t intervals using the degrees of freedom of each fit. Below, which choices it made: medicine users in or out, energy in the model or not, weights or not, a spline for age, which readings, one recall day or the mean of two. The pre-specified analysis is in gold, near the middle. The sixty-four slopes run from minus point one eight to plus point six four, and not one is distinguishable from zero. The estimates include both signs. None of these sixty-four intervals excludes zero.
Which choices move the answer most? Average the slope over the analyses with and without each choice. Two stand out. Including people on blood-pressure medicine pulls the slope down, from about plus point two zero to minus point zero seven. Using the mean of two recall days instead of one pushes it up, by about a tenth. Weights, the age spline, energy and the readings rule barely matter. The choices that matter are about who is in the sample and how the exposure is measured. Both point to the next two problems.
Two thousand six hundred and fifty-nine adults in our analytic sample supplied two reliable recalls, usually several days apart. This unweighted scatter compares their reported sodium. The correlation is point three two. The standard deviation of a single day is one point seven six grams, and the standard deviation of the day difference divided by root two is one point four two. Under independent replicate errors, that difference measures within-person variation. Calling the correlation a reliability requires equal replicate error variances and no shared reporting error. Two days alone cannot verify those assumptions.
In the classical model, a recalled day W is usual intake X plus independent mean-zero noise U. With accurately measured covariates Z and the appropriate linear mean model, the sodium coefficient is attenuated by the residual reliability lambda. Predicting the second day from the first, age, sex and BMI with the two-day dietary weights gives a calibration coefficient near point two four. Adding recall-day energy reduces it to point zero six. That is weak calibration, not proof that precisely ninety-four percent of the remaining sodium is noise: energy is noisy too, and its reporting error can correlate with sodium's. The attenuation interpretation needs assumptions these data cannot establish.
Regression calibration replaces the first recall by its linear prediction from a second recall and the model covariates. We use the CDC's two-day dietary weights and jointly linearize both regressions, so the interval accounts for estimating the calibration equation. Gold is the primary recall-day estimate, grey the estimate without energy. Blue is calibration without energy: plus point three seven, with an approximate interval from minus one point nine to plus two point seven. With energy, the estimate is plus point six five and the delta-method margin is about eight point seven, wider than this axis. Such weak calibration makes even that approximation fragile. These exploratory corrections are imprecise and assumption-dependent. They do not establish agreement or disagreement with a particular trial; they show how much uncertainty a single recalled day leaves.
The sixty-four specified alternatives all remain compatible with zero. The two-recall correlation and the small conditional calibration slope raise serious measurement concerns. Correcting under a classical replicate model produces broad, approximate intervals; shared reporting error, noisy energy and weak calibration remain limitations. Better measurement could include more recall days or repeated twenty-four-hour urine collections, with attention to collection completeness. INTERSALT collected urine in ten thousand and seventy-nine adults across fifty-two centres. It found an ecological association between sodium and the rise of pressure with age; that cross-centre comparison alone does not establish an individual causal effect.
Numbers: 64 slopes −0.18 to +0.64; medicine +0.20 → −0.07; two days +0.01 → +0.12; λ 0.24 and 0.06; calibrated without energy +0.37 ± 2.32; with energy +0.65 ± 8.72
9Causal or not?Bachelor's4 min
To see what the survey can and can't say about cause, draw the causal story, as Part 35 will do formally. The arrow we care about runs from usual sodium to blood pressure. Age and sex affect both; energy intake drives sodium; body size affects both. These are the confounders the model adjusted for. We never see usual sodium, only one day's recall of it, the dashed arrow of chapter eight. Time order matters: earlier high pressure can lead to diagnosis, which can change current sodium and treatment; both can affect current pressure. We separate earlier and current pressure so the diagram is acyclic. The primary analysis removed the medicated, but not everyone who changed their diet. And things we didn't measure, such as physical activity, alcohol and income, may affect both diet and pressure.
Is the backwards loop real here? A third of adults say a doctor has told them their pressure is high. They do eat a little less sodium, three point four zero grams against three point five five. But per thousand kilocalories, their diet is no less salty: one point six six against one point six four. They're older, by fourteen years, and older people eat less of everything. So in NHANES, at least, there's little sign that diagnosis changed the saltiness of diets. This aggregate cross-sectional comparison cannot rule out diet changes after diagnosis; age, treatment, reporting and selection may conceal them.
Now the trials. In DASH-Sodium, published in 2001, four hundred and twelve adults ate diets prepared for them, at three levels of sodium, each for a month, in random order. On a typical American diet, going from high sodium to low lowered systolic pressure by six point seven millimetres. In 2013 Feng He, Jiafu Li and Graham MacGregor pooled thirty-four randomized trials of at least four weeks: four point four grams a day less salt, one point seven five of sodium, lowered pressure by four point two. That's two and a half to three millimetres per gram of sodium. And because the diets were assigned at random, baseline confounders are balanced in expectation, though finite-sample imbalance, adherence and measurement remain considerations. DASH controlled the supplied food; the meta-analysis also included free-living trials, many using urinary sodium to assess intake.
The two kinds of evidence answer different questions. A trial tells us the causal effect of changing the diet, for the people in it, over a month or so. The survey describes the whole population as it lives. Trials have limits: they're short, their volunteers aren't typical, and they measure blood pressure rather than strokes. And this survey has the limits we've found: a single day's diet, possible confounding, and no time order, since diet and pressure were measured together. Each has to be read with the other's strengths in mind.
The report can describe the adjusted recall-day association in this analytic sample, with survey weights and explicit exclusions. Extending it to all eligible adults needs assumptions about nonresponse and missing measurements. The repeat recalls reveal measurement concerns; quantitative attenuation or correction needs an adequate error model, especially with noisy energy. A non-significant descriptive slope does not show that changing sodium has no causal effect. It also does not formally test a guideline supported by trials in different populations and interventions. Observational causal designs and their assumptions return in Parts thirty-five to thirty-seven.
Numbers: told 33%; sodium 3.40 vs 3.55, per 1,000 kcal 1.66 vs 1.64; age 58 vs 44; DASH-Sodium 6.7; meta-analysis 4.2 per 4.4 g salt
10The same pipeline on the WorldMaster's4 min
The World now has a health block, built for this part, with laws we wrote down. Each adult's systolic pressure follows age, body size and sex, plus one point five millimetres for every gram of sodium they currently eat, minus twelve if they take medicine, plus personal variation. One point five is the truth, for everyone. Sodium is proportional to energy intake times a personal taste for salt. Those whose pressure reaches a hundred and forty are usually told so, and then cut their salt by a tenth, and most take medicine. And each adult has two dietary recalls, each that day's intake with noise, tuned so that the two days correlate about as they do in NHANES. The World's averages match NHANES too: three point four seven grams of sodium, a hundred and twenty-four millimetres of pressure.
Use an illustrative NHANES-shaped design: ten regions, two PPS town draws per region, and two hundred and fifty adults in each draw, with older adults oversampled by age-stratified random sampling. The draw and within-age probabilities are exact. This is not NHANES's actual selection algorithm. Run the same analysis pipeline. In this survey the recall-day estimate is point three five. Joint regression calibration gives one point two three, with a much wider interval. Using true current intake gives one point zero zero. Even perfect sodium measurement does not automatically recover the structural effect, one point five.
Repeat for two hundred survey draws from this fixed World. The one-day analysis averages point two three, and none of its intervals contains one point five. Calibration averages point seven four and its joint design intervals cover in sixty-nine point five percent of draws. True intake gives an average of point nine six and coverage of fifty-three point five percent. These are empirical operating characteristics for this particular simulation and pipeline, not universal properties of survey analysis.
The simulation separates several problems, but these differences are not an additive causal decomposition. Even the true-intake regression is a descriptive projection, not the structural effect: diagnosis changes diet, medication exclusion selects adults, and the analysis's linear age and sex terms differ from the generating laws. Replicate calibration remains imperfect because its linear predictor and error assumptions are approximations. The simulated energy and sodium recalls share within-day reporting variation, so conditioning on noisy energy complicates classical attenuation. Better measurement can help, but cannot by itself establish causal identification. Confounding may be addressed only with further design or defensible assumptions, not by sodium replicates alone.
Now do what the trials did. Choose four hundred adults aged thirty to seventy, not on medicine, and assign half at random to a low-sodium diet, one point one five grams a day, and half to a high one, three point four five, for a month. Their pressures overlap enormously, but the means differ by four point four millimetres, which is one point nine three per gram, with an interval that contains the truth. Repeat the trial two thousand times: the intervals cover one point five ninety-six percent of the time. Four hundred randomized people succeed where five thousand surveyed people fail, because randomization breaks every arrow into sodium except the one we control.
Three rows for the Board, each a ninety-five percent interval for the World's sodium effect. The survey analysis as planned: zero percent, broken for this structural target. With joint regression calibration: sixty-nine point five percent, still below its nominal promise; causal and measurement assumptions remain unmet. The randomized trial: ninety-six percent, kept.
Numbers: one survey 0.35 / 1.23 / 1.00; 200 surveys 0.23 / 0.74 / 0.96, coverage 0 / 69.5 / 53.5%; trial 1.93 ± 1.20, 95.8%
11CommunicatingPractice2 min
The analysis is done; now it has to be said. Here are three ways to say it badly. Salt has no effect on blood pressure: a causal claim, from an absence of evidence. A non-significant trend toward higher pressure: a phrase that dresses noise up as a finding. After calibration, the effect rose to point three seven: an unplanned, hopelessly imprecise number promoted to a headline. And one way to say it well: who, when and how many; the estimate in its units, with its interval; and the one limitation that changes how to read it, stated plainly, with what it means for the trials.
The full report fits on one page. It starts with the question in the estimand's own words. Then the data, including who was excluded and why. Then the finding, in millimetres per gram, with its interval and the sixty-four alternatives. Then the limitation that changes everything: the reliability of one day's recall, and the corrected interval. Then what the result does not show. And a single figure: the survey's estimate beside the trials' range, which says more than any table.
The figures need the same honesty as the sentences, Part 1's rules of graphic integrity. Chapter four's decile means, plotted on an axis from a hundred and seventeen to a hundred and twenty-five, become a jagged mountain range. A reader sees structure: a peak in the fourth decile, a rise at the top. On an axis from zero, the same differences look much smaller. Neither axis proves the differences are real or mere noise; for blood pressure a range of clinical interest is reasonable. But the axis should never manufacture the finding, and every plot should show its uncertainty.
The page is short because the appendix is long. It holds the decision log, the analysis plan and any deviation from it, all sixty-four analyses and the exploratory interaction, clearly labelled, the model checks and the replay on the World, and the code, which is the subject of the next chapter.
Numbers: the one-page report; decile axis 117–125 vs 0–140
12Reproducibility and ethicsPractice3 min
Here is the chain from the CDC's files to every number in this part. Six public files, downloaded unchanged. A short extraction script that keeps the columns we use and renames them, nothing more. The original twenty-nine-column CSV plus a SEQN-aligned supplement containing the CDC two-day dietary weights. The pipeline, where every decision of chapters three to eight lives, as code. A compute script that produces every number, with fixed random seeds for the bootstrap and the World. Its results, cached. And the scenes and the report, which only read the cache. Numerical results come from the computation, while some labels and narrative summaries are rounded by hand. Force recomputation after source changes; one command reruns it all.
Reproducibility needs four things recorded. Where the data came from. A fingerprint of the exact file: a SHA-256 hash, which changes if a single digit changes, so a reader can confirm they have the same data. The random seeds, so that even the bootstrap and the simulations come out identically. And the versions of the code and the packages. Without these, a result can't be checked, only believed.
Public data must protect the people in it. NHANES does it in layers. No locations: only thirty masked PSUs. Age is top-coded at eighty, because a ninety-seven-year-old in a small county could be identified. The ratio of income to the poverty line is top-coded at five, for the same reason at the other end. Finer data exist, but only inside secure research centres, by application. And every participant gave informed consent to a protocol approved by an ethics review board. Part 63 will show how statistics itself can guarantee privacy.
And the ethics of the analysis itself. NHANES records race and ethnicity, and differences between groups are real, but they reflect social and environmental conditions; reporting them as biology causes harm. A null result like ours deserves to be published as much as a positive one, or the literature fills with flukes. Salt has an industry, and nutritional advice has its champions; who paid for a study should always be stated. A headline that says salt is harmless could change what millions of people eat. The analyst's duty is to say what the data show, as precisely as they show it, and no more.
Here is the whole capstone as a checklist of thirteen items, one per chapter: from the estimand to the design, cleaning, exploration, the plan and its checks, uncertainty, sensitivity, measurement, causation, the World, the page, and reproducibility. Every analysis you do from now on can be held against it.
Numbers: SHA-256 ae9be143…; 382 ages and 821 income ratios top-coded
13The BSc problem setBachelor's
The bachelor's problem set: six problems that draw on the whole of the first two stages, each solved on screen.
Bayes's rule, a survey's margin of error, attenuation, power, the bootstrap and multiplicity: every one of them turned up in this one analysis. Full solutions, with more detail, are in the README.
Numbers: six problems, below
The BSc, and the road aheadAll tracks3 min
Part twenty in fourteen lines. We turned a question about salt into an estimand for a stated population. NHANES's strata, PSUs and weights changed the mean pressure by three points and tripled its variance. Cleaning took five and a half thousand adults to three thousand and seventy-one, every step logged, and exploration showed age confounding the relationship the other way. The illustrative plan's model found plus point zero seven millimetres per gram, with an interval from minus point five to plus point six; the checks found curvature but no harm; the four standard errors differed, while all four intervals included zero; and sixty-four alternative analyses all stayed near zero. But the repeat recalls exposed measurement concerns, so the recall-day association is not directly comparable to randomized diet effects. On repeated World surveys, the recall-day estimate averaged point two three, calibration point seven four and true intake point nine six; a randomized trial's intervals covered the structural effect at roughly their promised rate. And it all fits on one page, rebuilt by one command.
Where it comes back. The master's begins with Part 21, on how estimates are actually computed. Part 23 takes the linear model apart properly, and Part 25 builds the multilevel models that surveys use for small areas. Part 28 compares ways of choosing a model. Parts 35 to 37 are the causal inference this survey couldn't do. Part 41 gives measurement error and missing data their full theory. Part 56 handles inference after the data have chosen the analysis, and Part 63 makes privacy a theorem.
The sources for this part: NHANES's own documentation and analytic guidelines, Thomas Lumley's book on complex surveys, Carroll and colleagues on measurement error, and Frank Harrell's Regression Modeling Strategies; with the trials, INTERSALT, and the papers on weights, the survey bootstrap and specification curves.
That completes the first two stages: the foundations, and the methods. Probability and inference, regression and experimental design, counts and Bayes, the bootstrap, time series, surveys and prediction, and one real analysis, done honestly from beginning to end. That completes this course's bachelor-level stage; the curriculum is not an accredited degree.
Twenty parts of sixty-five, and the first milestone. The bachelor's is complete. The master's begins with a question we've been avoiding: every estimate in this course was the solution of an optimization problem, from least squares to the lasso. How are those problems solved, and what does their geometry tell us about the estimators? Part 21: optimization for statistics.
Where it goes next. The master's stage begins with how estimators are computed (Part 21) and the linear model in depth (Part 23); causal questions from observational data are Parts 35 to 37, measurement error and missing data Part 41, and inference after selection Part 56.
Key results
The part's results in one place, for revision.
Try it
Lab 20 · One day's recall against usual intake
Survey 300,000 of the World's adults, regress measured systolic pressure on sodium with age, BMI and sex held fixed, and compare four exposures: one 24-hour recall, the mean of two, the recall calibrated on its replicate, and the intake itself. The World's effect is 1.5 mm Hg per gram.
python -m videos.stats.labs 20
needs numpy, scipy, matplotlib · download lab20.py ·
source on GitHubthe World's effect of sodium 1.50 mm Hg per g
slope on the intake itself 1.22
slope on one day's recall 0.38 (lambda x intake slope = 0.31 x 1.22 = 0.37)
slope on the mean of two recalls 0.59 (2 lambda/(1 + lambda) = 0.47, predicts 0.57)
regression calibration 1.25
two recalls: correlation 0.36
Day-to-day variation in what people eat shrinks the slope by the reliability lambda; a replicate recall measures lambda and undoes it. What is left, the gap to 1.5, is not noise: the diagnosed cut their salt and take medicine, and no adjustment of the exposure repairs that.
The code (74 lines; it asserts its own result)
"""Lab 20: the capstone's regression on the World, where the effect of sodium on blood pressure is known."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.kit import capstone
from explainer.stats.world import World
TITLE = "One day's recall against usual intake"
GOAL = ("Survey 300,000 of the World's adults, regress measured systolic pressure on sodium with age, BMI and sex held "
"fixed, and compare four exposures: one 24-hour recall, the mean of two, the recall calibrated on its "
"replicate, and the intake itself. The World's effect is 1.5 mm Hg per gram.")
TASKS = [
"Drop the adults on blood-pressure medicine (h['bp_meds']). Which slopes move, and why is that a different estimand?",
"Add recalled energy (h['kcal_day1']) to the covariates. What happens to lambda and to the calibrated slope's stability?",
"Cut the survey to 5,000 adults and rerun with ten seeds. How wide is the spread of the calibrated slope?",
]
def run(seed=0):
rng = np.random.default_rng(seed)
w = World()
h = w.health
i = rng.choice(np.flatnonzero(w.adult), 300_000, replace=False) # a simple random sample of adults
age = w.age[i].astype(float)
female = (~w.male[i]).astype(float)
Z = np.column_stack([age, (age - 18) ** 2, h["bmi"][i], female * (age < 60)])
y = h["sbp_read"][i].mean(1) # the mean of three readings
day1, day2, intake = h["na_day1"][i] / 1000, h["na_day2"][i] / 1000, h["na_current"][i] / 1000 # grams
def slope(x):
D = np.column_stack([x, np.ones(len(x)), Z])
return float(np.linalg.lstsq(D, y, rcond=None)[0][0])
rc = capstone.regression_calibration(day1, day2, Z)
lam = rc["lam"]
lam2 = 2 * lam / (1 + lam) # the reliability of a two-day mean
b1, b2, bcal, btrue = slope(day1), slope((day1 + day2) / 2), slope(rc["xhat"]), slope(intake)
truth = w.SODIUM_EFFECT
lab = labs.Lab()
lab.row("the World's effect of sodium", f"{truth:.2f} mm Hg per g")
lab.row("slope on the intake itself", f"{btrue:.2f}")
lab.row("slope on one day's recall", f"{b1:.2f} (lambda x intake slope = {lam:.2f} x {btrue:.2f} = {lam * btrue:.2f})")
lab.row("slope on the mean of two recalls", f"{b2:.2f} (2 lambda/(1 + lambda) = {lam2:.2f}, predicts {lam2 * btrue:.2f})")
lab.row("regression calibration", f"{bcal:.2f}")
lab.row("two recalls: correlation", f"{capstone.reliability(day1, day2):.2f}")
assert b1 < 0.45 * btrue, "one day's recall loses more than half of the slope"
assert abs(b1 / (lam * btrue) - 1) < 0.15, "the loss is the attenuation factor lambda"
assert abs(b2 / (lam2 * btrue) - 1) < 0.15 and b2 > b1, "a second day buys back 2 lambda/(1 + lambda)"
assert abs(bcal - btrue) < 0.25, "calibration recovers the slope on the intake itself"
assert 1.0 < btrue < truth - 0.05, "which is still below the structural effect: diagnosis changes diet and treatment"
lab.note = ("Day-to-day variation in what people eat shrinks the slope by the reliability lambda; a replicate recall "
"measures lambda and undoes it. What is left, the gap to 1.5, is not noise: the diagnosed cut their salt "
"and take medicine, and no adjustment of the exposure repairs that.")
fig, ax = labs.figure(2, size=(11, 4.2))
names = ["one day's\nrecall", "mean of\ntwo days", "calibrated", "the intake\nitself"]
vals = [b1, b2, bcal, btrue]
ax[0].bar(names, vals, color=[labs.RED, labs.ORANGE, labs.BLUE, labs.GREEN], width=0.6)
for k, v in enumerate(vals):
ax[0].text(k, v + 0.03, f"{v:.2f}", ha="center", color=labs.INK)
ax[0].axhline(truth, color=labs.GOLD, ls="--", label="the World's effect, 1.5")
ax[0].set(title="Sodium's slope by how intake is measured", ylabel="mm Hg per g of sodium", ylim=(0, 1.8))
ax[0].legend(loc="upper left")
days = np.arange(1, 15)
ax[1].plot(days, btrue * days * lam / (1 + (days - 1) * lam), "o-", color=labs.BLUE, ms=4,
label="theory: k λ/(1 + (k − 1)λ) × intake slope")
ax[1].scatter([1, 2], [b1, b2], color=labs.RED, zorder=5, s=50, label="measured: one and two recalls")
ax[1].axhline(btrue, color=labs.GREEN, ls="--", label="slope on the intake itself")
ax[1].set(title="What more recall days would buy", xlabel="recall days averaged, k", ylabel="expected slope",
ylim=(0, 1.8))
ax[1].legend(loc="lower right")
lab.fig = fig
return lab
Now change it
- Drop the adults on blood-pressure medicine (h['bp_meds']). Which slopes move, and why is that a different estimand?
- Add recalled energy (h['kcal_day1']) to the covariates. What happens to lambda and to the calibrated slope's stability?
- Cut the survey to 5,000 adults and rerun with ten seeds. How wide is the spread of the calibrated slope?
Problems, with solutions
Try each problem before opening its solution.
1. Two positive tests (Parts 2, 15). A condition affects 1% of adults. Two tests, conditionally independent given disease status, each detect it 90% of the time and give false alarms 5% of the time. Both are positive: how likely is the condition?
Solution
P(both + | sick) = 0.81 and P(both + | well) = 0.0025. So P(sick | both +) = 0.0081/(0.0081 + 0.002475) ≈ 0.766. One positive test alone gives 0.009/(0.009 + 0.0495) ≈ 0.154.
2. A survey's margin of error (Parts 8, 18). A survey of \(n = 4{,}948\) measures systolic pressure with SD 17 mm Hg; its design effect is 3.6. The 95% margin of error, with and without the design?
Solution
As an SRS, 1.96 × 17/√4,948 = 0.474. With a design effect of 3.6, multiply by √3.6: 0.90. The effective sample size is 4,948/3.6 ≈ 1,374.
3. Attenuation (Part 12). Usual intake \(X\) has variance 1; one day's recall \(W = X + U\) adds independent noise of variance 2. A true slope of 2.5 mm Hg per g: what slope does a regression on \(W\) find?
Solution
λ = Var X/(Var X + Var U) = 1/3, so the slope tends to 2.5/3 ≈ 0.83. The mean of k recall days has noise variance 2/k, so λ_k = 1/(1 + 2/k). For k = 7, λ = 7/9 ≈ 0.78.
4. Sizing a trial (Parts 10, 13). Plan a parallel trial: low vs high sodium, a difference of 2.3 g at 2.5 mm Hg per g, SD 15 within arms. How many per arm for 80% power at the 5% level?
Solution
Δ = 2.3 × 2.5 = 5.75 mm Hg. Then n = 2(1.96 + 0.8416)² × 15²/5.75² ≈ 106.8, so 107 per arm.
5. Counting bootstrap replicates (Parts 16, 18). NHANES's public design: 15 strata with 2 PSUs each. How many different Rao–Wu bootstrap replicates are there?
Solution
Each of the 15 strata draws n_h − 1 = 1 of its 2 PSUs, so there are 2¹⁵ = 32,768 equally likely replicates. The PSU-level information has 30 − 15 = 15 degrees of freedom however many replicates are drawn.
6. Sixty-four forks (Parts 10, 19). Sixty-four analyses, each with a 5% false-positive rate, if independent: the chance at least one is "significant"? And with a Bonferroni correction?
Solution
- Independent analyses. 1 − 0.95⁶⁴ ≈ 0.962.
- Bonferroni. Testing each at 0.05/64 ≈ 0.00078 keeps the family-wise rate at or below 0.05, by the union bound, whatever the dependence.
- Our 64. They are highly correlated, since they share the data and most choices, so the effective number of opportunities can be smaller. Correlation does not explain or guarantee the absence of a significant result. None was significant here.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| how estimators are computed | 21 |
| the linear model in depth | 23 |
| multilevel models, MRP for surveys | 25 |
| model choice | 28 |
| causal inference from observational data | 35, 36, 37 |
| measurement error and missing data | 41 |
| inference after selection | 56 |
| privacy for public data | 63 |
| the Coverage Board | every part; 65 |
Glossary
- Estimand: the precise target: population, variable, summary, contrast, and what is held fixed.
- Descriptive vs causal estimand: how groups differ as they are, vs how outcomes would change under an intervention.
- Usual intake: a person's long-run average consumption, the exposure that matters; a 24-hour recall measures one day.
- Analysis plan (pre-specification): the sample, model and outputs fixed before the results are seen.
- Masked variance units: NHANES's public pseudo-strata and pseudo-PSUs, built for correct SEs without revealing locations.
- Survey weight: inverse selection probability, adjusted for nonresponse and post-stratified to Census totals.
- Design effect; effective sample size: the variance ratio against an SRS, and n divided by it.
- Taylor linearization: design-based variance of a nonlinear estimator from the PSU totals of its linearized scores.
- Rao–Wu bootstrap: resampling n_h − 1 PSUs per stratum, with rescaled weights.
- Decision log: every cleaning step, with its reason and count.
- Top-coding: replacing extreme values (age 80+, income ratio 5+) by a cap, for privacy.
- Energy adjustment: including total energy so that the exposure is diet composition rather than diet size.
- Restricted cubic spline: piecewise cubic, linear beyond the outer knots; a check for nonlinearity.
- Specification curve (multiverse): the estimate under every reasonable combination of analytic choices.
- Reliability (attenuation factor) λ: Var(X | Z)/Var(W | Z); the factor by which classical error shrinks a slope.
- Regression calibration: replacing W by E[X | W, Z], estimated from a replicate.
- Reverse causation: the outcome affecting the exposure (diagnosis changes diet).
- Internal and external validity: whether a study answers its own question correctly, and whether that answer generalizes.
- Reproducible pipeline: raw data, code, seeds and versions from which every number can be rebuilt.
Sources
- Data. CDC/NCHS, National Health and Nutrition Examination Survey 2017–2018: data files DEMO_J, BPX_J, BMX_J, DR1TOT_J, DR2TOT_J, BPQ_J; NHANES Analytic Guidelines and the sample design documentation.
- Salt and blood pressure.
- F. Sacks et al., "Effects on blood pressure of reduced dietary sodium and the DASH diet", NEJM 344 (2001).
- F. He, J. Li & G. MacGregor, BMJ 346 (2013), f1325.
- INTERSALT Cooperative Research Group, BMJ 297 (1988).
- W. Willett, Nutritional Epidemiology (3rd ed., 2013).
- Methods.
- T. Lumley, Complex Surveys (2010).
- J. Rao & C. Wu, JASA 83 (1988).
- W. DuMouchel & G. Duncan, JASA 78 (1983); G. Solon, S. Haider & J. Wooldridge, J. Human Resources 50 (2015).
- R. Carroll, D. Ruppert, L. Stefanski & C. Crainiceanu, Measurement Error in Nonlinear Models (2nd ed., 2006).
- F. Harrell, Regression Modeling Strategies (2nd ed., 2015).
- U. Simonsohn, J. Simmons & L. Nelson, Nature Human Behaviour 4 (2020).
- A. Gelman & E. Loken, "The garden of forking paths" (2013).
About this partfrom its README
Part 20 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus). It is the capstone of Stage II and of the bachelor's degree. It introduces no new method. Instead it takes one question through every stage of a real analysis, on real public data, and then runs the identical code on the World, where the answer is known.
The question. How does blood pressure depend on salt?
- Untreated adults in this weighted analytic sample report about 3,550 mg of sodium on the recall day; the guideline is under 2,300.
- Randomized trials find 2–3 mm Hg of systolic pressure per gram of sodium.
- In NHANES 2017–2018 the crude slope is −0.14 mm Hg per gram.
The part distinguishes recall-day associations from causal trial effects:
- The estimand. Population, outcome, exposure (usual intake, not yesterday's), contrast and what is held fixed. Descriptive vs causal readings. An illustrative plan presented before the results; this is not evidence of prospective registration.
- The design and its weights. NHANES's four stages; 15 strata × 2 masked PSUs, so 15 degrees of freedom; the
oversampling of Black, Asian, Hispanic and older adults.
- Weights run from 4,580 to 419,763 and sum to 236 million.
- Mean systolic pressure is 123.9 weighted against 127.1 raw.
- The design effect for the mean is 3.6, so n_eff ≈ 1,365.
- Cleaning. A codebook first: recall reliability codes, age top-coded at 80, a diastolic of zero. Readings 2–3 are averaged. Energy outside 500–5,000 kcal is implausible. The decision log runs 5,533 → 3,071, and excluding the 1,319 adults on BP medicine changes the estimand.
- Exploration.
- Pressure: median 118, with 24% at 130 or above.
- Sodium: median 3.26 g, with 76% over the guideline.
- Pressure rises with age while sodium falls with age: a confounder pointing the other way.
- Sodium and energy correlate at r = 0.75; decile means are flat.
- A first model. Weighted least squares on sodium, age, sex, BMI and energy. Sodium: +0.07 mm Hg per g, 95% CI −0.50 to +0.63 (t₁₅), p = 0.81. The displayed trial effects lie outside this recall-day interval, but target different exposures and estimands. Why weight a regression (DuMouchel & Duncan; Solon, Haider & Wooldridge).
- Checking it.
- Binned residuals and a Q-Q plot (skewness 1.05).
- A restricted cubic spline for age: a design Wald F₂,₁₅ test suggests curvature (p = 0.022), but sodium moves only from +0.07 to +0.04.
- An unplanned sodium × age interaction (p = 0.02) is reported as exploratory.
- Dropping the top 1% by Cook's distance gives −0.02.
- Uncertainty. Four SEs for the slope: model 0.229, sandwich 0.311, linearized 0.266, Rao–Wu PSU bootstrap 0.272. Use t with 15 df rather than z. The design effect is 2.7 for a mean and about 1.4 for a slope.
- Sensitivity.
- A specification curve of 64 analyses: −0.18 to +0.64, none distinguishable from zero.
- Medicine users and two-day means are the choices that matter.
- Two-recall correlation r = 0.32 (unweighted). The weighted conditional calibration slopes are 0.24 without energy and 0.06 with energy. They represent reliability only under classical error assumptions, which correlated reporting errors and noisy covariates can violate.
- Regression calibration without energy gives +0.37, approximate CI −1.9 to +2.7. With energy, +0.65 ± 8.7. Both stages enter the joint design delta-method variance; weak calibration makes even these approximate intervals fragile.
- Causal or not? A causal diagram. The diagnosed eat a little less sodium but no less per calorie. DASH-Sodium (6.7 mm Hg) and He, Li & MacGregor (4.2 mm Hg per 4.4 g of salt). Internal vs external validity, and what the report may and may not say.
- The same pipeline on the World. The World's new health block has a true effect of 1.5 mm Hg per g, a
diagnosis loop and noisy recalls. Over 200 NHANES-shaped surveys:
- one-day recall averages 0.23 (coverage 0%);
- joint calibration averages 0.74 (69.5%);
- even true intake averages 0.96 (53.5%): diagnosis, medication selection and model projection separate the descriptive slope from the structural effect.
- A 400-person randomized trial recovers 1.93 ± 1.20, and covers the truth in 95.8% of 2,000 repeats.
- Communicating. Three bad sentences and one good one; a one-page report; graphic integrity (axis limits change visual emphasis; neither scale proves signal or noise); the appendix.
- Reproducibility and ethics.
- The chain from the CDC's files to every number; a SHA-256 fingerprint and seeds.
- NHANES's privacy layers and consent.
- Race as a social category; publishing nulls; interests.
- A thirteen-item checklist.
- The BSc problem set. Six problems spanning Stages I–II, solved on screen.
Numerical results are computed in compute.py by the pipeline in pipeline.py:
- the data are NHANES 2017–2018 (CDC/NCHS, public domain), extracted by
tools/nhanes_extract.pyintoexplainer/stats/data/nhanes_bp.csv(5,533 adults, 29 columns, SHA-256ae9be143…); the SEQN-aligned two-day weight supplement isdata/nhanes_day2_weights.csv. CDC requires WTDR2D when an analysis uses both recalls; the original extract remains unchanged. All 5,533 rows reproduce byte-for-byte from current CDC downloads; - the replays use the World's health block.
Built in this part:
-
The capstone pipeline (
pipeline.py):clean, the decision log of chapter three;fit, the pre-specified model with design-based SEs, and its 64 variants;calibrated, regression calibration with two-day dietary weights and joint two-stage design variance;world_frame, an NHANES-shaped survey of the World (10 strata, 2 PPS town draws with replacement each, 250 adults per draw, exact age-stratum sampling probabilities and Hansen–Hurwitz draw weights).
All of them run unchanged on NHANES and the World.
-
statkit.capstone(explainer/stats/kit/capstone.py):DecisionLog, restricted cubic splines, reliability from replicates, and regression calibration. -
statkit.surveyadditions:svy_meanandsvy_ols(Taylor linearization over strata and PSUs, with model and sandwich SEs alongside), andpsu_bootstrap_weights(Rao & Wu 1988).Both are checked in
tests/test_stats_kit_capstone.py. -
The World's health block (
World.health):- BMI, energy and usual sodium;
- systolic pressure with
SODIUM_EFFECT= 1.5 mm Hg per g; - diagnosis, salt-cutting and medicine;
- three readings and two 24-hour recalls.
It adds a block without changing any other.
-
The Museum's NHANES extract (
museum.nhanes()).
The Coverage Board gains three rows: 95% intervals for the World's sodium effect.
| Method | Setting | Reps | Achieved | Verdict |
|---|---|---|---|---|
| one-day recall, design t CI | the World's sodium effect, 5,000 surveyed | 200 | 0.0% | broken |
| regression calibration, design t CI | the World's sodium effect, 5,000 surveyed | 200 | 69.5% | broken |
| randomized trial, z CI | the World's sodium effect, 400 randomized | 2,000 | 95.8% | kept |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | Salt and blood pressure: a question | mean 3,551 mg; 76% over 2,300; 9,254 interviewed, 8,704 examined; crude slope −0.14 (3,071 adults) |
| 1 | From question to estimand | 236 million adults; two recalls r = 0.32 (2,659); 2⁶ = 64 analyses |
| 2 | The design and its weights | 15 strata, 30 PSUs; Black 24% vs 11%, Asian 14% vs 6%, 60+ 39% vs 29%; weights 4,580–419,763, median 26,549; 127.1 vs 123.9; SE 0.49 vs 0.26 (weighted population SRS reference), deff 3.6 |
| 3 | Cleaning | codes 4,742 / 33 / 490; 382 at 80; 87 diastolic zeros; first reading +0.6; 57 under 500 kcal, 67 over 5,000; funnel 5,533 → 3,071 |
| 4 | Exploration | median 118 (103–141), 24% ≥ 130; sodium median 3.26, mean 3.55; r(sodium, energy) = 0.75; deciles 120 → 122 |
| 5 | A first model | age +0.40, female −4.97, BMI +0.52, energy +0.07, sodium +0.07 [−0.50, +0.63], p = 0.81 |
| 6 | Checking it | skewness 1.05; spline Wald F₂,₁₅ = 4.98, p = 0.022, sodium +0.04; interaction −0.041 (SE 0.016); top 1% dropped: −0.02 |
| 7 | Uncertainty | SEs 0.229 / 0.311 / 0.266 / 0.272; t₁₅ = 2.13; mean 120.4, SE 0.54 vs 0.33 |
| 8 | Sensitivity | 64 slopes −0.18 to +0.64; medicine +0.20 → −0.07; two days +0.01 → +0.12; λ 0.24 and 0.06; calibrated without energy +0.37 ± 2.32; with energy +0.65 ± 8.72 |
| 9 | Causal or not? | told 33%; sodium 3.40 vs 3.55, per 1,000 kcal 1.66 vs 1.64; age 58 vs 44; DASH-Sodium 6.7; meta-analysis 4.2 per 4.4 g salt |
| 10 | The same pipeline on the World | one survey 0.35 / 1.23 / 1.00; 200 surveys 0.23 / 0.74 / 0.96, coverage 0 / 69.5 / 53.5%; trial 1.93 ± 1.20, 95.8% |
| 11 | Communicating | the one-page report; decile axis 117–125 vs 0–140 |
| 12 | Reproducibility and ethics | SHA-256 ae9be143…; 382 ages and 821 income ratios top-coded |
| 13 | The BSc problem set | six problems, below |
| 14 | Outro | the Transcript: the BSc |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: a question. For example: how does blood pressure depend on salt and age? Answered from NHANES (CDC, public domain; availability (verify), otherwise the World's health survey).
- From question to estimand. What exactly is being estimated, for whom.
- The design and its weights (Part 18). Why survey weights matter here.
- Cleaning. Codes, missing values, implausible values: each decision logged.
- Exploration (Part 1). Distributions, relationships, surprises.
- A first model (Parts 12, 14). Specification choices, written down before looking at results.
- Checking it. Residuals, influence, nonlinearity (splines), interactions.
- Uncertainty. Design-based vs model-based SEs; the bootstrap (Part 16).
- Sensitivity. What changes the answer: covariates, outliers, missing-data handling.
- Causal or not? What this analysis can and cannot say (a preview of Parts 35–37).
- The same pipeline on the World, where the truth is known: did we recover it?
- Communicating. A one-page report and its graphics (Part 1's integrity rules).
- Reproducibility and ethics. Seeds, scripts, data provenance, privacy.
- The BSc problem set. Six problems spanning Stages I–II, solved.
- Outro. The Transcript: the BSc. The master's begins.
Built: the capstone pipeline and report.
Build the film
python -m videos.stats.stats20.compute # the part's numbers, into .cache/stats20
python tools/build.py stats20 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats20 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats20. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
# once: the data (already in the repository; this rebuilds it from the CDC)
for f in DEMO_J BPX_J BMX_J DR1TOT_J DR2TOT_J BPQ_J; do
curl -sSL -o $f.xpt https://wwwn.cdc.gov/Nchs/Data/Nhanes/Public/2017/DataFiles/$f.xpt
done
python tools/nhanes_extract.py . explainer/stats/data/nhanes_bp.csv
python tools/nhanes_extract.py --day2-weights . explainer/stats/data/nhanes_bp.csv videos/stats/stats20/data/nhanes_day2_weights.csv
python -m videos.stats.stats20.compute --force # recompute after changes, including dependent report and board results
python tools/build.py stats20 -q l # fast 480p preview
python tools/build.py stats20 # 1080p30 -> renders/stats20.mp4
python tools/qa_scene.py stats20 Sensitivity
python tools/lecture_length.py stats20 --floor 50