Survey Weights in R: NHANES Adult Obesity Estimates

Two dots for BMI of at least 30 kilograms per square metre: unweighted 41.14 percent and weighted 40.26 percent, with a horizontal 95 percent interval from 36.34 to 44.19 percent only for the weighted dot.

NHANES 2021–2023: sampling weights, clustered design, honest uncertainty

A sample percentage answers “What fraction of the examined participants meets the BMI threshold?” A survey-weighted estimate asks the more consequential question: “What fraction of the population represented by the survey meets it?” Both are meaningful, but only the second uses the survey’s sampling structure to estimate a population quantity.

NHANES is a cross-sectional survey, so this analysis estimates a descriptive prevalence, not a cause or a change over time. The BMI threshold is useful for population monitoring but is not a complete clinical assessment of an individual.

The question and dataset

NHANES August 2021–August 2023 samples the civilian, noninstitutionalized U.S. population through a multistage probability design. Here the outcome is measured body mass index (BMI) of at least 30 kg/m² among adults aged 20 or older. Valid survey inference needs the examination weight, masked variance stratum, and masked primary sampling unit (PSU). These encode different aspects of population representation and sampling precision.

  • Observed target: BMI ≥ 30 kg/m² among adults aged 20+ with measured BMI, excluding known pregnancy-positive participants.
  • Sampling features: WTMEC2YR, SDMVSTRA, and SDMVPSU.
  • Age groups: 20–39, 40–59, and 60+ (top-coded age 80).
  • Key limitation: Unreported pregnancy status cannot be treated as confirmed nonpregnancy, and exam weights do not fix BMI item missingness.

The aim is to teach why weighting changes a point estimate and why stratified, clustered sampling changes its standard error. No model is trained, no individual outcome is predicted, and no causal explanation is inferred.

Step 1 — Import the actual data

We begin with the measured-data extract and use two R packages for complementary tasks: survey implements the complex sampling design and its variance estimators, while ggplot2 makes the statistical comparison visible. The input includes one record per examined adult rather than one row per sampling cluster.

# 1. Dependencies and data
packages <- c("survey", "ggplot2")
missing_packages <- packages[!vapply(packages, requireNamespace, logical(1), quietly = TRUE)]
if (length(missing_packages)) {
  stop("Install required packages first: install.packages(c(\"survey\", \"ggplot2\"))",
       call. = FALSE)
}
library(survey)
Warning: package 'survey' was built under R version 4.5.2
Loading required package: grid
Loading required package: Matrix
Loading required package: survival

Attaching package: 'survey'
The following object is masked from 'package:graphics':

    dotchart
library(ggplot2)

input_file <- "01_data/nhanes_2021_2023_adult_bmi.csv"
output_dir <- "04_outputs"
if (!file.exists(input_file)) stop("Run from the project root: CSV not found")
dir.create(output_dir, showWarnings = FALSE, recursive = TRUE)
nhanes <- read.csv(input_file, na.strings = c("", "NA"))

The file contains examined adults with positive mobile-examination-center (MEC) weights. The presence of an examination record does not mean every participant has a measured BMI. The next step therefore establishes the correct outcome denominator before any proportions are calculated.

Step 2 — Validate denominators and define the population domain

BMI missingness must stay missing: otherwise the denominator is inflated and obesity prevalence is biased downward. The code checks uniqueness, classifications, design variables, and valid recorded demographics. The primary analysis excludes individuals known to be pregnancy-positive, because the standard adult BMI threshold is not clinically interpretable in pregnancy. We retain missing pregnancy status as unknown, not as evidence of nonpregnancy.

# 2. Audit the participant-level data
expected <- c("SEQN", "RIDAGEYR", "RIAGENDR", "BMXBMI", "BMDSTATS",
              "RIDEXPRG", "WTMEC2YR", "SDMVSTRA", "SDMVPSU",
              "obesity_30", "age_group", "bmi_observed")
if (!identical(names(nhanes), expected)) stop("Unexpected dataset columns or order")
if (anyDuplicated(nhanes$SEQN)) stop("Participant IDs are not unique")
if (anyNA(nhanes$WTMEC2YR) || any(nhanes$WTMEC2YR <= 0)) {
  stop("Examination weights must be present and positive")
}
if (anyNA(nhanes$SDMVSTRA) || anyNA(nhanes$SDMVPSU)) {
  stop("Missing masked survey design variable")
}
if (any(nhanes$RIDAGEYR < 20) || any(!nhanes$RIAGENDR %in% c(1, 2))) {
  stop("Unexpected adult age or gender code")
}
expected_obesity <- ifelse(is.na(nhanes$BMXBMI), NA_integer_,
                           as.integer(nhanes$BMXBMI >= 30))
if (!identical(as.integer(nhanes$obesity_30), expected_obesity)) {
  stop("BMI and obesity classification disagree")
}
if (!identical(as.integer(nhanes$bmi_observed),
               as.integer(!is.na(nhanes$BMXBMI)))) {
  stop("BMI completeness indicator disagrees with BMI")
}

nhanes$age_group <- factor(nhanes$age_group,
                           levels = c("20-39", "40-59", "60+"))
if (anyNA(nhanes$age_group)) stop("Unknown age-group label")
nhanes$gender <- factor(nhanes$RIAGENDR, levels = c(1, 2),
                        labels = c("Male", "Female"))

# Pregnancy-positive BMI is unsuitable for the usual adult obesity definition.
# Missing RIDEXPRG values are *not* interpreted as confirmed nonpregnancy.
nhanes$analysis_eligible <- !is.na(nhanes$BMXBMI) &
  (is.na(nhanes$RIDEXPRG) | nhanes$RIDEXPRG != 1)

n_complete <- sum(!is.na(nhanes$BMXBMI))
n_eligible <- sum(nhanes$analysis_eligible)
audit <- data.frame(
  item = c("examined_adults", "bmi_observed", "bmi_missing",
           "pregnancy_positive", "primary_analysis_n", "strata", "stratum_psu_pairs"),
  count = c(nrow(nhanes), n_complete, sum(is.na(nhanes$BMXBMI)),
            sum(nhanes$RIDEXPRG == 1, na.rm = TRUE), n_eligible,
            length(unique(nhanes$SDMVSTRA)),
            nrow(unique(nhanes[c("SDMVSTRA", "SDMVPSU")])))
  )
write.csv(audit, file.path(output_dir, "01_data_audit.csv"), row.names = FALSE)
print(audit, row.names = FALSE)
               item count
    examined_adults  6064
       bmi_observed  5970
        bmi_missing    94
 pregnancy_positive    41
 primary_analysis_n  5929
             strata    15
  stratum_psu_pairs    30

What the audit means: In this snapshot, 6064 examined adults are available; 5970 have BMI, and 5929 meet the teaching analysis domain. These are sample counts, not weighted U.S. population totals.

Step 3 — Tell R how NHANES sampled people

An NHANES weight represents an observation’s contribution to a population summary. Clustering means people from the same masked PSU are not independent in the same way as independent random draws. Stratification divides the design into variance-estimation strata. The survey package uses these structures for design-based (Taylor-linearized) uncertainty.

Construct the full examined-adult design first, then use subset() to make the analysis domain. Dropping other surveyed participants before design creation can discard design information and distort domain variance calculations.

# 3. Specify the actual NHANES complex sample
# Construct the design before restricting to the BMI/pregnancy domain.
nhanes_design <- svydesign(ids = ~SDMVPSU, strata = ~SDMVSTRA,
                           weights = ~WTMEC2YR, nest = TRUE, data = nhanes)
main_design <- subset(nhanes_design, analysis_eligible)
all_bmi_design <- subset(nhanes_design, !is.na(BMXBMI))
design_df <- degf(nhanes_design)
cat("Design degrees of freedom:", design_df, "\n")
Design degrees of freedom: 15 

The dataset has 15 masked strata and 30 stratum–PSU combinations, giving 15 design degrees of freedom. These degrees of freedom reflect the available sampling units relative to strata, not the number of participant records. The uncertainty calculation cannot treat thousands of records as thousands of independently sampled areas.

Step 4 — The key comparison: sample share versus population estimate

The unweighted sample share is a legitimate description of the analysis participants. The weighted estimate answers the population question using each person’s examination weight. For binary obesity status, the point estimator is a ratio of weighted totals:

p̂ = (Σᵢ∈D wáµ¢yáµ¢) / (Σᵢ∈D wáµ¢), where yáµ¢ = I(BMIáµ¢ ≥ 30).

Here, D is the observed-BMI domain after excluding known pregnancy-positive respondents; wáµ¢ is the examination weight. This equation changes the point estimate; stratification and PSU clustering govern its design-based uncertainty.

# 4. Compare the sample fraction with a national survey-weighted estimate
ordinary_fraction <- mean(nhanes$obesity_30[nhanes$analysis_eligible])
weighted_obesity <- svymean(~obesity_30, main_design)
weighted_ci <- confint(weighted_obesity, df = degf(main_design))

# A useful arithmetic cross-check: weighting the same domain must match svymean.
direct_weighted <- with(nhanes[nhanes$analysis_eligible, ],
                        weighted.mean(obesity_30, WTMEC2YR))
stopifnot(isTRUE(all.equal(unname(coef(weighted_obesity)), direct_weighted)))

comparison <- data.frame(
  method = c("Unweighted sample", "Survey-weighted population"),
  n = rep(n_eligible, 2),
  estimate = c(ordinary_fraction, unname(coef(weighted_obesity))),
  se = c(NA_real_, unname(SE(weighted_obesity))),
  ci_low = c(NA_real_, weighted_ci[1, 1]),
  ci_high = c(NA_real_, weighted_ci[1, 2])
)
write.csv(comparison, file.path(output_dir, "02_overall_comparison.csv"),
          row.names = FALSE)
print(comparison, row.names = FALSE, digits = 4)
                     method    n estimate      se ci_low ci_high
          Unweighted sample 5929   0.4114      NA     NA      NA
 Survey-weighted population 5929   0.4026 0.01843 0.3634  0.4419
Sample share and design-based population prevalence
Approach Sample n BMI ≥ 30 95% design-based CI
Unweighted sample 5929 41.14% Not a population CI
Survey-weighted population 5929 40.26% 36.34%–44.19%

The observed fraction among eligible respondents is 41.14%. Applying examination weights gives 40.26%, a reduction of 0.87 percentage points in this dataset. Weighting can move a point estimate in either direction; its impact depends on how outcome values covary with survey weights.

The design-based standard error is 1.84 percentage points, and the 95% interval is 36.34%–44.19%. This is a t-based, Taylor-linearized interval that accounts for masked strata and PSU clustering. A small shift in the point estimate does not excuse ignoring the design, and the descriptive unweighted dot has no national confidence interval in the comparison graphic.

Step 5 — Examine subgroups without pretending to have a simple random sample

Group-specific estimates are calculated as domains of the same complex sample. The uncertainty bars matter especially when groups have different precision. These are crude age-group comparisons, not age-standardized population comparisons. Recorded gender is the two-category NHANES variable supplied in the demographic file.

# 5. Design-aware prevalence by age group and recorded gender
# A short helper keeps each domain on the same estimator and t-based CI.
domain_estimate <- function(design, label) {
  result <- svymean(~obesity_30, design)
  interval <- confint(result, df = degf(design))
  data.frame(group = label, n = nrow(design$variables),
             estimate = unname(coef(result)), se = unname(SE(result)),
             ci_low = interval[1, 1], ci_high = interval[1, 2])
}

age_table <- do.call(rbind, lapply(levels(nhanes$age_group), function(g) {
  domain_estimate(subset(main_design, age_group == g), g)
}))
gender_table <- do.call(rbind, lapply(levels(nhanes$gender), function(g) {
  domain_estimate(subset(main_design, gender == g), g)
}))
rownames(age_table) <- NULL
rownames(gender_table) <- NULL
write.csv(age_table, file.path(output_dir, "03_prevalence_by_age.csv"),
          row.names = FALSE)
write.csv(gender_table, file.path(output_dir, "04_prevalence_by_gender.csv"),
          row.names = FALSE)
print(age_table, row.names = FALSE, digits = 4)
 group    n estimate      se ci_low ci_high
 20-39 1498   0.3553 0.02954 0.2923  0.4182
 40-59 1709   0.4638 0.01754 0.4264  0.5012
   60+ 2722   0.3890 0.01549 0.3560  0.4220
print(gender_table, row.names = FALSE, digits = 4)
  group    n estimate      se ci_low ci_high
   Male 2680   0.3920 0.01929 0.3509  0.4332
 Female 3249   0.4128 0.02197 0.3660  0.4597
Population estimates by age group (not age-standardized)
Age group Sample n Estimated BMI ≥ 30 95% design-based CI
20-39 1498 35.53% 29.23%–41.82%
40-59 1709 46.38% 42.64%–50.12%
60+ 2722 38.90% 35.60%–42.20%
Population estimates by recorded gender (unadjusted)
Recorded gender Sample n Estimated BMI ≥ 30 95% design-based CI
Male 2680 39.20% 35.09%–43.32%
Female 3249 41.28% 36.60%–45.97%

The highest observed age-group point estimate is for ages 40–59, at 46.38%, versus 35.53% for ages 20–39 and 38.90% for ages 60+. The 20–39 estimate also has the widest interval. The groups are not age-standardized or otherwise covariate-adjusted; neither the ranking nor overlap of intervals is a formal test of pairwise differences.

The two NHANES recorded-gender categories likewise have design-based estimates: 39.20% for males and 41.28% for females. These are unadjusted descriptive rates, not evidence of a causal gender effect.

Step 6 — Check missing BMI and the pregnancy decision

Complete-case analysis can change the represented target population if BMI is not observed at random. The code measures weighted missingness among examined adults and contrasts the primary result with a sensitivity version that includes observed BMI for known pregnancy-positive respondents. These are sensitivity checks, not proof that bias is absent.

# 6. Missing measurement and pregnancy sensitivity
bmi_recorded <- svymean(~bmi_observed, nhanes_design)
weighted_missing <- 1 - unname(coef(bmi_recorded))
with_pregnancy <- svymean(~obesity_30, all_bmi_design)
sensitivity <- data.frame(
  measure = c("Weighted BMI missing fraction (all examined adults)",
              "Primary obesity fraction (known pregnancy-positive excluded)",
              "Obesity fraction (pregnancy-positive included)"),
  estimate = c(weighted_missing, unname(coef(weighted_obesity)),
               unname(coef(with_pregnancy)))
)
write.csv(sensitivity, file.path(output_dir, "05_sensitivity.csv"),
          row.names = FALSE)
print(sensitivity, row.names = FALSE, digits = 4)
                                                      measure estimate
          Weighted BMI missing fraction (all examined adults)  0.01275
 Primary obesity fraction (known pregnancy-positive excluded)  0.40264
               Obesity fraction (pregnancy-positive included)  0.40270

Of 6064 examined adults, 94 lack measured BMI. Their weighted share is 1.27%. This quantifies missing outcome records but cannot establish that missingness is unrelated to BMI.

When known pregnancy-positive records are included, the weighted estimate is 40.27%, compared with 40.26% under the primary exclusion. The difference is only 0.007 percentage points here, but a small numerical sensitivity is not a clinical justification for combining pregnant and nonpregnant adult BMI classifications. Missing pregnancy codes may also reflect inapplicability of the question rather than a confirmed negative status.

Step 7 — Make interpretable graphics

Three views illuminate distinct statistical mechanisms. The overall comparison separates a sample fraction from a population estimator. The age-group plot shows point estimates with their design-based precision rather than relying on ranks alone. The weight-distribution plot uses a logarithmic vertical axis to show how variable respondent contributions are; it is not itself a comparison of obesity outcomes.

# 7. Visualize population estimates, intervals, and sample weights
comparison$method <- factor(comparison$method, levels = comparison$method)
p_comparison <- ggplot(comparison, aes(x = method, y = estimate * 100)) +
  geom_point(size = 3.5, color = "#126e82") +
  geom_errorbar(data = subset(comparison, !is.na(ci_low)),
                aes(ymin = 100 * ci_low, ymax = 100 * ci_high),
                width = 0.12, linewidth = 0.8, color = "#126e82") +
  coord_flip() +
  labs(x = NULL, y = "Adults with BMI ≥ 30 (%)",
       title = "Counting people and estimating a population differ",
       subtitle = "95% design-based interval shown for the weighted estimate only",
       caption = "NHANES Aug 2021–Aug 2023; adults 20+, observed BMI; known pregnancy-positive excluded") +
  theme_minimal(base_size = 12) +
  theme(panel.grid.major.y = element_blank(), legend.position = "none")

ggsave(file.path(output_dir, "01_sample_vs_weighted.png"),
       p_comparison, width = 9, height = 4.5, dpi = 300, bg = "white")

age_table$group <- factor(age_table$group, levels = c("20-39", "40-59", "60+"))
p_age <- ggplot(age_table, aes(x = group, y = estimate * 100)) +
  geom_errorbar(aes(ymin = ci_low * 100, ymax = ci_high * 100),
                width = 0.11, linewidth = 0.8, color = "#126e82") +
  geom_point(size = 3.1, color = "#126e82") +
  coord_flip() +
  labs(x = "Age group (years)", y = "Estimated BMI ≥ 30 (%)",
       title = "Age-group estimates must carry design-based uncertainty",
       subtitle = "Point estimates and 95% confidence intervals",
       caption = "NHANES Aug 2021–Aug 2023; not age-standardized") +
  theme_minimal(base_size = 12) +
  theme(panel.grid.major.y = element_blank())

ggsave(file.path(output_dir, "02_age_group_intervals.png"),
       p_age, width = 9, height = 4.5, dpi = 300, bg = "white")

p_weights <- ggplot(nhanes[nhanes$analysis_eligible, ],
                    aes(x = gender, y = WTMEC2YR, fill = gender)) +
  geom_boxplot(outlier.alpha = 0.18, width = 0.5) +
  scale_y_log10(labels = scales::label_number(big.mark = ",")) +
  scale_fill_manual(values = c(Male = "#126e82", Female = "#d08d57")) +
  labs(x = "NHANES gender code", y = "Exam weight (logarithmic scale)",
       title = "Survey participants represent different population shares",
       subtitle = "Sampling weights are not all equal",
       caption = "NHANES Aug 2021–Aug 2023; visualization is not an obesity comparison") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "none", panel.grid.major.x = element_blank())

ggsave(file.path(output_dir, "03_exam_weight_distribution.png"),
       p_weights, width = 9, height = 4.5, dpi = 300, bg = "white")

Two dots for BMI of at least 30 kilograms per square metre: unweighted 41.14 percent and weighted 40.26 percent, with a horizontal 95 percent interval from 36.34 to 44.19 percent only for the weighted dot.

Same observed domain, different estimands: the unweighted sample fraction is 41.14% and the survey-weighted estimate is 40.26% (95% CI 36.34%–44.19%); only the latter has a population interval.

Three horizontally oriented dot-and-interval marks: age 20 to 39 at 35.53 percent, 40 to 59 at 46.38 percent, and 60 plus at 38.90 percent, each with a horizontal confidence interval.

Observed age pattern: adults 40–59 have the highest weighted point estimate (46.38%), while adults 20–39 have a wider 95% design-based interval. These estimates are not age-standardized.

Two boxplots of positive survey weights displayed on a logarithmic axis.

Examination weights vary substantially within both recorded-gender groups. The logarithmic scale shows weight heterogeneity, not an obesity difference.

Step 8 — Save a reproducibility record

Reproducible survey research records the software environment alongside the estimator, the population domain, and the sampling-design variables. Package versions can matter for numerical behavior and reporting defaults. The final section captures that information so later analysts can interpret and repeat the calculation.

# 8. Record provenance of the software used
writeLines(capture.output(sessionInfo()),
           con = file.path(output_dir, "06_R_session_info.txt"))
cat("Saved survey estimates and figures in", output_dir, "\n")
Saved survey estimates and figures in 04_outputs 

Interpreting the result responsibly

The main weighted estimate of 40.26% is a descriptive prevalence for the stated observed-BMI domain in the August 2021–August 2023 release. Its confidence interval captures sampling variability under the specified complex design. Neither the point estimate nor the interval can remove all item-nonresponse, coverage, or measurement bias.

The data are cross-sectional. Differences across age and recorded-gender categories cannot establish causes, and one survey period does not demonstrate a trend. BMI at or above 30 is a population-surveillance category, not an individual’s complete diagnosis. Source qualification: the teaching CSV was assembled from public mirrors of NHANES demographic and body-measurement files; exact byte-level agreement with the original CDC XPT files has not been established. This source limitation does not disappear because calculations are internally reproducible.

For other surveys, the transferable procedure is to identify the appropriate analysis weight and sampling units, define the target population and denominator, calculate a design-aware estimator, and report uncertainty and missingness. A simple random sample or an agricultural experiment requires its own design analysis; NHANES weights and masked PSU identifiers are not generic inputs.

Common mistake

Using mean(obesity_30, na.rm = TRUE) alone and reporting a simple-binomial confidence interval as a national NHANES population estimate. That ignores unequal weights and the clustered/stratified design. Conversely, using weights but treating each respondent as independent also gives the wrong uncertainty mechanism.

Primary sources and reproducibility

AGRON Info Tech — Applied survey statistics in R.

Comments