Time to Event
How do you average lifetimes you have not finished watching?
Freireich's leukaemia trial ends with twelve of twenty-one patients on 6-MP still in remission: averaging their times as if they had relapsed gives 17.1 weeks, and averaging only the relapses gives 12.1, and both are wrong. The part builds the answer from the risk set. The hazard and the survival function determine each other, and under independent censoring Kaplan and Meier's product over the shrinking risk set estimates survival, drawn as the staircase with Greenwood's variance around it. Aalen's counting processes make every estimator an integral against a martingale. The log-rank test compares observed and expected relapses over risk sets, and Cox's partial likelihood estimates a hazard ratio without the baseline. Then the traps: a hazard ratio drifts when frailty selects the survivors, and counting the wait for a heart transplant as treated time gives Stanford's programme a hazard ratio of 0.27 where the time-varying analysis gives 1.13. Competing risks, frailty models and prediction under censoring close the part.
What you need. Likelihood and its asymptotics (Part 22) and generalized linear models (Part 24).
- Hook
- Freireich's 6-MP trial, 1963
- Mathematics
- censoring, Kaplan–Meier, Greenwood, log-rank, Cox, counting processes, competing risks, frailty
- Built
- statkit.survival
What you will be able to do
Bachelor's
- Compute a Kaplan-Meier curve by hand from a risk table and read a median from it.
- Explain why dropping the censored, or counting them as events, biases a survival estimate.
Master's
- Derive Greenwood's variance and compute a log-log interval for S(t).
- Compute the log-rank statistic from observed and expected events over risk sets.
- Write Cox's partial likelihood, fit it, and check proportional hazards with Schoenfeld residuals.
PhD
- Show that the counting process minus its compensator is a martingale and write the Nelson-Aalen estimator as a stochastic integral against it.
Practice
- Report a restricted mean survival time beside a hazard ratio, and say why a period-specific hazard ratio is not a causal effect.
- Recognize immortal time and remove it by coding treatment as time-varying.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 12 min · Master's 51 min · PhD 53 min · Practice 18 min.
- 0The 6-MP trialBachelor's2 min
- 1LifetimesBachelor's3 min
- 2Censoring and truncationMaster's4 min
- 3Kaplan–MeierBachelor's3 min
- 4Greenwood's varianceMaster's3 min
- 5Nelson–AalenMaster's3 min
- 6Counting processesPhD3 min
- 7The log-rank testMaster's3 min
- 8Cox's partial likelihoodMaster's4 min
- 9Checking CoxMaster's3 min
- 10What hazard ratios meanPractice3 min
- 11Immortal timePractice4 min
- 12Parametric and AFT modelsMaster's3 min
- 13Competing risksMaster's4 min
- 14FrailtyMaster's3 min
- 15PredictionMaster's4 min
- 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 6-MP trialBachelor's2 min
In 1963 Emil Freireich and colleagues at the National Cancer Institute reported a trial in acute leukaemia, then almost always fatal for children. Steroids could push the disease into remission for a few weeks. The question was whether a drug, six-mercaptopurine, would keep it there longer. Patients in remission were paired, and within each pair one received the drug and the other a placebo, by chance, with neither patient nor doctor knowing which. It was one of the first randomized, placebo-controlled trials in cancer, and its numbers became the most re-analysed little data set in survival analysis.
Here are the forty-two patients, one lane each, ending at relapse, a red dot. On placebo, every one of the twenty-one relapsed, the last at twenty-three weeks. On the drug, nine relapsed. The other twelve, the open rings, were still in remission when the trial ended or when they were last seen: we know only that their remission lasted at least that long.
So how long does remission last on the drug? Averaging the twenty-one times as if all had relapsed gives weeks, which is too short, since twelve of them had not. Averaging only the nine relapses gives , shorter still, since it throws away the patients who did best. And waiting until everyone relapses is neither ethical nor useful.
The open rings are censored observations: each says, at least this long. That is real information, and the whole subject is about using it rather than throwing it away. The tools are the risk set, the hazard, Kaplan and Meier's curve, and Cox's model. And there are traps, famous ones, in what hazard ratios mean, in time that cannot kill you, and in risks that compete.
Numbers: 12 of 21 censored
1LifetimesBachelor's3 min
For the continuous lifetime models here, T is positive and has a density. Its survival function S of t is the chance it exceeds t. The hazard is the instantaneous rate of the event at time t among those who have survived to t: the density divided by the survival. Its integral is the cumulative hazard, which is minus the log of the survival function, so survival is e to the minus cumulative hazard. Any one of the three determines the other two.
The hazard is the natural language for lifetimes because it describes risk among those still at risk. A hazard of point zero one a year means that, of those alive now, about one in a hundred will die over the coming year if the hazard stays near that rate. It can rise with age, fall after a dangerous operation, or stay constant, which gives the exponential distribution of Part three, the only nondegenerate continuous lifetime distribution with the memoryless property.
The oldest survival curve is John Graunt's of 1662, from London's weekly bills of mortality, which we met at the very start of this course. Of a hundred conceived, he reckoned, sixty-four were alive at six, twenty-five at twenty-six, and six at fifty-six. It was a survival function, partly guessed. Edmond Halley built a better one in 1693 from the records of Breslau, and used it to price annuities: the beginning of actuarial science.
In 1825 the actuary Benjamin Gompertz noticed that adult death rates grow exponentially with age. On a log scale, a single Gompertz hazard is a straight line. Our sum of two Gompertz hazards is approximately straight. Here are the World's hazards for a man and a woman with systolic pressure 130, BMI 27 and frailty one: men's higher at every age, and both doubling roughly every eight years. Gompertz's law still describes human mortality between about thirty and ninety remarkably well.
Integrating the hazard gives the survival curve. For a model man recruited at sixty, with systolic pressure 130 and BMI 27, in the World, survival from sixty falls slowly at first, then faster, as the hazard climbs. After integrating over frailty drawn at recruitment, half this model group live another years. The median is the natural summary for lifetimes, because it needs only the first half of the curve; the mean needs the whole tail, and the tail is exactly what censoring hides.
Hazards come in shapes. The Weibull family, h of t equals k t to the k minus one, falls when its shape k is below one, is constant at one, and rises above one, like machines that wear out. Human mortality over a whole life is a bathtub: high in infancy, low through youth, then rising by Gompertz's law. Looking at the hazard, not the density, is what makes these shapes visible.
Numbers: median 18.6 years from 60 (specified covariates)
2Censoring and truncationMaster's4 min
Four ways a lifetime can be partly hidden. Right censoring, the common one: we know only that the event had not happened by some time, because the study ended or the patient was lost. Left censoring: it had already happened before we looked. Interval censoring: it happened between two visits. And truncation, which is different: people whose event came too early never enter the study at all, so we do not even know they existed.
With right censoring we see the smaller of the lifetime T and a censoring time C, and an indicator of which came first. The likelihood and regression analyses require censoring to be independent of the lifetime conditional on the covariates used, with adequate follow-up support. Unadjusted Kaplan-Meier needs independence at the population level being pooled; conditional independence alone is insufficient. Then the likelihood multiplies the density for each observed event and the survival function for each censored case, exactly the at least this long of the open rings. The assumption fails if the sickest patients drop out, or the healthiest stop coming to clinic, and the data alone cannot tell: it is the missing at random of Part forty-one, in disguise.
The World runs a cohort study: adults aged forty to seventy-nine, followed for fifteen years. deaths are seen, and the other are censored: most reached the end of the study alive, and the rest moved away or stopped answering. Unlike any real study, the World also knows every lifetime, including those it did not see, so we can check each method against the truth.
What share of the cohort survives ten years? The truth, in gold, is . Counting the censored as deaths gives , far too low. Dropping them, and using only people whose fate is known, is worse: , because the dropped are mostly survivors. Counting them as alive to the end gives , too high. The Kaplan-Meier curve, in blue, closely follows the truth: . This agreement is empirical, under the simulator’s independent dropout; Kaplan-Meier is not exact in one finite sample.
Truncation appears as soon as we measure time by age. Someone enrolled at sixty-five is seen only because they survived to sixty-five. So the risk set at each age must contain only those who have entered and not yet left: delayed entry. Ignoring it treats everyone as at risk from forty, crediting them with years in which they could not have died in our data. Age can be a useful clock. Estimating survival from forty additionally requires entry to be independent of lifetime, possibly after appropriate adjustment.
A separate seeded demonstration generates lifetimes from forty and independent scheduled entry ages from forty to eighty. Only people alive at entry are observed, followed for at most fifteen years. The true survival from forty, in gold, has a median of . Ignoring delayed entry gives a curve that is far too optimistic, with a median of . Starting each person’s risk at entry closely follows the reference curve here. Frailty is generated at forty and survivor selection is retained; this is not the original World cohort, whose frailty is reset at recruitment.
Numbers: 0.786 vs 0.590 / 0.320 / 0.815
3Kaplan–MeierBachelor's3 min
Edward Kaplan and Paul Meier's idea of 1958: write survival past time t as a chain of conditional survivals, past each event time given survival to it. Each factor is easy to estimate: of the n k people still at risk just before t k, d k have the event. Multiply the factors one minus d over n. That is the product-limit estimator, and it is the nonparametric maximum likelihood estimate of S. A censored patient never causes a step: they simply leave the risk set, after contributing to every factor up to the time they were last seen.
The KM staircase, built step by step for the twenty-one patients on 6-MP. Below the plot, each patient is a dot in order of their time, red for a relapse, grey for censored. At week six, three of the twenty-one relapse: the curve drops by the factor one minus three over twenty-one. One patient is censored at six, so at week seven only seventeen are at risk, and one relapse multiplies by one minus one over seventeen. The grey ticks mark censorings: no step, just a smaller risk set afterwards. The curve ends at , not at zero, because the longest times are censored.
Both arms. On placebo, red, the curve falls to zero by week twenty-three. On 6-MP, green, it falls slowly and stays above a third. The median remission is weeks on placebo and on the drug. The curves separate from the first weeks. Whether chance could produce such a gap is chapter seven's question.
Bradley Efron gave another way to see the estimator in 1967. Give each of the twenty-one patients, in order of time, an equal share of probability. When we reach a censored patient, we know their lifetime lies somewhere to the right, so pass their share equally to everyone later. When all the censored shares have been passed on, the mass sitting on each relapse is exactly the Kaplan-Meier drop there. Redistribute to the right, and the product-limit estimator appears; the mass left on the last censored patients is the curve's final height.
The median is read off where the curve first reaches one half. On 6-MP it is weeks, and its confidence interval, from the times where the curve's band crosses one half, runs from weeks to beyond the end of the data. On placebo it is , from to . The unrestricted mean is not identified nonparametrically when follow-up ends with survival above zero: the unseen tail requires additional assumptions. chapter ten's restricted mean is the fix.
Numbers: medians 23 vs 8 weeks
4Greenwood's varianceMaster's3 min
The log of the Kaplan-Meier estimate is a sum of logs of the factors. Each factor is a binomial proportion among the n k at risk, and the delta method gives the variance of its log. Adding them and converting back gives Major Greenwood's formula of 1926, derived for life tables of cancer patients half a century before Kaplan and Meier: S squared times a sum of d over n times n minus d. The asymptotic linear representation uses orthogonal martingale increments, which justify this variance estimate; the nonlinear product factors are not claimed independent.
The 6-MP curve with approximate ninety-five percent pointwise intervals. The plain band, estimate plus or minus one point nine six standard errors, in red, is symmetric before clipping; this display clips it to zero and one. Unclipped it can extend above one or below zero. The log-log band, in green, is computed for log of minus log S and transformed back, so it stays inside zero and one and is lopsided where it should be. Tail uncertainty often grows as the risk set shrinks, although interval width need not increase monotonically: by week thirty-two only a handful remain.
Three standard intervals. The plain one is a Wald interval on the raw scale. The log interval works on log S. The log-log interval works on log of minus log S, a scale that runs over the whole real line, and maps back into zero and one. The transformation matters when the risk sets are small, the lesson of Part eleven's binomial intervals once more. The Board measures how much.
These bands are pointwise: at each single time, their nominal coverage at a fixed time is ninety-five percent, approximately under regularity conditions. A statement about the whole curve at once, that it lies inside the band everywhere up to some horizon, needs a simultaneous band. W. J. Hall and Jon Wellner built one in 1980 from the fact that the Kaplan-Meier error has a Gaussian-process limit, expressible using Brownian motion or a rescaled Brownian bridge on a new clock, the subject of Part forty-eight. Simultaneous bands are wider; reading a pointwise band as if it were simultaneous is another way of looking at many times and reporting the one that looks best.
Numbers: plain 87.0% vs log-log 90.8%
5Nelson–AalenMaster's3 min
Wayne Nelson, an engineer studying failures of electrical equipment, proposed in 1969 to estimate the cumulative hazard directly: at each event time, add the number of events divided by the number at risk. Odd Aalen gave it its theory in 1978. Its variance is a sum of d over n squared. Exponentiating minus it gives a survival estimate that is always a little above Kaplan-Meier, since e to the minus x exceeds one minus x. The idea: each event uses up a one over n k share of the risk among those exposed.
The two arms' cumulative hazards. On placebo, the steps climb along a fairly straight line, at about per week. On 6-MP, the line is much flatter, about a fifth as steep. A straight cumulative hazard means a constant hazard, an exponential lifetime; curvature up or down shows the hazard rising or falling, far more visibly than a survival curve does.
Side by side for 6-MP, the two survival estimates are close early in follow-up, and drift apart only as the number at risk gets small. For continuous lifetimes and independent censoring, both are consistent where follow-up has support; Nelson-Aalen is the more natural for the theory, and for checking models, because it estimates the hazard, which is what models are written in.
Before computers, survival was computed from life tables: follow-up cut into intervals, with the numbers entering, dying and censored in each. The actuarial estimate of the chance of dying in an interval approximately counts each censored person as at risk for half of it, using a uniform-within-interval censoring approximation. Multiplying the interval survivals gives Sidney Cutler and Fred Ederer's estimator, published the same year as Kaplan and Meier's. When exact event and censoring times are available, shrink intervals so distinct event and censoring times are separated; the actuarial table becomes the product-limit estimator: the limit in its name.
That makes the cumulative hazard a diagnostic. An exponential gives a straight line through the origin. A Weibull gives a straight line when log H is plotted against log t, with slope equal to its shape. And if two groups have proportional hazards, their log cumulative hazards are parallel, a constant distance beta apart, the assumption of chapter eight. So look at log H against log t before fitting anything.
Numbers: slopes 0.15 vs 0.03 a week
6Counting processesPhD3 min
Odd Aalen's 1978 counting-process work recast the whole subject in terms of counting. N of t counts the events observed by time t. Y of t counts those still at risk. The compensator integrates the hazard over the risk set: the accumulated predictable event intensity, based on who has been at risk. The difference, observed minus expected, is a martingale: its expected future change, given the past, is zero, provided the specified intensity remains valid in the observed-data filtration and censoring does not reveal additional future event risk.
One path. Fifty lifetimes with hazard one, randomly censored. The count of events climbs in unit steps. The compensator climbs smoothly, at a rate equal to the hazard times the number at risk, so it slows as deaths and censoring empty the risk set. The two stay close: the red steps scatter around the gold curve.
Martingales have no drift: given everything up to just before t, the expected increment is zero. Their predictable variation is the compensator itself, so the variance of M is the expected number of events. With suitable integrability, weighting the increments by a predictable process known just before each time gives another martingale. And Rolando Rebolledo's central limit theorem says a normal limit follows when jump sizes are negligible and predictable variance converges appropriately. Part forty-four proves it.
Check it on four thousand such paths. Observed minus expected events by time one averages , zero up to simulation noise, and its variance is , against an expected compensator of . And the histogram is close to a normal reference; the martingale central limit theorem explains the approximation under its conditions.
Why bother? Because every estimator in this part is an integral against M. The Nelson-Aalen error is the martingale integral of dM over Y, for the cumulative hazard stopped when the risk set becomes empty. This qualification matters: the estimator is not exactly unbiased for unrestricted H after the last person leaves. Its variance estimator follows at once. The Kaplan-Meier error has the same form, and Greenwood's formula drops out. The log-rank statistic is a weighted integral of dM, and so is Cox's score. Per Kragh Andersen and Richard Gill used this in 1982 to give Cox's model its large-sample theory, including covariates that change over time.
Numbers: Var M(1) = 26.0 ≈ EΛ = 26.3
7The log-rank testMaster's3 min
At each event time, form a two by two table: group by event, among those at risk. If the groups have the same hazard, the events among the at-risk are shared out at random, so group one's count is hypergeometric, as in Part fourteen's Fisher test, with expectation d k times group one's share of the risk set. Its variance is the hypergeometric one. Sum observed minus expected over all event times, square, and divide by the summed variance: Nathan Mantel's log-rank statistic of 1966, the Cochran-Mantel-Haenszel test with time as the strata. Under the null it is asymptotically chi-squared on one degree of freedom under the usual event-count and risk-set conditions.
The first rows for Gehan's data, counting 6-MP as group one. At week one, forty-two at risk, half on the drug, two relapses, both on placebo: the drug arm expected one and had none. Week after week the drug arm has fewer relapses than its share of the risk set predicts. In total the 6-MP group had relapses where were expected.
Against the chi-squared distribution on one degree of freedom, the observed statistic is , a p-value of about four in a hundred thousand. Edmund Gehan's 1965 test, which weights each table by the number at risk, gives : a little less, because it emphasizes the early weeks, when both arms still had most patients.
The log-rank test is one member of a family that weights the tables. Equal weights are locally efficient against proportional-hazards alternatives under the standard model. Weighting by the number at risk stresses early differences. Thomas Fleming and David Harrington's weights can stress early, late or middle times. The weights must be chosen before looking, or the test is Part thirty-three's garden of forking paths.
The log-rank test answers only whether the curves differ, not by how much. It can miss a real difference when the curves cross, because early harm and late benefit cancel in the sum. A stratified version sums observed minus expected within strata, such as hospitals or disease stages. And the estimate behind it, the quantity whose score test it is, is Cox's hazard ratio, which comes next.
Numbers: χ² = 16.8
8Cox's partial likelihoodMaster's4 min
David Cox's model of 1972: each person's hazard is a common baseline hazard multiplied by e to the linear predictor. The baseline can have any shape at all, and is left unspecified. Each e to the beta j is a hazard ratio, the factor by which the hazard is multiplied for one unit of x j, and it is the same at every time: the proportional hazards assumption. A few parameters of interest and an infinite-dimensional nuisance: a semiparametric model, the kind Part forty-nine studies.
Cox's insight. At each event time, ask: given that one of the people at risk fails now, what is the chance it is this one? It is their hazard over the sum of everyone's hazards in the risk set. The unknown baseline hazard multiplies the top and every term at the bottom, so it cancels. Multiply these conditional probabilities over the event times: the partial likelihood, which depends on beta alone. Cox showed in 1975 that maximizing it behaves like ordinary maximum likelihood. Its score is a sum over events of each failure's covariate minus the hazard-weighted average among those at risk: observed minus expected once more.
The model is for continuous time, but real times are rounded, so several events share a time. Norman Breslow's approximation lets every tied failure face the full risk set; it is simple but can differ materially from other tie methods when ties are numerous; the direction is not universal. Efron's approximation of 1977 removes the tied failures from the risk set gradually, one average share at a time, and is the usual default. An exact continuous-time treatment sums over possible failure orderings; a discrete conditional likelihood sums over failing subsets. These are distinct formulations.
Gehan's data, with placebo as the covariate. Efron's method gives a hazard ratio of , with a ninety-five percent interval from to ; Breslow's, with these many ties, a little less. On placebo the hazard of relapse is nearly five times that on the drug, week after week, if the hazards are proportional. And with no tied times, Cox's score test for a single group indicator is exactly the log-rank test; here the ties make them differ a little.
A real regression. Primary biliary cholangitis is a slow autoimmune disease of the liver's bile ducts. The Mayo Clinic's trial of 1974 to 1984 followed three hundred and twelve patients; one hundred and twenty-five died. Cox's model with age, oedema, and the logs of bilirubin, albumin and prothrombin time refits the five-variable form of the famous Mayo model; these are not a reproduction of every detail of the original published score. Transplants are censored, requiring appropriate independent-censoring assumptions for the mortality interpretation. Older age, oedema, high bilirubin and slow clotting raise the hazard; albumin lowers it. Doubling bilirubin multiplies the hazard by . E. Rolland Dickson and colleagues turned these five into a risk score that hepatologists used to decide when to transplant.
To predict, the baseline is needed after all. Breslow's estimator is a Nelson-Aalen estimator in which each person at risk counts by their hazard ratio. A typical patient, with median values of all five, and the same patient with a bilirubin of eight: half are dead within about five years. Each curve is the baseline raised to the power of that patient's hazard ratio.
The trial itself tested D-penicillamine against placebo. The curves lie on top of each other: a hazard ratio of , with an interval from to , and a log-rank p-value of . This analysis detects no survival benefit; its confidence interval still allows clinically relevant effects. The lasting value of the trial was its careful follow-up, which gave medicine the prognostic model.
Numbers: HR 4.82; the Mayo model
9Checking CoxMaster's3 min
David Schoenfeld's residuals of 1982: at each event, the failing person's covariate minus the risk-set average, the terms of the score. Scaled using the estimated coefficient covariance and added to beta hat, they estimate the coefficient at that event's time, as Patricia Grambsch and Terry Therneau showed in 1994. If the hazards are proportional, they scatter around a horizontal line; a trend against time means the effect changes, and a regression on a function of time gives a test.
The Veterans' Administration lung cancer trial: a hundred and thirty-seven men with advanced disease, almost all of whom died. The Karnofsky score measures how well a patient can function, and Cox's model gives a hazard ratio of per ten points: fitter patients die more slowly. But the scaled residuals tell a different story over time. The effect is strong in the first months and fades towards nothing later; our approximate KM-transformed scaled-residual diagnostic gives a p-value of . This diagnostic uses a simplified constant covariance and Breslow risk-set residuals, so it is not an exact reproduction of software’s tie-adjusted Grambsch-Therneau test. The single hazard ratio averages a large early effect and none at all.
The same tests for the Mayo model. These approximate diagnostics do not provide strong evidence against the assumption; bilirubin and prothrombin time are borderline, with p-values near point one. Like every goodness-of-fit test, its power depends on the departure and the available events, and very large samples can detect clinically trivial changes. Look at the residual plot, and ask whether the change in effect matters.
What to do. If the offending variable is a nuisance, stratify on it: each stratum gets its own baseline hazard, and nothing is assumed about how they relate. If its effect is the point, let the coefficient change with time, smoothly or in pieces. Time-varying covariates or piecewise effects can be fitted by splitting follow-up into start-stop rows; the counting-process form of chapter six. Or report an estimand that needs no proportional hazards at all, the subject of chapter ten.
For the veterans, split each man's follow-up at ninety days and give the score a separate coefficient in each piece. In the first ninety days, ten Karnofsky points cut the hazard to of its value; after ninety days, the ratio is : a much weaker estimated late association. An interval containing one does not establish that the late effect is zero.
Numbers: Karnofsky 0.61 → 1.01
10What hazard ratios meanPractice3 min
A hazard ratio at time t compares the event rates among those still alive at t. Randomization makes the arms comparable at the start, and only at the start. If the treatment works, it keeps alive people who would otherwise have died, typically the frailer ones. So later in the trial the treated survivors are frailer on average than the control survivors, and the hazard ratio mixes the effect of the treatment with the selection it caused. Miguel Hernán called this the hazards of hazard ratios.
A seeded trial with twenty thousand patients. For every single patient, the treatment halves the hazard at every moment. Patients differ in an unmeasured frailty that multiplies their hazard. The empirical incidence-rate ratio in each period starts near one half, then drifts up toward one: . Nothing about the treatment changed. For speed, Cox is fitted to a fixed one-in-twenty subsample of one thousand patients and reports , an average of ratios among ever more different groups.
The mechanism. At randomization, about thirteen and a half percent are very frail in expectation in each arms. In the control arm the frail die quickly, and in the treated arm more of them survive. So the later comparison sets frailer treated survivors against hardier controls: randomized at the start, confounded by survival afterwards.
None of this breaks the log-rank test: under the no-treatment-effect null, independent censoring and the usual risk-set conditions, the test is valid. But read as a causal effect, a hazard ratio is hard to interpret, even in a perfect randomized trial. Hernán's advice: report absolute quantities, the difference in survival at chosen times, or the difference in restricted mean survival, and show the curves.
The restricted mean survival time is the expected lifetime capped at a horizon tau: the area under the survival curve up to tau. Its estimate is the area under the Kaplan-Meier curve, an old idea of Oscar Irwin's revived by Patrick Royston and Mahesh Parmar. Its variance has a Greenwood-like formula. The difference between arms is the average time gained by tau, in units a patient understands, and it needs no proportional hazards.
Gehan's data, to thirty-five weeks. Under the 6-MP curve lies an area of weeks, under the placebo curve . Over the first thirty-five weeks, the drug gave patients on average more weeks in remission, with an interval from to . This approximate percentile interval resamples the twenty-one original pairs, keeping each pair together and carrying its estimated curve flat to thirty-five weeks.
Numbers: 0.52 → 0.76; RMST +14.6 weeks
11Immortal timePractice4 min
In 2001 Donald Redelmeier and Sheldon Singh reported that actors who won an Academy Award lived almost four years longer than nominees who did not. Fame, they suggested, was good for health. But to win an Oscar, an actor has to be alive on the night. Counting each winner's life before their first win as winner's time credits the winners with years in which they could not have died as winners: immortal time. When Marie-Pierre Sylvestre, Ella Huszti and James Hanley re-analysed the data in 2006, treating winning as something that happens during follow-up, the advantage shrank to about a year and was no longer statistically significant.
The general mistake: classifying people at the start of follow-up by something that happens to them later. Whoever ends up treated must have survived until treatment, so the treated group is guaranteed a stretch of survival. Correcting the time classification requires treatment to be a covariate that switches on when it starts: each person contributes untreated time until then, and treated time after, using chapter nine's start-stop rows. Or classify everyone at a fixed landmark time and follow from there.
The classic case. Stanford's heart transplant programme accepted patients between 1967 and 1974. received a heart, after a median wait of days. died while waiting. Compare survival from acceptance of those who were ever transplanted with those who never were, and the gap is enormous. But part of it is built in: to receive a heart you had to survive the wait, and those who died early never could.
The numbers. The naive comparison gives a hazard ratio of : transplantation would cut the hazard of death by nearly three quarters. With transplant as a time-varying covariate, the ratio is , and adjusting for age, , with wide intervals around one. In these early years, with the drugs of the time, these association estimates are imprecise. Correcting immortal time does not resolve confounding by disease severity or establish a causal absence of benefit. John Crowley and Marie Hu's analysis of 1977 made time-varying covariates a standard tool.
The World's cohort has a statin that does nothing at all; doctors start it sooner in people with high blood pressure. Comparing ever-users with never-users gives a hazard ratio of , a protective effect, with an interval excluding one: immortal time again. Treating use as time-varying removes that, and reveals the next bias: , harmful, because those given statins had higher pressure, confounding by indication. Adjusting for pressure and age as well gives , closer to the known no-effect model. This approximate adjusted Cox fit is not itself the simulator’s exact causal truth.
Samy Suissa found immortal time in dozens of published studies of drugs, often producing impressive, and spurious, benefits. The cure is to line up three things: the time zero of follow-up, the moment of eligibility, and the moment treatment is assigned. That is what emulating a target trial, Part thirty-six's discipline, enforces. In a randomized trial the three coincide by design; in observational data, only by care.
Numbers: Stanford 0.27 → 1.13
12Parametric and AFT modelsMaster's3 min
The accelerated failure time model is a linear regression for the log of the lifetime. Covariates stretch or shrink time: a person's survival curve is the baseline curve with the clock running faster or slower. So e to the gamma j is a time ratio, which many find easier to explain than a hazard ratio: this treatment makes remissions last forty percent longer. The error distribution sets the shape of the hazard.
A parametric model is fitted by chapter two's likelihood: the density for each observed event, the survival function for each censored time. Then everything from Part twenty-two applies: Newton's method, the observed information for standard errors, likelihood ratio tests and Akaike's criterion.
The Weibull distribution, named for the Swedish engineer Waloddi Weibull, is special. It is both a proportional hazards model and an accelerated failure time model, with the hazard ratio coefficient equal to minus the time coefficient over the scale. Within the regular nondegenerate continuous families with a common AFT scale and freely varying covariates, it is the only family, with its special case the exponential, that is both, so Weibull hazard ratios can be compared directly with Cox's.
The veterans' data under four models. Ten Karnofsky points stretch survival time by a factor of about one point four to one point five in every model. The Weibull's scale is close to one, so it is nearly exponential, and its implied hazard ratio, , matches Cox's. By Akaike's criterion the log-logistic fits best: its hazard rises and then falls, a descriptive fit here, not proof of a particular selection mechanism.
Against the Kaplan-Meier curves for the fitter and the frailer men, the Weibull's curves at scores of forty and eighty, and the log-logistic's, which keep a heavier tail of long survivors. Parametric models give smooth curves, efficient estimates and extrapolation beyond the data, which is exactly where they can be most wrong. Health economists, who need lifetime means, extrapolate anyway, and should show several models.
Some diseases are cured in a fraction of patients. A cure model mixes a fraction pi who will never have the event with others whose survival falls to zero. Pi is the height of the plateau the curve approaches. The 6-MP curve stops at : a cured fraction, or simply the end of follow-up? Thirty-five weeks cannot say. Nonparametric identification requires enough follow-up to distinguish a genuine cured fraction from a long tail. A finite plateau alone does not suffice; parametric extrapolation adds assumptions.
Numbers: log-logistic AIC 1,448.3
13Competing risksMaster's4 min
Monoclonal gammopathy of undetermined significance, MGUS, is an abnormal protein in the blood, common in older adults. A few patients progress to multiple myeloma or a related cancer; most die of something else first. A death is not a censoring: right censoring leaves later progression unknown, while death prevents it for ever. So one minus the Kaplan-Meier curve, treating deaths as censored, gives a net-risk quantity constructed from the observed cause-specific hazard. Interpreting it as a causal risk in a world where nobody dies of anything else requires extra assumptions about eliminating the competing cause.
Each cause k has its own cause-specific hazard. The chance of failing from cause k by time t, the cumulative incidence, integrates that hazard against the chance of having survived everything until then. Its estimate, by Odd Aalen and Søren Johansen, sums the cause-k events over the risk sets, each weighted by the all-cause Kaplan-Meier just before. The incidences of all the causes add up to one minus the all-cause survival, as probabilities of a real world should.
Robert Kyle's Mayo Clinic cohort: patients with MGUS, with a median age of . progressed; died without progressing. Death without progression climbs to percent by twenty years. The cumulative incidence of progression reaches percent by twenty years. One minus Kaplan-Meier says percent by twenty and by thirty: double, and more. This net-risk construction removes competing deaths from the risk set instead of counting them as outcomes that preclude progression.
In the World's cohort, where deaths from other causes compete with cardiovascular death, the truth is known. Fifteen-year cardiovascular mortality is percent. Aalen-Johansen recovers it. One minus Kaplan-Meier overstates it, by less than for MGUS, because here the competing hazard is smaller; the bias grows with it.
Two regressions answer two questions. A cause-specific Cox model treats the other causes as censoring, and asks whether a covariate changes the rate of this event among people still alive: an association among those still event-free, not by itself a causal statement about mechanism. Jason Fine and Robert Gray's model of 1999 puts proportional hazards on the subdistribution, keeping those who died of other causes in the risk set with weights, and asks whether the covariate changes the chance that the event actually happens: a question about prognosis. They can disagree, and both can be right.
In the MGUS data, each decade of age at diagnosis multiplies the death rate by . Its cause-specific effect on progression is : among the living, older patients progress at least as fast. But the Fine-Gray hazard ratio is : older patients are less likely ever to progress, because death comes first. The cause-specific coefficient describes the observed event rate; the subdistribution coefficient concerns cumulative incidence and is not an ordinary risk ratio. Neither establishes biology or causation. The second can help with what to tell a patient.
Numbers: 10% vs 21%
14FrailtyMaster's3 min
James Vaupel, Kenneth Manton and Eric Stallard gave the idea a name in 1979: frailty, an unmeasured factor that multiplies each person's hazard. With a gamma frailty of mean one and variance theta, the population's survival is the average of individual survivals, which has a closed form. The population's hazard is the individual baseline times the mean frailty of the survivors, and that mean falls as the frail die. So population hazards bend below the baseline even when nobody's own hazard does: selection, not a change in anyone.
The World's cardiovascular hazard from sixty. For any one person it follows Gompertz's straight line. For the surviving population, with the World's frailty variance of point six, it bends further and further below the line, as the frail are removed. The slowing of death rates at the very oldest ages, seen in human and insect populations, is consistent with this mechanism, although frailty is not the only possible explanation. And chapter ten's drifting hazard ratio was the same selection at work inside a trial.
When frailty is shared, by members of a family, by the two kidneys of a patient, by the repeated infections of one person, it makes their times dependent. With a gamma frailty, it integrates out of each cluster's likelihood in closed form. Its variance theta measures the dependence: David Clayton's model of 1978, whose Kendall's tau is theta over theta plus two. The coefficients are now conditional on the frailty, Part twenty-five's random effects for lifetimes, and can differ from population-averaged associations; there is no universal coefficient ordering under arbitrary covariates or misspecification.
Christine McGilchrist and Chris Aisbett's data: thirty-eight dialysis patients, each with two times to an infection at the catheter site. Ignoring the pairing, women's hazard of infection is about of men's, and a Weibull model agrees. With a shared gamma frailty, theta is , and the female hazard ratio, now conditional on the latent patient frailty, is . The likelihood ratio test of no frailty gives ; because theta equal zero is on the boundary, the usual asymptotic reference is a half point mass at zero and half a chi-squared-one distribution; with only thirty-eight clusters this is an approximation, the boundary problem of variance components once more.
Events that can happen again, infections, admissions, recurrences of a tumour, need the same care. The Andersen-Gill model treats each person's events as one counting process and corrects the standard errors with a sandwich. Other models stratify by the event's number, or model each event's time marginally. A person-level frailty models the dependence instead of merely correcting for it.
Numbers: θ̂ = 0.50
15PredictionMaster's4 min
To judge a prognostic model, compare pairs of patients where we know who failed first: the shorter time must be an event. Frank Harrell's concordance is the share of such pairs in which the model gave the earlier failure the higher risk. One half is a coin, one is a perfect ranking: Part nineteen's area under the ROC curve, for lifetimes. But it only judges the ranking, it depends on the censoring pattern, and it cannot see whether the predicted probabilities are right.
The Brier score measures calibration and discrimination together: the mean squared error of the predicted probability of surviving past t. Patients censored before t have no outcome, so the others are weighted up by the inverse probability of remaining uncensored, estimated by Kaplan-Meier applied to the censoring times. It is Part eighteen's Horvitz-Thompson weighting: the weights require adequate censoring support. A pooled censoring KM assumes the relevant unconditional independence; censoring that depends on predictors needs suitable conditional weights.
All four hundred and sixteen PBC patients with complete data, split into a training two thirds and a test third. With no model, the concordance is one half by definition, and the five-year Brier score is . Bilirubin alone ranks patients with a concordance of . The Mayo Cox model reaches on new patients, and cuts the Brier score to . A random survival forest, a hundred and fifty trees split by log-rank statistics, does a little worse on this one seeded split: with five well-chosen variables and a few hundred patients, the old model is hard to beat.
The Brier score over time, on the test patients. Without covariates it climbs toward one quarter, the score of a coin, as survival approaches one half. The Cox model stays well below it at every horizon, and the forest stays a little above Cox.
Hemant Ishwaran's random survival forests grow trees whose splits maximize a log-rank statistic. Each leaf holds a Nelson-Aalen curve, and the forest averages them. Others boost Cox's partial likelihood, or fit hazards with neural networks. They can help when there are many variables, real interactions, and enough events to learn them; with a few strong predictors, as in PBC, a well-specified Cox model is hard to improve on.
Part thirty-four's conformal prediction can be carried over. The goal is a lower bound on a new patient's lifetime with ninety percent marginal coverage under exchangeability, a predictor trained separately, and the required censoring assumptions; it is not a conditional guarantee for every patient. The difficulty is that censoring hides the calibration patients' lifetimes. Emmanuel Candès, Lihua Lei and Zhimei Ren's answer: pick a threshold c nought, use only calibration patients whose censoring time exceeds it, for whom the lifetime capped at c nought is seen, and weight them by the inverse chance of being so lucky. The demonstration has known censoring times, even for early failures, and censoring independent of covariates and lifetimes, so weights are constant. With known correct censoring weights the model can be arbitrary; estimated weights do not generally give exact finite-sample coverage. Then calibrate its quantile as in split conformal.
Numbers: C = 0.828; Brier 0.133
Recap, problems, and the road aheadAll tracks3 min
Part forty in twelve lines. Twelve patients still in remission made the average remission impossible to compute naively. The survival function, the hazard and the cumulative hazard are three faces of one distribution, and Gompertz's law gives the shape of adult mortality. Censoring and truncation must be handled, never ignored. Kaplan and Meier multiply conditional survivals over the risk sets, and Greenwood's formula gives their variance; use the log-log interval when the risk set is small. Nelson and Aalen sum the hazard instead. Counting processes make every estimator observed minus expected, a martingale. The log-rank test sums observed minus expected over the event times. Cox's partial likelihood removes the baseline hazard, and gave medicine the Mayo model. Schoenfeld residuals check proportional hazards, and showed the Karnofsky effect fading. Hazard ratios select their survivors, so report restricted means, and never let future treatment classify the past. And accelerated failure time models, competing risks, frailty and honest prediction complete the toolkit.
A promise for later. This part handled lifetimes we see only in part. Everything rested on one untestable assumption: that censoring is independent of the lifetime, given the covariates. Part forty-one takes up missing data in general, where that assumption has a name, missing at random, and the tools are weighting, imputation and sensitivity analysis.
Where it comes back. Part forty-one treats censoring as one kind of missing data, and its weights as inverse probability weights. Part forty-four proves the martingale theory behind every estimator here. Part forty-eight studies the Kaplan-Meier curve as a random function. Part forty-nine shows why Cox's estimator is efficient in a semiparametric model. And Part fifty-eight monitors survival trials as the data accumulate.
Six problems, with full solutions in the README. Kaplan-Meier without censoring; the exponential rate under censoring; Cox's score test as the log-rank test; the Weibull as both a proportional hazards and an accelerated failure time model; the gamma frailty's population hazard; and the restricted mean as an area. Pause here if you want to try them.
The books this part follows: Kalbfleisch and Prentice; Fleming and Harrington on counting processes; Therneau and Grambsch on extending Cox's model; and Aalen, Borgan and Gjessing on event history analysis; with the papers from Greenwood to conformal survival.
Forty parts of sixty-five. A censored time is not a missing value but a partial one, and the risk set is how to use it. Next, data that are missing for reasons that may matter: Part forty-one, what you didn't see.
Where it goes next. Censoring is one kind of missing data, and its weights return in Part 41; Part 44 builds the martingales and Rebolledo's central limit theorem, Part 48 treats the Kaplan-Meier curve as an empirical process, Part 49 shows Cox's estimator is semiparametrically efficient, and Part 58 monitors survival trials as they accumulate.
Key results
The part's results in one place, for revision.
Try it
Lab 40 · Kaplan-Meier against the two easy mistakes
Simulate 1,000 studies of 100 exponential lifetimes (mean 10) with independent uniform censoring, and estimate S(8) by Kaplan-Meier, by dropping the censored, and by counting the censored as deaths; then compare Greenwood's standard error with the spread of the Kaplan-Meier estimates and check the log-log interval.
python -m videos.stats.labs 40
needs numpy, scipy, matplotlib · download lab40.py ·
source on GitHubtrue S(8) 0.449
Kaplan-Meier, mean of 1,000 0.446
censored dropped 0.248
censored counted as deaths 0.303
sd of the KM estimates 0.0562 (mean Greenwood SE 0.0550)
95% log-log interval covers 94.3%
share censored 37%
A censored patient is known to have survived up to the censoring time: Kaplan-Meier uses exactly that and is unbiased, while both shortcuts throw it away and are biased downward.
The code (76 lines; it asserts its own result)
"""Lab 40: estimate a survival probability from censored lifetimes three ways, and check Greenwood's variance."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.kit import survival
TITLE = "Kaplan-Meier against the two easy mistakes"
GOAL = ("Simulate 1,000 studies of 100 exponential lifetimes (mean 10) with independent uniform censoring, and estimate "
"S(8) by Kaplan-Meier, by dropping the censored, and by counting the censored as deaths; then compare "
"Greenwood's standard error with the spread of the Kaplan-Meier estimates and check the log-log interval.")
TASKS = [
"Shorten follow-up (censoring uniform on 0 to 12). Which estimator moves, and what happens to Greenwood's SE?",
"Make censoring informative: censor the frailest early (c = 0.5 * t for half of those with t < 5). Does Kaplan-Meier survive?",
"Set n = 20 and compare the coverage of the plain interval (km['plain']) with the log-log interval at S(12).",
]
def run(seed=0):
rng = np.random.default_rng(seed)
n, reps, mean, cmax, t0 = 100, 1000, 10.0, 25.0, 8.0
truth = float(np.exp(-t0 / mean))
km_hat, se_hat, dropped, as_deaths, covered = (np.empty(reps) for _ in range(5))
for r in range(reps):
t, c = rng.exponential(mean, n), rng.uniform(0, cmax, n)
time, event = np.minimum(t, c), t <= c
km = survival.kaplan_meier(time, event)
km_hat[r] = survival.km_at(km, t0)
se_hat[r] = survival.step_at(t0, km["t"], km["se"], left=0.0)
lo = survival.step_at(t0, km["t"], km["loglog"][0], left=1.0)
hi = survival.step_at(t0, km["t"], km["loglog"][1], left=1.0)
covered[r] = lo <= truth <= hi
dropped[r] = np.mean(time[event] > t0) # only the patients whose death was seen
as_deaths[r] = np.mean(time > t0) # a censored patient is counted as dead at the censoring time
censored = (mean / cmax) * (1 - np.exp(-cmax / mean)) # P(C < T) = E exp(-C / mean) for these laws
lab = labs.Lab()
lab.row("true S(8)", f"{truth:.3f}")
lab.row("Kaplan-Meier, mean of 1,000", f"{km_hat.mean():.3f}")
lab.row("censored dropped", f"{dropped.mean():.3f}")
lab.row("censored counted as deaths", f"{as_deaths.mean():.3f}")
lab.row("sd of the KM estimates", f"{km_hat.std(ddof=1):.4f} (mean Greenwood SE {se_hat.mean():.4f})")
lab.row("95% log-log interval covers", f"{covered.mean():.1%}")
lab.row("share censored", f"{censored:.0%}")
lab.note = ("A censored patient is known to have survived up to the censoring time: Kaplan-Meier uses exactly that "
"and is unbiased, while both shortcuts throw it away and are biased downward.")
assert abs(km_hat.mean() - truth) < 0.008, "Kaplan-Meier is (nearly) unbiased under independent censoring"
assert dropped.mean() < truth - 0.10 and as_deaths.mean() < truth - 0.08, "both shortcuts are biased downward"
assert abs(se_hat.mean() / km_hat.std(ddof=1) - 1) < 0.08, "Greenwood's SE matches the spread"
assert abs(covered.mean() - 0.95) < 0.025, "the log-log interval covers"
# one study for the picture
t, c = rng.exponential(mean, n), rng.uniform(0, cmax, n)
time, event = np.minimum(t, c), t <= c
km = survival.kaplan_meier(time, event)
grid = np.linspace(0, 20, 400)
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].fill_between(grid, survival.step_at(grid, km["t"], km["loglog"][0]), survival.step_at(grid, km["t"], km["loglog"][1]),
step="post", color=labs.GOLD, alpha=0.2, label="95% log-log band")
ax[0].step(grid, survival.km_at(km, grid), where="post", color=labs.GOLD, label="Kaplan-Meier")
ax[0].plot(grid, np.exp(-grid / mean), color=labs.MUTED, ls="--", label="truth")
ax[0].step(grid, [np.mean(time[event] > g) for g in grid], where="post", color=labs.RED, lw=1.3, label="censored dropped")
ax[0].step(grid, [np.mean(time > g) for g in grid], where="post", color=labs.ORANGE, lw=1.3, label="censored as deaths")
cens = time[~event]
ax[0].plot(cens[cens < 20], survival.km_at(km, cens[cens < 20]), "|", color=labs.GOLD, ms=7)
ax[0].set(title="One study of 100 patients (ticks: censored)", xlabel="time", ylabel="estimated S(t)", xlim=(0, 20), ylim=(0, 1.02))
ax[0].legend()
bins = np.arange(0.095, 0.66, 0.02) # two percentage points wide, centred on multiples of 1/n
for x, color, name in ((km_hat, labs.GOLD, "Kaplan-Meier"), (dropped, labs.RED, "censored dropped"),
(as_deaths, labs.ORANGE, "censored as deaths")):
ax[1].hist(x, bins=bins, color=color, alpha=0.6, label=name)
ax[1].axvline(truth, color=labs.INK, ls="--", lw=1.2, label=f"true S(8) = {truth:.3f}")
ax[1].set(title="Estimates of S(8) over 1,000 studies", xlabel="estimate", ylabel="studies")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Shorten follow-up (censoring uniform on 0 to 12). Which estimator moves, and what happens to Greenwood's SE?
- Make censoring informative: censor the frailest early (c = 0.5 * t for half of those with t < 5). Does Kaplan-Meier survive?
- Set n = 20 and compare the coverage of the plain interval (km['plain']) with the log-log interval at S(12).
Problems, with solutions
Try each problem before opening its solution.
-
KM without censoring. With no censoring, show the Kaplan–Meier estimate is the empirical survival function \(\#\{T_i > t\}/n\).
Solution
With no censoring, n_{k+1} = n_k − d_k, so each factor is n_{k+1}/n_k and the product telescopes to (n − Σ_{t_k ≤ t} d_k)/n = #{T_i > t}/n.
-
The censored exponential. Exponential lifetimes, right censoring: show \(\hat\lambda = d / \sum_i x_i\) and \(\text{Var}(\hat\lambda) \approx \lambda^2 / d\).
Solution
The log-likelihood is Σ δ_i log λ − λ Σ x_i = d log λ − λ Σ x_i. Setting the score to zero gives λ̂ = d/Σx_i. The information is d/λ², so Var(λ̂) ≈ λ²/d: precision comes from events, not people.
-
Cox's score is log-rank. Two groups, no ties: show Cox's score at \(\beta = 0\) is \(\sum_k (d_{1k} - n_{1k}/n_k)\), the log-rank O \(-\) E.
Solution
For one binary covariate at β = 0, x̄(t_k) = n_{1k}/n_k. So U(0) = Σ_k (x_{(k)} − n_{1k}/n_k) = Σ_k (d_{1k} − E_{1k}) when each d_k = 1. The information at 0 is Σ (n_{1k}/n_k)(1 − n_{1k}/n_k), the log-rank variance without ties.
-
Weibull is PH and AFT. Weibull: show \(\log T = x^\top\gamma + \sigma W\) has proportional hazards with \(\beta = -\gamma/\sigma\).
Solution
With W extreme-value, S(t | x) = exp(−e^{(log t − x'γ)/σ}) = exp(−t^{1/σ} e^{−x'γ/σ}). That is a Weibull with shape k = 1/σ, and the hazard k t^{k−1} e^{−x'γ/σ} is proportional in x with β = −γ/σ.
-
The gamma frailty's population hazard. Gamma frailty: show the population hazard is \(h_0(t)/(1 + \theta H_0(t))\).
Solution
S(t) = E e^{−Z H_0} = (1 + θ H_0)^{−1/θ}, the gamma Laplace transform. Then h_pop = −d log S/dt = h_0/(1 + θH_0). This equals E[Z | T > t] h_0, since the survivors' frailty is Gamma(1/θ, θ/(1 + θH_0)).
-
RMST. Show \(E \min(T, \tau) = \int_0^\tau S(t)\, dt\).
Solution
min(T, τ) = ∫_0^τ 1{T > t} dt. Take expectations and swap the order (Fubini): E min(T, τ) = ∫_0^τ S(t) dt.
Notes and sources
Where it comes back
- Part 41: censoring as one kind of missing data; inverse probability weights.
- Part 44: martingales, counting processes and Rebolledo's central limit theorem.
- Part 48: the Kaplan–Meier curve as an empirical process.
- Part 49: Cox's estimator as a semiparametric efficient estimator.
- Part 58: monitoring survival trials as they accumulate.
Glossary
- Survival function; hazard; cumulative hazard: P(T > t); the event rate among those at risk; its integral, −log S.
- Right, left and interval censoring; truncation; delayed entry: partial knowledge of T; not being seen at all unless T exceeds the entry time.
- Risk set: those still under observation and event-free just before t.
- Kaplan–Meier; Greenwood; log-log interval: the product-limit estimator; its variance; the interval on log(−log S).
- Nelson–Aalen; life table: the summed hazard; grouped-interval estimation.
- Counting process; compensator; martingale: N(t); the expected count ∫ Y h; their difference.
- Log-rank test; weighted log-rank: summed observed-minus-expected over risk sets; with weights.
- Proportional hazards; partial likelihood; Breslow and Efron ties; Breslow's baseline: Cox's model and its pieces.
- Schoenfeld residuals; Grambsch–Therneau test; time-varying coefficient; stratification: checking and relaxing PH.
- RMST: the area under S up to τ.
- Immortal time; landmark analysis; target trial: time in which the outcome could not occur; fixes.
- AFT model; time ratio; cure fraction: regression for log T; e^γ; the plateau.
- Competing risks; cause-specific hazard; cumulative incidence; Aalen–Johansen; Fine–Gray: other events that prevent the one of interest, and their tools.
- Frailty; shared frailty; recurrent events: unmeasured multiplicative risk; shared by a cluster; repeated events.
- Concordance; IPCW Brier score; random survival forest; conformal lower bound: prediction and its evaluation.
Sources
- Foundations.
- J. Graunt (1662); E. Halley, Phil. Trans. 17 (1693); B. Gompertz, Phil. Trans. 115 (1825); W. Weibull, J. Appl. Mech. 18 (1951).
- M. Greenwood, Reports on Public Health and Medical Subjects 33 (1926); E. Kaplan & P. Meier, JASA 53 (1958); S. Cutler & F. Ederer, J. Chronic Dis. 8 (1958).
- B. Efron, Proc. 5th Berkeley Symp. 4 (1967); W. Nelson, J. Qual. Technol. 1 (1969); O. Aalen, Ann. Stat. 6 (1978).
- W. J. Hall & J. Wellner, Biometrika 67 (1980); R. Brookmeyer & J. Crowley, Biometrics 38 (1982).
- Trials and data.
- E. Freireich et al., Blood 21 (1963); E. Gehan, Biometrika 52 (1965).
- E. R. Dickson et al., Hepatology 10 (1989); T. Fleming & D. Harrington (1991).
- J. Crowley & M. Hu, JASA 72 (1977); J. Kalbfleisch & R. Prentice (1980, 2002).
- R. Kyle et al., NEJM 346 (2002); C. McGilchrist & C. Aisbett, Biometrics 47 (1991).
- Tests and Cox.
- N. Mantel, Cancer Chemother. Rep. 50 (1966); R. Peto & J. Peto, JRSS A 135 (1972).
- D. Cox, JRSS B 34 (1972), Biometrika 62 (1975); N. Breslow, Biometrics 30 (1974); B. Efron, JASA 72 (1977).
- P. Andersen & R. Gill, Ann. Stat. 10 (1982); R. Rebolledo, Z. Wahrsch. 51 (1980).
- D. Schoenfeld, Biometrika 69 (1982); P. Grambsch & T. Therneau, Biometrika 81 (1994).
- Interpretation.
- M. Hernán, Epidemiology 21 (2010); J. O. Irwin, J. Hyg. 47 (1949); P. Royston & M. Parmar, BMC Med. Res. Methodol. 13 (2013).
- D. Redelmeier & S. Singh, Ann. Intern. Med. 134 (2001); M.-P. Sylvestre, E. Huszti & J. Hanley, Ann. Intern. Med. 145 (2006).
- S. Suissa, Am. J. Epidemiol. 167 (2008); J. Anderson, K. Cain & R. Gelber, J. Clin. Oncol. 1 (1983); M. Hernán & J. Robins, Am. J. Epidemiol. 183 (2016).
- Competing risks and frailty.
- O. Aalen & S. Johansen, Scand. J. Stat. 5 (1978); J. Fine & R. Gray, JASA 94 (1999).
- J. Vaupel, K. Manton & E. Stallard, Demography 16 (1979); D. Clayton, Biometrika 65 (1978).
- J. Boag, JRSS B 11 (1949); J. Berkson & R. Gage, JASA 47 (1952).
- Prediction.
- F. Harrell et al., JAMA 247 (1982); E. Graf et al., Stat. Med. 18 (1999); H. Uno et al., Stat. Med. 30 (2011).
- H. Ishwaran et al., Ann. Appl. Stat. 2 (2008); E. Candès, L. Lei & Z. Ren, JRSS B 85 (2023).
- Books. Kalbfleisch & Prentice (2002); Fleming & Harrington (1991); Therneau & Grambsch (2000); Aalen, Borgan & Gjessing (2008).
About this partfrom its README
Part 40 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the twentieth part of Stage III, Master's. A leukaemia trial ends with twelve of twenty-one patients still in remission: how long does remission last? This part builds survival analysis from the risk set up:
- the survival function, the hazard and the cumulative hazard; censoring and truncation;
- Kaplan–Meier, Greenwood's variance and its intervals, Nelson–Aalen, the life table;
- counting processes and martingales;
- the log-rank test and Cox's partial likelihood, and how to check it;
- what hazard ratios mean, the restricted mean, and immortal time;
- parametric and AFT models, cure fractions, competing risks, frailty;
- prediction, with concordance, the IPCW Brier score, a survival forest and conformal lower bounds.
The part builds statkit.survival and an instrument, the Kaplan–Meier staircase (KMStaircase): the step function
drawn from the risk table, censoring ticks, a row of patients in time order, the drop at each event time labelled with
n and d, and shaded pointwise bands. Its real data, all from R's survival package (LGPL ≥ 2) except Gehan's table:
- Freireich et al.'s (1963) 6-MP trial, as tabulated by Gehan (1965);
- the Mayo Clinic PBC trial, 1974–84 (Fleming & Harrington 1991);
- the Stanford heart transplant programme, 1967–74 (Crowley & Hu 1977);
- the VA lung cancer trial (Kalbfleisch & Prentice 1980);
- the Mayo Clinic MGUS cohort (Kyle et al. 2002);
- McGilchrist & Aisbett's (1991) kidney catheter infections.
It opens with the 6-MP trial. On placebo all 21 relapsed; on 6-MP 9 did and 12 were censored. Averaging the 6-MP times as if all had relapsed gives 17.1 weeks; averaging only the relapses gives 12.1.
From there the part covers:
- Lifetimes. S, h, H and S = e^{−H}; Graunt (1662) and Halley (1693); Gompertz (1825), with the World's hazards doubling about every 8 years; a model man recruited at 60, with SBP 130 and BMI 27 and frailty integrated at recruitment, has a median of 18.6 more years; Weibull and bathtub hazards.
- Censoring and truncation.
- The four kinds; independent censoring and the likelihood.
- The World's cohort: 4,000 adults aged 40–79 followed 15 years; 1,086 deaths, 1,702 alive at the end, 1,212 lost.
- Ten-year survival: truth 0.786, KM 0.786; censored counted as deaths 0.590; censored dropped 0.320; censored as alive 0.815.
- A separate age-40 simulation draws independent scheduled entry ages and observes only survivors to entry. Reference median age at death is 78.3, delayed-entry KM is 78.7, and ignoring entry gives 82.1. Covariate triples preserve their joint empirical distribution; frailty is drawn at 40 and selected by survival, rather than reset at recruitment.
- Kaplan–Meier. The product-limit estimator; the staircase for 6-MP (week 6: n = 21, d = 3; week 7: n = 17); the curve ends at 0.448. Efron's redistribute-to-the-right. Medians 23 weeks (95% CI from 13 to beyond the data) and 8 (4–11).
- Greenwood. Greenwood (1926); plain, log and log-log bands; Hall–Wellner's simultaneous band.
- Nelson–Aalen. The cumulative hazard; placebo's slope is about 0.15 a week, 6-MP's a fifth of it. The life table (Cutler & Ederer 1958); log H against log t as a diagnostic.
- Counting processes. N, Y, Λ and M = N − Λ. Over 4,000 seeded paths M(1) has mean −0.01 and variance 26.0, against EΛ(1) = 26.3. Every estimator here is an integral against dM (Aalen 1978; Andersen & Gill 1982).
- The unstratified log-rank test. On Gehan's data the 6-MP arm had 9 relapses against 19.3 expected: χ² = 16.8, p = 4.2 × 10⁻⁵. Gehan's weighted version gives 13.5; Fleming–Harrington weights.
- Cox.
- The partial likelihood, derived; Breslow and Efron ties.
- Gehan's data: HR 4.82 (2.15–10.81) by Efron, 4.52 by Breslow.
- The Mayo model on 312 patients with 125 deaths. HRs: age per decade 1.39, edema 2.19, log bilirubin 2.41, log albumin 0.05, log prothrombin time 20.4. Doubling bilirubin multiplies the hazard by 1.84.
- D-penicillamine against placebo: HR 1.06 (0.75–1.50), log-rank p = 0.75.
- Checking Cox. Schoenfeld residuals and an approximate KM-transformed scaled-residual diagnostic, motivated by Grambsch–Therneau. The teaching implementation uses a simplified constant covariance and Breslow risk-set residuals; its p-values are not exact reproductions of software’s tie-adjusted test.
- VA trial: Karnofsky HR 0.71 per 10 points, approximate diagnostic p = 0.001. Split at 90 days, the HR is 0.61 early and 1.01 late.
- The Mayo diagnostics give p ≥ 0.055. This does not establish proportional hazards; test power depends on the departure and event information.
- What hazard ratios mean.
- A seeded trial in which every patient's HR is 0.5, with a gamma frailty: the empirical period incidence-rate ratios are 0.52, 0.67, 0.67 and 0.76, and Cox's HR on a fixed one-in-twenty subsample (1,000 patients) is 0.58 (Hernán 2010).
- RMST to 35 weeks on Gehan's data: 23.3 against 8.7, a gain of 14.6 weeks (paired-bootstrap 95% percentile interval 8.0–21.3; 3,999 resamples of the original 21 pairs). The curve is carried flat to 35 weeks in each resample; this tail convention and the small trial limit precision.
- Immortal time.
- The Oscar winners (Redelmeier & Singh 2001; Sylvestre et al. 2006).
- Stanford: 103 patients, 69 transplanted after a median 25 days, 30 died waiting. Ever-transplanted HR 0.27 (0.17–0.43); transplant as time-varying 1.13 (0.63–2.04); adjusted for age 0.99.
- The World's useless statin: ever-users 0.77 (0.67–0.90); time-varying 1.41 (confounding by indication); adjusted 1.00 (0.86–1.17).
- Suissa (2008); target trials.
- Parametric models.
- AFT models; Weibull as PH and AFT.
- VA trial: the time ratio per 10 Karnofsky points is 1.42–1.50 across four models. Weibull σ = 1.02 and implied HR 0.71, as Cox. Log-logistic has the best AIC (1,448.3).
- Cure models: the 6-MP plateau.
- Competing risks.
- Cause-specific hazards; Aalen–Johansen.
- MGUS, 1,384 patients, median age 72: 115 progressions, 860 deaths first. Progression by 20 years: 10.0% by Aalen–Johansen against 21.0% by 1 − KM; by 30 years 13.4% against 42.5%.
- The World's cardiovascular deaths by 15 years: truth 14.9%, AJ 15.4%, 1 − KM 16.9%.
- Per decade of age: death HR 1.91; progression cause-specific 1.14; Fine–Gray 0.84.
- Frailty.
- Vaupel, Manton & Stallard; the World's population hazard bending below Gompertz.
- Shared gamma frailty (Clayton). Kidney infections: θ̂ = 0.50. The female HR is 0.43 by Cox, 0.41 by Weibull and 0.15 conditional on the frailty. LR for θ = 0 is 8.6 (boundary p = 0.002).
- Recurrent events.
- Prediction. PBC, 416 patients, a third held out in one seeded split; this comparison does not establish a universal model ranking.
- Concordance: bilirubin alone 0.773, Cox 0.828 (0.838 on its training data), a random survival forest 0.804.
- Five-year IPCW Brier: no model 0.218, Cox 0.133, forest 0.148.
- Conformal lower bounds under censoring (Candès, Lei & Ren 2023).
Data:
- Gehan, PBC, Stanford, VA, MGUS and kidney are the Museum's;
- the cohort is the World's;
- the rest are seeded simulations.
Built in this part:
statkit.survival(explainer/stats/kit/survival.py), checked against statsmodels (SurvfuncRight,survdiff,PHReg) and closed forms intests/test_stats_kit_survival.py:- Survival and hazard: risk tables with delayed entry and weights; Kaplan–Meier with Greenwood and plain, log and log-log intervals; medians and Brookmeyer–Crowley intervals; redistribute-to-the-right; Nelson–Aalen; RMST with its variance.
- Tests and Cox: log-rank, Gehan–Breslow and Fleming–Harrington tests. Cox by Newton with Breslow or Efron ties, start-stop rows and weights, with Breslow's baseline. Schoenfeld residuals and an approximate KM-transform trend diagnostic; see its limitations above.
- Parametric: exponential, Weibull, log-normal and log-logistic AFT models.
- Competing risks and frailty: Aalen–Johansen; Fine–Gray with IPCW weights; the shared gamma frailty Weibull.
- Prediction: Harrell's C; the IPCW Brier score; a random survival forest with log-rank splits; conformal lower prediction bounds under censoring.
- The World gains its
cohortblock. Gompertz hazards for cardiovascular and other death; a gamma frailty on the first; loss to follow-up; 15 years of administrative censoring; a statin with no effect. - The Museum gains
gehan(),pbc(),stanford_heart(),mgus2(),veteran()andkidney(). - The Kaplan–Meier staircase (
KMStaircaseinexplainer/stats/viz.py).
The Coverage Board gains seven rows:
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| S(t) from the known fates only (censored dropped) | exponential lifetimes, uniform censoring, n = 200 | 69.8% | broken |
| KM 90% CI, plain Greenwood | exponential lifetimes, n = 20, S(t) = 0.30 | 87.0% | broken |
| KM 90% CI, log-log | same | 90.8% | kept |
| Cox Wald 90% CI for β | exponential, n = 60, about 33% censored | 89.8% | kept |
| Cox CI, ever-treated (immortal time) | a null treatment started during follow-up, n = 400 | 0.0% | broken |
| Cox CI, treatment as time-varying | same | 91.2% | kept |
| conformal lower bound for T (90%) | Weibull lifetimes, exponential censoring, a wrong q(x) | 90.2% | kept |
Scientific conditions and implementation scope:
- Hazard-density identities and the Gaussian-process limits use the stated continuous-lifetime and regularity assumptions. Greenwood intervals are approximate and pointwise; the plotted plain interval is clipped to [0,1]. Simultaneous critical values depend on the chosen band and time interval. Orthogonal martingale increments justify the variance calculation, rather than independent nonlinear KM factors.
- Unadjusted KM needs independent censoring in the pooled population; independence only conditional on covariates does not by itself suffice. Delayed entry additionally needs independent truncation (or suitable adjustment). Nelson–Aalen is unbiased for a stopped cumulative-hazard target while the risk set is nonempty, not unrestricted H after everyone leaves.
- The displayed trial log-rank and Cox calculations are unstratified teaching analyses, without incorporating matched-pair strata. Restricted-mean uncertainty resamples the original pairs. Prognostic coefficients, including bilirubin and age associations, are not causal intervention effects. Censoring liver transplants requires the relevant independent-censoring assumptions.
- Failure to detect D-penicillamine or transplant benefit does not establish no benefit. Time-varying treatment removes immortal-time classification but does not itself remove treatment confounding. Stanford zero-duration intervals use a stated half-day convention; the simulated statin’s exact null is known from its generator, not proved by an adjusted Cox estimate near one.
- Treating competing events as removed from risk sets identifies cause-specific hazards without independent latent failure times. The resulting net-risk 1−KM is not automatically a causal risk under elimination of other causes. Fine–Gray ratios describe subdistribution hazards, not ordinary risk ratios. Its displayed intervals use standard errors from 399 patient bootstrap fits, including refitting censoring KM; they are approximate, with bootstrap Monte Carlo variation, rather than inverse conditional-information intervals.
- Gamma frailty has shape 1/theta and scale theta. Integrated shared-frailty likelihoods use hazards before multiplying by the latent frailty. Conditional coefficients need not have a universal size ordering relative to marginal coefficients. The boundary likelihood-ratio reference is asymptotic, particularly approximate with 38 clusters.
- A finite plateau alone cannot distinguish a cure fraction from an unseen long tail. Weibull’s joint AFT/PH characterization assumes regular nondegenerate continuous common-scale models.
- The pooled IPCW Brier evaluation requires unconditional independent censoring and positive censoring support; covariate-dependent censoring needs conditional weights. Deaths use G(T−), survivors use right-continuous G(t). The score reduces to ordinary binary MSE without censoring.
- The conformal demonstration knows censoring times even for early failures, and censoring is independent of covariates and lifetimes. Separately trained predictors, exchangeability and correct censoring weights are needed; estimated weights do not generally give exact finite-sample guarantees. Coverage is marginal, not conditional for every patient. The Board averages 200 independent calibrations, each evaluated on 400 new lifetimes; its Monte Carlo SE is 0.171 percentage points across calibrations, not based on a fabricated independent-prediction count.
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | The 6-MP trial | 12 of 21 censored |
| 1 | Lifetimes | median 18.6 years from 60 (specified covariates) |
| 2 | Censoring and truncation | 0.786 vs 0.590 / 0.320 / 0.815 |
| 3 | Kaplan–Meier | medians 23 vs 8 weeks |
| 4 | Greenwood's variance | plain 87.0% vs log-log 90.8% |
| 5 | Nelson–Aalen | slopes 0.15 vs 0.03 a week |
| 6 | Counting processes | Var M(1) = 26.0 ≈ EΛ = 26.3 |
| 7 | The log-rank test | χ² = 16.8 |
| 8 | Cox's partial likelihood | HR 4.82; the Mayo model |
| 9 | Checking Cox | Karnofsky 0.61 → 1.01 |
| 10 | What hazard ratios mean | 0.52 → 0.76; RMST +14.6 weeks |
| 11 | Immortal time | Stanford 0.27 → 1.13 |
| 12 | Parametric and AFT models | log-logistic AIC 1,448.3 |
| 13 | Competing risks | 10% vs 21% |
| 14 | Frailty | θ̂ = 0.50 |
| 15 | Prediction | C = 0.828; Brier 0.133 |
| 16 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Freireich et al. (1963); Gehan (1965).
- Lifetimes. S, h, H, S = e^{−H}; Graunt and Halley again; Gompertz.
- Censoring and truncation (Board).
- Kaplan–Meier (1958). Derived; the shrinking risk set (
KMStaircase); redistribute-to-the-right. - Greenwood (1926). Log-log intervals (Board).
- Nelson–Aalen.
- Counting processes. The compensator and martingale (Aalen 1978); the full theory in Part 44.
- The log-rank test. O − E over risk sets, derived.
- Cox (1972). The partial likelihood, derived; ties.
- Checking Cox. Schoenfeld residuals; time-varying coefficients.
- What hazard ratios mean (Hernán 2010); RMST.
- Immortal time (Suissa 2008); the Oscar winners.
- Parametric and AFT models.
- Competing risks. Fine–Gray; Aalen–Johansen.
- Frailty. Vaupel, Manton & Stallard (1979); recurrent events.
- Prediction. Concordance; IPCW Brier; survival forests; conformal survival.
- Outro.
Built: statkit.survival. Data: Freireich/Gehan.
Build the film
python -m videos.stats.stats40.compute # the part's numbers, into .cache/stats40
python tools/build.py stats40 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats40 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats40. 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.stats40.compute # once (a few minutes)
python tools/build.py stats40 -q l # fast 480p preview
python tools/build.py stats40 # 1080p30 -> renders/stats40.mp4
python tools/qa_scene.py stats40 KaplanMeier
python tools/lecture_length.py stats40 --floor 50