Applied Health Economics, RWE & HTA
Overview / Module 2 / Day 16
Module 2 · Biostatistics & econometrics · Day 16 of 100

Survey Data and Bootstrap Weights

Administrative data cover everyone with a health card but say nothing about whether people have a family doctor, how they rate their health, or whether they had a flu shot. Surveys do, for a sample. Statistics Canada's Canadian Community Health Survey (CCHS) is the main source in the corridor, and it ships with a final weight and bootstrap replicate weights. Today you estimate prevalence, differences and regressions from a CCHS-style file. You see why the naive standard error is too small, apply Statistics Canada's release rules, and check the bootstrap by running the whole survey 300 more times.

▶
Video for Day 16 coming soon

By the end of today you can

  • weight every population estimate with the final weight and get every SE from the bootstrap weights
  • explain a design effect and why clustering and unequal weights inflate the variance
  • apply the CV and minimum-count release rules and flag E and F estimates
  • fit weighted regressions with replicate-weight SEs, in Python and with R's survey package
  • name a bias that weighting does not fix (nonresponse related to the outcome)

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:35
16.1 The survey file and its weights
0:35–1:15
16.2 Weighted estimates and bootstrap standard errors
1:15–1:30
Break
1:30–2:10
16.3 Domains, differences and release flags
2:10–2:40
16.4 Truth check: run the survey 300 more times
2:40–2:55
Break
2:55–3:35
16.5 Regression with survey weights
3:35–3:50
16.6 The right weights, the wrong standard error
3:50–4:50
16.7 Mini-project: survey indicators for the burden-of-illness report
4:50–5:00
16.8 Save your work
5:00–5:30
Bloc français

In this lesson

16.1 The survey file and its weights (35 min)

cchs_2024.csv is a synthetic survey of Corridor Health adults in mid-2024. The design is shaped like the CCHS, simplified:

  1. Strata: the 11 health regions. Each gets the same sample size, so small regions (Laval, Outaouais) are heavily over-sampled.
  2. Clusters: in each region, 10 of 30 collection areas are drawn, then 45 adults in each. People in the same area are more alike than strangers (access to a doctor, for example).
  3. Nonresponse: older and higher-income people respond more; people in poor health respond less. 2,806 of 4,950 responded (57%).
  4. Weights: design weight × nonresponse adjustment (within region and age group) × calibration to the population by province, age group and sex. That is wts_m.
  5. Bootstrap weights: bsw1–bsw500 in cchs_2024_bootstrap.csv.gz. Each repeats the whole weighting on a resample of collection areas (the Rao–Wu rescaled bootstrap), so it carries the clustering, stratification and weighting into the variance.

Like the CCHS public file, the survey has no area codes and no link to the health card number. The bootstrap weights are the only route to correct standard errors.

def load():
    """Respondents and their bootstrap weights: (DataFrame, n x B array aligned with it)."""
    con = duckdb.connect()
    df = con.sql(f"SELECT * FROM read_csv('{SURVEY}') ORDER BY resp_id").df()
    bw = con.sql(f"SELECT * FROM read_csv('{BOOT}') ORDER BY resp_id").df()
    assert (bw.resp_id.to_numpy() == df.resp_id.to_numpy()).all()
    df["fair_or_poor_health"] = (df.self_rated_health >= 4).astype(int)
    return df, bw.drop(columns="resp_id").to_numpy()

def estimate(stat, df, w, reps):
    """Apply stat(df, weights) -> number with the final weight and every replicate weight."""
    theta = stat(df, w)
    boot = np.array([stat(df, reps[:, b]) for b in range(reps.shape[1])])
    se = float(np.sqrt(np.mean((boot - theta) ** 2)))
    return theta, se

def proportion(var, mask=None):
    """A stat for estimate(): the weighted share with var == 1 (optionally within a domain mask)."""
    def stat(df, w):
        m = np.ones(len(df), bool) if mask is None else np.asarray(mask)
        return float(np.sum(w[m] * df[var].to_numpy()[m]) / np.sum(w[m]))
    return stat
"""Day 16.1: what is in the survey file, and why every respondent has a different weight."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb  # noqa: E402

from corridor.db import DATA  # noqa: E402
from corridor.survey import load  # noqa: E402

df, reps = load()
print(f"{len(df):,} respondents, {reps.shape[1]} bootstrap weights; final weights sum to {df.wts_m.sum():,.0f} adults")
print(f"weights: min {df.wts_m.min():.1f}, median {df.wts_m.median():.1f}, max {df.wts_m.max():.1f}")
PERSONS = os.path.join(DATA, "persons.csv").replace("\\", "/")
pop = duckdb.sql(f"""SELECT region, count(*) AS adults FROM read_csv('{PERSONS}')
                     WHERE (death_date IS NULL OR death_date >= DATE '2024-07-01')
                       AND registry_start <= DATE '2024-07-01' GROUP BY 1""").df().set_index("region")
by = df.groupby("region").agg(respondents=("resp_id", "size"), weighted=("wts_m", "sum"), mean_weight=("wts_m", "mean"))
by = by.join(pop)
by["share of sample"] = by.respondents / by.respondents.sum()
by["share of adults"] = by.adults / by.adults.sum()
print(by.round(3).to_string())
ages = df.groupby("age_group").agg(n=("resp_id", "size"), w=("wts_m", "sum"))
print("\nAge structure: unweighted sample vs weighted (= population)")
print((ages / ages.sum()).round(3).rename(columns={"n": "sample", "w": "weighted"}).to_string())
2,806 respondents, 500 bootstrap weights; final weights sum to 248,765 adults
weights: min 9.2, median 88.4, max 226.3
        respondents   weighted  mean_weight  adults  share of sample  share of adults
region                                                                               
ON-CEN          278  46342.182      166.698   46263            0.099            0.186
ON-EST          250  40252.728      161.011   40188            0.089            0.162
ON-NTH          243   7705.113       31.708    7789            0.087            0.031
ON-TOR          260  32615.874      125.446   32556            0.093            0.131
ON-WST          253  27441.104      108.463   27561            0.090            0.111
QC-03           253   8386.033       33.146    8444            0.090            0.034
QC-06           249  22692.697       91.135   22796            0.089            0.092
QC-07           268   5043.690       18.820    4712            0.096            0.019
QC-13           258   4702.389       18.226    4717            0.092            0.019
QC-16           244  17040.647       69.839   16949            0.087            0.068
QC-OTH          250  36542.544      146.170   36790            0.089            0.148

Age structure: unweighted sample vs weighted (= population)
           sample  weighted
age_group                  
18-34       0.206     0.258
35-49       0.231     0.249
50-64       0.259     0.243
65-79       0.216     0.186
80+         0.088     0.063

Every region has about 250 respondents, but they stand for anything from 4,700 adults (Laval) to 46,000 (Central Ontario). The weights run from 9 to 226. Weighted, the age structure is the population's: the unweighted sample has too few young adults because they respond less. The regional totals are close to, not exactly, the population, because calibration is by province, age and sex, not by region.


16.2 Weighted estimates and bootstrap standard errors (40 min)

Every estimate is computed once with wts_m, then once with each of the 500 bootstrap weights. The variance is the average squared distance of the 500 replicate estimates from the main one:

Var^(θ^)=1B∑b=1B(θ^b−θ^)2\widehat{\text{Var}}(\hat\theta) = \frac{1}{B}\sum_{b=1}^{B} (\hat\theta_b - \hat\theta)^2
def estimate(stat, df, w, reps):
    """Apply stat(df, weights) -> number with the final weight and every replicate weight."""
    theta = stat(df, w)
    boot = np.array([stat(df, reps[:, b]) for b in range(reps.shape[1])])
    se = float(np.sqrt(np.mean((boot - theta) ** 2)))
    return theta, se
"""Day 16.2-16.3: weighted prevalence with bootstrap standard errors, and what ignoring the design costs."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.survey import estimate, flag, load, proportion, srs_se  # noqa: E402

df, reps = load()
w = df.wts_m.to_numpy()
ITEMS = ["diabetes", "high_blood_pressure", "regular_provider", "flu_shot_past_year", "fair_or_poor_health"]
print(f"{'item':<22}{'unweighted':>11}{'weighted':>9}{'boot SE':>9}{'95% CI':>17}{'CV %':>6}{'flag':>5}"
      f"{'naive SE':>9}{'design effect':>14}")
for v in ITEMS:
    est, se = estimate(proportion(v), df, w, reps)
    naive = srs_se(df, v, w)
    print(f"{v:<22}{df[v].mean():>11.3f}{est:>9.3f}{se:>9.4f}{est - 1.96 * se:>9.3f}-{est + 1.96 * se:.3f}"
          f"{100 * se / est:>6.1f}{flag(est, se, len(df)):>5}{naive:>9.4f}{(se / naive) ** 2:>14.2f}")
item                   unweighted weighted  boot SE           95% CI  CV % flag naive SE design effect
diabetes                    0.120    0.105   0.0072    0.091-0.119   6.8        0.0058          1.53
high_blood_pressure         0.283    0.251   0.0088    0.234-0.268   3.5        0.0082          1.15
regular_provider            0.686    0.683   0.0139    0.655-0.710   2.0        0.0088          2.51
flu_shot_past_year          0.310    0.278   0.0110    0.257-0.300   4.0        0.0085          1.70
fair_or_poor_health         0.133    0.124   0.0072    0.110-0.138   5.8        0.0062          1.35
  • Weights move the estimates. Unweighted, 28.3% report high blood pressure; weighted, 25.1%. The sample has too many older people (they respond more), and older people have more hypertension.
  • The design inflates the variance. The design effect is the ratio of the true variance to the simple-random-sample variance. It is 2.5 for having a regular provider: clustering matters most when the outcome depends on the area. Every design effect is above 1.
  • Every estimate here is releasable: the CVs are 2–7%.

16.3 Domains, differences and release flags (40 min)

A domain estimate (a province, an age group) uses the whole design and only the domain's respondents. A difference between domains is estimated in each replicate, so its SE accounts for both estimates coming from the same survey.

Statistics Canada's CCHS rules for releasing an estimate use its coefficient of variation (CV = SE / estimate):

CVFlagRelease
0–16.5%nonerelease
16.6–33.3%Erelease with a warning: use with caution
over 33.3%Fsuppress: too unreliable
fewer than 10 respondentsFsuppress
def flag(est, se, n):
    """Statistics Canada-style quality flag from the CV and the unweighted count."""
    if n < 10:
        return "F (n<10)"
    cv = se / est if est else np.inf
    return "" if cv <= 0.165 else ("E" if cv <= 0.333 else "F")
"""Day 16.4: estimates for subgroups (domains), a difference between provinces, and release flags."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402

from corridor.survey import estimate, load, table  # noqa: E402

df, reps = load()
w = df.wts_m.to_numpy()
print("Regular health care provider, by province")
print(table(df, w, reps, "regular_provider", "province").round(3).to_string(index=False))

def gap(d, wt):
    on, qc = (d.province == "ON").to_numpy(), (d.province == "QC").to_numpy()
    p = lambda m: np.sum(wt[m] * d.regular_provider.to_numpy()[m]) / np.sum(wt[m])  # noqa: E731
    return float(p(on) - p(qc))

est, se = estimate(gap, df, w, reps)
print(f"\nON minus QC: {est:.3f} (95% CI {est - 1.96 * se:.3f} to {est + 1.96 * se:.3f}); the difference is"
      f" estimated replicate by replicate, so its SE accounts for the shared design")

df["region_age"] = df.region + " " + df.age_group
t = table(df, w, reps, "fair_or_poor_health", "region_age")
print(f"\nFair or poor health by region x age group: {len(t)} cells; flags: "
      + ", ".join(f"{k or 'none'} {v}" for k, v in t.flag.value_counts().items()))
print(t[t.region_age.str.startswith("QC-07")].round(3).to_string(index=False))
Regular health care provider, by province
province    n  estimate    se  ci_low  ci_high    cv flag
      ON 1284     0.725 0.019   0.688    0.762 0.026     
      QC 1522     0.614 0.019   0.576    0.651 0.031     

ON minus QC: 0.111 (95% CI 0.059 to 0.163); the difference is estimated replicate by replicate, so its SE accounts for the shared design

Fair or poor health by region x age group: 55 cells; flags: F 30, E 23, none 2
 region_age  n  estimate    se  ci_low  ci_high    cv flag
QC-07 18-34 51     0.016 0.017  -0.018    0.049 1.110    F
QC-07 35-49 59     0.094 0.048  -0.000    0.188 0.511    F
QC-07 50-64 68     0.178 0.036   0.108    0.248 0.202    E
QC-07 65-79 60     0.232 0.059   0.116    0.348 0.256    E
  QC-07 80+ 30     0.346 0.095   0.160    0.533 0.274    E

72.5% of Ontario adults and 61.4% of Quebec adults have a regular provider: a gap of 11.1 points (95% CI 5.9 to 16.3). Quebec's lower attachment to a family physician is built into the generator, as in the real corridor.

Cross region by age group and most cells become unreliable: 30 of 55 must be suppressed (F) and 23 need an E flag. A survey designed for regional estimates cannot answer every regional subgroup question. Report what the design supports, or pool years.

Try it (10 min). Estimate fair or poor self-rated health by income quintile, with CIs and flags.

Solution
"""Day 16 try it: fair or poor self-rated health by income quintile, with flags."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.survey import load, table  # noqa: E402

df, reps = load()
print(table(df, df.wts_m.to_numpy(), reps, "fair_or_poor_health", "income_quintile").round(3).to_string(index=False))
 income_quintile   n  estimate    se  ci_low  ci_high    cv flag
               1 495     0.187 0.022   0.145    0.230 0.116     
               2 478     0.127 0.018   0.091    0.163 0.145     
               3 587     0.118 0.016   0.087    0.149 0.134     
               4 607     0.100 0.012   0.075    0.124 0.125     
               5 639     0.101 0.012   0.076    0.125 0.124     

18.7% of adults in the lowest income quintile rate their health as fair or poor, against 10.1% in the highest. Every estimate is releasable without a flag (CVs 12–15%). The gradient is the kind of equity result Module 4 returns to.


16.4 Truth check: run the survey 300 more times (30 min)

A standard error is a claim about what would happen if the survey were repeated. The truth folder has the sampling frame, so you can repeat it: draw areas and people, simulate nonresponse, weight, estimate, 300 times. The spread of those 300 estimates is the true standard error.

"""Day 16.6 (truth check): run the whole survey again 300 times and see how much the estimate moves.

data/truth/ has the sampling frame: every adult's region, collection area, answers and probability of
responding. Redrawing the survey (10 of 30 areas per region, 45 people per area, nonresponse, weighting)
gives the true sampling distribution of each estimate. The bootstrap SE from ONE survey should match its
spread; the naive SE should not.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb  # noqa: E402
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from corridor.survey import estimate, load, proportion, srs_se  # noqa: E402
from corridor.truth import TRUTH  # noqa: E402

frame = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/cchs_frame.csv.gz') ORDER BY person_id").df()
frame["fair_or_poor_health"] = (frame.self_rated_health >= 4).astype(int)
ITEMS = ["diabetes", "regular_provider", "fair_or_poor_health"]
totals = frame.groupby(["province", "age_group", "sex"]).size().rename("N")
areas = {k: v.to_numpy() for k, v in frame.groupby(["region", "area"]).groups.items()}
regions = sorted(frame.region.unique())
rng = np.random.default_rng(2026)

def one_survey():
    idx, base = [], []
    for r in regions:
        for a in rng.choice(30, 10, replace=False):
            people = areas[(r, a)]
            take = rng.choice(people, min(45, len(people)), replace=False)
            idx.append(take)
            base.append(np.full(len(take), 3.0 * len(people) / len(take)))
    s = frame.loc[np.concatenate(idx)].assign(w=np.concatenate(base))
    s["resp"] = rng.random(len(s)) < s.response_probability
    nr = s.groupby(["region", "age_group"]).w.transform("sum") /         s.w.where(s.resp, 0).groupby([s.region, s.age_group]).transform("sum")
    s = s[s.resp].assign(w=lambda d: d.w * nr[d.index])
    ps = s.join(totals, on=["province", "age_group", "sex"])
    s["w"] = s.w * ps.N / s.groupby(["province", "age_group", "sex"]).w.transform("sum")
    return {v: float(np.average(s[v], weights=s.w)) for v in ITEMS}

sims = pd.DataFrame([one_survey() for _ in range(300)])
df, reps = load()
w = df.wts_m.to_numpy()
print(f"{'item':<22}{'population':>11}{'mean of 300':>12}{'true SD':>9}{'boot SE (file)':>15}{'naive SE':>10}")
for v in ITEMS:
    _, se = estimate(proportion(v), df, w, reps)
    print(f"{v:<22}{frame[v].mean():>11.3f}{sims[v].mean():>12.3f}{sims[v].std():>9.4f}{se:>15.4f}"
          f"{srs_se(df, v, w):>10.4f}")
item                   population mean of 300  true SD boot SE (file)  naive SE
diabetes                    0.115       0.113   0.0066         0.0072    0.0058
regular_provider            0.684       0.688   0.0135         0.0139    0.0088
fair_or_poor_health         0.145       0.128   0.0070         0.0072    0.0062

The bootstrap SE from the one survey you have is within 10% of the true SD for all three items. The naive SE is 35% too small for regular provider. The bootstrap gets the variance right.

The table also shows what weights cannot fix. Across 300 surveys, fair or poor health averages 12.8% against a true 14.5%. People in poor health respond less, within every age and income group, and calibration to age, sex and province cannot see that. This is nonresponse bias: it doesn't shrink with sample size, and no standard error measures it. CCHS documentation discusses it; your methods section should too.


16.5 Regression with survey weights (40 min)

Fit the model with the final weight, then refit it with each bootstrap weight; the spread of each coefficient across the 500 fits is its SE. That takes about 15 seconds here.

"""Day 16.5: a weighted logistic regression with bootstrap standard errors."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402
import statsmodels.api as sm  # noqa: E402
import statsmodels.formula.api as smf  # noqa: E402

from corridor.survey import load  # noqa: E402

df, reps = load()
F = "flu_shot_past_year ~ C(age_group) + regular_provider + C(province) + C(income_quintile)"

def fit(weights):
    return smf.glm(F, df, family=sm.families.Binomial(), var_weights=weights / weights.mean()).fit().params

main = fit(df.wts_m.to_numpy())
boot = np.array([fit(reps[:, b]).to_numpy() for b in range(reps.shape[1])])
se_boot = np.sqrt(((boot - main.to_numpy()) ** 2).mean(axis=0))
naive = smf.glm(F, df, family=sm.families.Binomial()).fit()
t = pd.DataFrame({"OR (weighted)": np.exp(main), "SE boot": se_boot,
                  "95% CI": [f"{np.exp(b - 1.96 * s):.2f}-{np.exp(b + 1.96 * s):.2f}" for b, s in zip(main, se_boot)],
                  "OR (unweighted)": np.exp(naive.params), "SE unweighted": naive.bse})
print("Flu shot in the past year: odds ratios")
print(t.drop("Intercept").round(3).to_string())
Flu shot in the past year: odds ratios
                         OR (weighted)  SE boot      95% CI  OR (unweighted)  SE unweighted
C(age_group)[T.35-49]            1.527    0.169   1.10-2.13            1.983          0.172
C(age_group)[T.50-64]            3.461    0.162   2.52-4.75            4.063          0.161
C(age_group)[T.65-79]            5.933    0.163   4.31-8.17            7.282          0.163
C(age_group)[T.80+]             11.265    0.208  7.50-16.93           13.673          0.195
C(province)[T.QC]                1.239    0.118   0.98-1.56            1.237          0.090
C(income_quintile)[T.2]          1.215    0.191   0.84-1.77            1.141          0.155
C(income_quintile)[T.3]          1.556    0.190   1.07-2.26            1.222          0.147
C(income_quintile)[T.4]          1.619    0.179   1.14-2.30            1.387          0.146
C(income_quintile)[T.5]          1.833    0.197   1.25-2.69            1.607          0.143
regular_provider                 1.647    0.123   1.29-2.10            1.856          0.107

Check it in R. The survey package does all of Day 16 with svrepdesign(type = "bootstrap", ..., mse = TRUE):

# Day 16: the same estimates with the survey package and the bootstrap weights.
suppressPackageStartupMessages(library(survey))
df <- read.csv("data/cchs_2024.csv")
bw <- read.csv(gzfile("data/cchs_2024_bootstrap.csv.gz"))
stopifnot(identical(df$resp_id, bw$resp_id))
df <- cbind(df, bw[, -1])
df$fair_or_poor_health <- as.integer(df$self_rated_health >= 4)
des <- svrepdesign(data = df, weights = ~wts_m, repweights = "bsw[0-9]+", type = "bootstrap",
                   combined.weights = TRUE, scale = 1 / 500, rscales = 1, mse = TRUE)
for (v in c("diabetes", "high_blood_pressure", "regular_provider", "flu_shot_past_year", "fair_or_poor_health")) {
  m <- svymean(as.formula(paste0("~", v)), des)
  cat(sprintf("%-22s %.3f  SE %.4f\n", v, coef(m), SE(m)))
}
cat("\nRegular provider by province:\n")
print(svyby(~regular_provider, ~province, des, svymean))
fit <- svyglm(flu_shot_past_year ~ age_group + regular_provider + province + factor(income_quintile),
              design = des, family = quasibinomial())
cat("\nFlu shot: odds ratios (survey-weighted)\n")
print(round(exp(coef(fit))[-1], 3))
diabetes               0.105  SE 0.0072
high_blood_pressure    0.251  SE 0.0088
regular_provider       0.683  SE 0.0139
flu_shot_past_year     0.278  SE 0.0110
fair_or_poor_health    0.124  SE 0.0072

Regular provider by province:
   province regular_provider         se
ON       ON        0.7247593 0.01894264
QC       QC        0.6135682 0.01908884

Flu shot: odds ratios (survey-weighted)
          age_group35-49           age_group50-64           age_group65-79 
                   1.527                    3.461                    5.933 
            age_group80+         regular_provider               provinceQC 
                  11.265                    1.647                    1.239 
factor(income_quintile)2 factor(income_quintile)3 factor(income_quintile)4 
                   1.215                    1.556                    1.619 
factor(income_quintile)5 
                   1.833 

Python and R agree to every printed digit. Two things change between the weighted and unweighted models:

  • The SEs. The bootstrap SE for Quebec is 0.118, against 0.090 unweighted. Province, like having a provider, varies between clusters.
  • The age ORs. Weighted, adults 80+ have 11 times the odds of a flu shot compared with 18–34-year-olds; unweighted, 14 times. When the design or the nonresponse depends on things related to the outcome, the unweighted model estimates something about the sample, not the population. For population-level statements in HTA or policy, use the weights.

16.6 The right weights, the wrong standard error (15 min)

Bug of the day. An analyst weights the estimate correctly, then builds the confidence interval with the textbook formula $\sqrt{p(1-p)/n}$:

"""Day 16 bug of the day: the right weights, the wrong standard error."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import statsmodels.stats.proportion as smp  # noqa: E402

from corridor.survey import estimate, load, proportion  # noqa: E402

df, reps = load()
w = df.wts_m.to_numpy()
qc = (df.province == "QC").to_numpy()
est, se = estimate(proportion("regular_provider", qc), df, w, reps)
lo, hi = smp.proportion_confint(round(est * qc.sum()), qc.sum(), method="normal")   # the bug: n respondents, SRS
print(f"Quebec adults with a regular provider: {est:.3f}")
print(f"  'CI' from the SRS formula with n = {qc.sum():,}:  {lo:.3f} to {hi:.3f}   (width {hi - lo:.3f})")
print(f"  CI from the bootstrap weights:                 {est - 1.96 * se:.3f} to {est + 1.96 * se:.3f}   "
      f"(width {3.92 * se:.3f})")
Quebec adults with a regular provider: 0.614
  'CI' from the SRS formula with n = 1,522:  0.589 to 0.638   (width 0.049)
  CI from the bootstrap weights:                 0.576 to 0.651   (width 0.075)

The naive interval is two-thirds as wide as the correct one. Section 16.4 showed the bootstrap matches the truth, so the naive interval would miss the true value far more often than 5% of the time. It looks more precise, and a provincial comparison built on it would find "significant" differences that are not there. If a file comes with bootstrap weights, every SE uses them.

Why it matters at work: Survey estimates feed HTA models (utilities, prevalence, productivity) and policy briefs. Reviewers and Statistics Canada's research data centres check that variance estimates use the bootstrap weights and that releases follow the CV rules. Results that don't are sent back.

Where you'll meet this: CCHS and the Canadian Health Measures Survey in Statistics Canada research data centres · prevalence inputs for budget impact analyses · EQ-5D from surveys (Day 17)


16.7 Mini-project: survey indicators for the burden-of-illness report (60 min)

Build the survey table for the Module 2 capstone: self-reported diabetes and high blood pressure, by province and age group, with percentages, estimated numbers of adults, 95% CIs and release flags. Suppress F estimates. The table is aggregate, so it goes into docs/.

"""Day 16 mini-project: a survey indicator table for the burden-of-illness report.

Self-reported diabetes and high blood pressure, by province and age group: prevalence, estimated number
of adults, 95% CIs and release flags. The table is aggregate and safe to share (docs/).
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from corridor.db import ROOT  # noqa: E402
from corridor.survey import estimate, flag, load, proportion, total  # noqa: E402

df, reps = load()
w = df.wts_m.to_numpy()
rows = []
for item in ("diabetes", "high_blood_pressure"):
    for prov in ("ON", "QC"):
        for age in ["All"] + sorted(df.age_group.unique()):
            m = (df.province == prov).to_numpy() & ((df.age_group == age).to_numpy() if age != "All" else True)
            p, se = estimate(proportion(item, m), df, w, reps)
            n_adults, se_n = estimate(total(item, m), df, w, reps)
            f = flag(p, se, int(m.sum()))
            show = not f.startswith("F")
            rows.append({"item": item, "province": prov, "age_group": age, "respondents": int(m.sum()),
                         "percent": round(100 * p, 1) if show else None,
                         "ci_95": f"{100 * (p - 1.96 * se):.1f}-{100 * (p + 1.96 * se):.1f}" if show else "",
                         "adults": int(round(n_adults, -2)) if show else None,
                         "adults_ci_95": f"{round(n_adults - 1.96 * se_n, -2):,.0f}-{round(n_adults + 1.96 * se_n, -2):,.0f}"
                         if show else "", "flag": f})
t = pd.DataFrame(rows).astype({"percent": "Float64", "adults": "Int64"})
os.makedirs(os.path.join(ROOT, "docs"), exist_ok=True)
t.to_csv(os.path.join(ROOT, "docs", "survey_indicators.csv"), index=False)
print(t[t.item == "diabetes"].to_string(index=False))
print(f"\n{len(t)} rows written to docs/survey_indicators.csv; flags: "
      + ", ".join(f"{k or 'none'} {v}" for k, v in t.flag.value_counts().items()))
    item province age_group  respondents  percent     ci_95  adults  adults_ci_95 flag
diabetes       ON       All         1284     11.0  9.0-13.1   17000 13,900-20,200     
diabetes       ON     18-34          271     <NA>              <NA>                  F
diabetes       ON     35-49          316      5.1   2.0-8.2    2000     800-3,200    E
diabetes       ON     50-64          329      7.9  4.2-11.6    3000   1,600-4,400    E
diabetes       ON     65-79          263     23.1 16.5-29.7    6700   4,800-8,600     
diabetes       ON       80+          105     42.0 31.1-52.9    4100   3,000-5,200     
diabetes       QC       All         1522      9.7  8.2-11.3    9200  7,700-10,600     
diabetes       QC     18-34          307     <NA>              <NA>                  F
diabetes       QC     35-49          331      5.4   2.6-8.2    1300     600-1,900    E
diabetes       QC     50-64          398      8.5  5.5-11.5    1900   1,300-2,600    E
diabetes       QC     65-79          343     19.2 15.7-22.7    3400   2,700-4,000     
diabetes       QC       80+          143     31.5 19.4-43.6    1900   1,200-2,600    E

24 rows written to docs/survey_indicators.csv; flags: none 14, E 8, F 2

About 17,000 Ontario adults and 9,200 Quebec adults in Corridor Health report diabetes, 11.0% and 9.7%. The young-adult estimates are suppressed and most middle-age ones carry an E flag. Two cautions for the report:

  • Self-report is not diagnosis. In the generator, 7% of adults with diabetes don't report it and a few without it say they have it. Even a perfect survey measures self-report: across the whole frame it is 11.5%, and this one sample's 10.5% is within 1.5 SE of that. Day 5's administrative case definition answers a different question, and the report should give both.
  • The burden is in the oldest groups: 42% of Ontario adults 80+ report diabetes. That is where the CKD cohort comes from.

Write one paragraph that a provincial reader can quote, flags included.

16.8 Save your work

python -m pytest -q
git add .
git commit -m "Day 16: survey weights, bootstrap variance, release flags, survey indicators"

Day 16 checklist

  • I weight every population estimate with the final weight and get every SE from the bootstrap weights
  • I can explain a design effect and why clustering and unequal weights inflate the variance
  • I apply the CV and minimum-count release rules and flag E and F estimates
  • I fit weighted regressions with replicate-weight SEs, in Python and with R's survey package
  • I can name a bias that weighting does not fix (nonresponse related to the outcome)