How to Analyze NHANES and UK Biobank: Weighting, Variance, and RAP Workflow

Analyzing NHANES and UK Biobank microdata requires distinct analytical frameworks for complex survey weighting, variance estimation, and secure enclave governance. Here is how to execute an end-to-end epidemiological workflow that withstands peer review.

HumanPen Team

· 16 min read

Public Health Cohort Analysis: Harmonizing NHANES and UK Biobank Workflows

Empirical investigations across nutritional epidemiology, chronic disease surveillance, and environmental health rely extensively on two premier population-scale microdata resources: the US National Health and Nutrition Examination Survey (`NHANES`, administered continuously by the CDC National Center for Health Statistics) and the UK Biobank (`UK Biobank`, tracking approximately 500,000 middle-aged and older volunteers across England, Scotland, and Wales). While both resources empower high-impact clinical discoveries, their fundamental sampling architectures and inferential objectives diverge. NHANES is a complex, multistage probability survey explicitly designed to produce nationally representative prevalence and health metric estimates for the civilian noninstitutionalized US population, mandating the rigorous application of survey weights (`WTMEC2YR`/`WTINT2YR`), primary sampling units (`SDMVPSU`), and stratification units (`SDMVSTRA`). In sharp contrast, UK Biobank is an unweighted prospective volunteer cohort designed to elucidate biological exposure–disease etiological relationships; its participants are not representative of the broader UK population, but its internal hazard ratios and odds ratios remain generalizable without survey probability weights.

Core methodological takeaway: Quoting official guidance from the CDC NCHS NHANES Tutorials Weighting Module: "Weights are created in NHANES to account for the complex survey design (including oversampling), survey non-response, and post-stratification adjustment to match total population counts from the Census Bureau. When a sample is weighted in NHANES it is representative of the U.S. civilian noninstitutionalized population. A sample weight is assigned to each sampled person. It is a measure of the number of people in the population represented by that sampled person." Failing to apply complex multistage weights in NHANES biases parameter estimates and severely underestimates standard errors, whereas attempting to force demographic probability weights onto UK Biobank fundamentally misapprehends its unweighted volunteer cohort design.

Navigating these multi-gigabyte biobanks demands disciplined data governance: harmonizing SAS transport (`.XPT`) files across multi-cycle continuous NHANES releases, adhering strictly to the smallest subpopulation weighting rule, constructing full-sample survey design objects with stratum nesting in R `survey::svydesign(..., nest = TRUE)`, and respecting UK Biobank Material Transfer Agreement enclave boundaries. Establishing reproducible end-to-end analytical pipelines—moving deterministically from raw microdata archives to peer-reviewed regression tables and restricted cubic spline plots—follows the rigorous principles outlined in our guide on building reproducible empirical papers from public microdata, and provides an essential counterpart to the longitudinal panel methods detailed in our guide on CHARLS, CFPS, and HRS longitudinal survey analysis.

Multi-Cycle NHANES Survey Weighting, Smallest Subpopulation Rules, and XPT Merging

Processing continuous NHANES data begins with automated retrieval and concatenation of SAS transport (`.XPT`) files across survey cycles using R `nhanesA` (`v1.4.1`) or Python, joining demographic records (`DEMO`), mobile examination center data (`BMX`), laboratory assays (`LAB`), and questionnaire modules on the unique respondent sequence number `SEQN`. The primary analytical pitfall in NHANES research lies in weight selection. CDC NCHS explicitly mandates the Smallest Subpopulation Rule: "You must use the weight of the smallest subpopulation that includes all the variables you want to include in your analysis." If every covariate and outcome in the model is collected exclusively during the household interview, the analyst applies interview weights `WTINT2YR`. However, the moment any variable requires examination at the Mobile Examination Center (such as blood pressure, body mass index, complete blood count, or standard biochemistry), the researcher must apply MEC examination weights `WTMEC2YR`. Furthermore, if the model incorporates subsample laboratory analytes—such as morning fasting glucose and insulin (`WTSAF2YR`), 24-hour dietary recalls (`WTDRD1` or `WTDR2D`), or environmental chemical panels administered to a one-third subsample—the analyst must select the specific subsample weight, even if all other covariates originate from interview or full-MEC modules.

Epidemiological Cohort and Survey PlatformTarget Population and Sampling StrategyPrimary Weights and Adjustment FormulasVariance Estimation and Subgroup StrategyCritical Methodological and Governance Boundary
CDC NHANES Standard 2-Year Continuous Cycles (2001-2018)Noninstitutionalized civilian US population sampled via stratified multistage probability clusteringContinuous cycle weights WTMEC2YR or WTINT2YR divided by k pooled cycles (w_multi = WTMEC2YR / k)Taylor series linearization using SDMVPSU and SDMVSTRA with nest = TRUE on complete sampleOpen public-use XPT microdata freely accessible and uploadable up to 5 GB for survey modeling
CDC NHANES Pre-Pandemic Pooled Cycle (2017-March 2020, sddsrvyr == 66)Nationally representative 3.2-year pre-pandemic sample combining 2017-2018 and partial 2019-2020Scaled pre-pandemic weights WTMECPRP multiplied by 3.2 / (2m + 3.2) when pooled with m standard cyclesFull-sample svydesign before subpopulation domain analysis via subset(des_full, ...)Never pool standalone 2017-2018 J-cycle with pre-pandemic P_* files due to duplicate participant records
UK Biobank Prospective Cohort (~500,000 Participants Aged 40-69)Community volunteers across England, Scotland, and Wales (2006-2010 baseline with 5.5% response rate)Unweighted for etiological hazard ratios and odds ratios (no population probability weights applied)Robust sandwich clustering by assessment center or family ID without complex survey weightingPronounced healthy volunteer selection bias: never report crude cohort rates as UK national disease prevalence
UK Biobank Research Analysis Platform (UKB-RAP / DNAnexus Enclave)Cloud-based secure compute environment hosting individual-level phenotypic and genomic dataApplication-specific scrambled 7-digit eid identifiers (1,000,000-6,000,000 range)High-performance computing execution of GWAS, Cox models, and pheWAS within certified boundaryMTA Annex 1 strictly prohibits unauthorized export or external upload of individual-level participant data

Multi-cycle pooling requires disciplined mathematical scaling to prevent population inflation. When combining `k` standard two-year cycles from 2001 onward, the pooled weight equals `w_multi = WTMEC2YR / k`. However, the COVID-19 pandemic abruptly disrupted 2019–2020 field operations in mid-March 2020 after completing only 18 of 30 planned PSUs, rendering the 2019–2020 cycle non-representative in isolation. To restore population validity, CDC NCHS merged 2017–2018 (`_J`) and 2019–March 2020 data into pre-pandemic `P_*` files (`WTINTPRP`, `WTMECPRP`, `WTSAFPRP`, flagged by `sddsrvyr == 66`), representing a 3.2-year period. Quoting official CDC NCHS tutorial guidance on combining cycles: "The 2017-March 2020 pre-pandemic files represent a 3.2-year period, in contrast to previous data releases which represent a 2-year period. Combining cycles 2015-2016 and 2017-March 2020 would result in a data file representing a 5.2-year period. You can create a 5.2-year weight variable by multiplying the 2-year weight (WTMEC2YR) for cycle 2015-2016 by 2/5.2 (the fraction of the 5.2-year period represented by the 2015-2016 cycle) and likewise, the 2017-March 2020 weight (WTMECPRP) by 3.2/5.2." Analysts combining `m` standard two-year cycles with the 3.2-year pre-pandemic file must multiply standard weights by `2 / (2m + 3.2)` and pre-pandemic weights by `3.2 / (2m + 3.2)`. Researchers must never combine standalone `2017–2018` with `2017–March 2020` files, and must audit sampling frame shifts in the August 2021–August 2023 (`_L`) release.

  • Enforce the Smallest Subpopulation Rule: Select `WTINT2YR` exclusively when all variables are interview-derived, switch to `WTMEC2YR` for physical measurements or standard lab panels, and adopt specialized subsample weights (`WTSAF2YR`, dietary, or environmental) whenever restricted-subsample analytes enter the specification.
  • Scale Multi-Cycle Weights by Time Span: Divide standard two-year weights by `k` when pooling consecutive continuous cycles from 2001 onward to align the sample scale with the US Census civilian noninstitutionalized population frame.
  • Apply the 3.2-Year Pre-Pandemic Scaling Formula: Scale the 2017–March 2020 pre-pandemic release (`sddsrvyr == 66`) by `3.2 / (2m + 3.2)` and earlier two-year cycles by `2 / (2m + 3.2)`, avoiding duplicative merging of standalone 2017–2018 releases.
  • Audit Recent Post-Pandemic Sampling Modifications: Inspect CDC NCHS analytical guidance for the August 2021–August 2023 release (`_L`) prior to multi-cycle pooling, verifying altered stratification parameters, reduced oversampling domains, and modified primary sampling unit layouts.

Taylor Series Linearization, Full-Sample Survey Design, and Restricted Cubic Splines

In complex multistage probability sampling, geographical clustering within primary sampling units (`PSUs`) and administrative stratification induce substantial intracluster correlation, violating the independent and identically distributed (`i.i.d.`) assumptions of ordinary least squares and standard logistic regression. NHANES provides masked pseudo-PSUs (`SDMVPSU`) and masked variance strata (`SDMVSTRA`) to facilitate Taylor series linearization. Because pseudo-PSUs are numbered generically (1, 2, or 3) within each stratum, declaring `nest = TRUE` in R `survey::svydesign` is strictly mandatory to prevent the algorithm from artificially pooling identical PSU numbers across different strata into a single cluster. The most damaging error in NHANES publications occurs when researchers subset their analytical dataset prior to initializing the survey design object using `dplyr::filter()` or listwise deletion. Dropping non-eligible respondents from the raw data frame deletes strata and clusters that contain only out-of-scope individuals, corrupting the sampling geometry, deflating degrees of freedom, and producing artificially deflated standard errors and spurious p-values.

Methodological mandate: Quoting the CDC NCHS NHANES Tutorials Variance Estimation Module: "When working with complex survey data such as NHANES, you should never delete or drop records from your analysis dataset before executing your analysis procedures. Instead, use the special statements provided in your software's analysis procedure to perform subgroup analyses. It is important that you do not create a smaller subset of your data based on any non weight-related groups of interest (e.g. demographic, laboratory or examination variables) before executing your analysis procedures." Subpopulation analysis must be executed exclusively via domain estimation by calling `subset()` directly on the instantiated full-sample survey design object.

In computational practice, researchers implement this pipeline using CRAN packages `nhanesA` (`v1.4.1`), `survey` (`v4.5`), and Frank Harrell's `rms` (`v8.2-1`). The protocol begins by declaring `options(survey.lonely.psu = "adjust")` to handle singleton sampling strata resulting from subpopulation isolation. Next, the analyst constructs the design on the complete, unedited sample: `des_full <- svydesign(id = ~SDMVPSU, strata = ~SDMVSTRA, weights = ~wt_multi, nest = TRUE, data = nhanes_merged)`. Subpopulation filtering is subsequently executed strictly on the design object: `des_sub <- subset(des_full, RIDAGEYR >= 20 & RIDEXPRG != 1 & !is.na(exposure) & !is.na(outcome))`. To evaluate non-linear exposure–outcome associations without arbitrary categorization, researchers fit weighted generalized linear models incorporating restricted cubic splines: `fit_rcs <- svyglm(outcome ~ rcs(exposure, 4) + RIDAGEYR + RIAGENDR, design = des_sub, family = quasibinomial())`. Reporting weighted baseline characteristics, survey proportions, and standardized mean differences follows the methodological framework established in our guide on Table 1 baseline characteristics and standardized mean differences in observational studies.

  • Configure Lonely PSU Adjustments: Declare `options(survey.lonely.psu = "adjust")` in R prior to model fitting to prevent computation failure when subpopulation domains isolate a single PSU within a stratum.
  • Initialize Survey Design on the Full Sample: Execute `survey::svydesign(id = ~SDMVPSU, strata = ~SDMVSTRA, weights = ~wt_multi, nest = TRUE, data = nhanes_merged)` on the complete dataset to preserve sampling degrees of freedom.
  • Execute Subgroup Filtering Exclusively via Domain Subsetting: Apply `subset(des_full, ...)` directly to the instantiated survey design object, retaining empty strata and correctly zeroing out non-subpopulation weights.
  • Model Non-Linear Exposure Curves with Restricted Cubic Splines: Incorporate `rms::rcs(exposure, 4)` within `survey::svyglm(..., family = quasibinomial())` or survey-weighted Cox models to flexibly capture non-linear biological dose-response gradients.

UK Biobank Healthy Volunteer Bias, RAP Data Governance, and HumanPen Start Project

Contrasting sharply with NHANES, the UK Biobank was designed as an unweighted prospective cohort rather than a nationally representative probability survey. Between 2006 and 2010, the study recruited 502,493 community-dwelling volunteers aged 40–69 across 22 assessment centers in England, Scotland, and Wales from approximately 9.2 million invited individuals, yielding an overall response rate of 5.5% (Sudlow et al., 2015; Bycroft et al., 2018). In their seminal empirical audit, Anna Fry and colleagues (2017, `PMC5860371`) demonstrated that UK Biobank participants exhibit pronounced "healthy volunteer" selection bias: compared to the UK general population of equivalent age, participants are disproportionately female, less likely to smoke, less likely to be obese, reside in less socioeconomically deprived neighborhoods, and exhibit 46.2% and 55.5% lower all-cause mortality among men and women aged 70–74. Consequently, researchers must never report crude UK Biobank disease rates as national UK prevalence or incidence. However, Fry et al. established that this selection mechanism does not invalidate internal etiological associations: risk factor hazard ratios and odds ratios from Cox and logistic regression models remain highly concordant with nationally representative cohorts and widely generalizable across human populations.

Governance boundary and platform capabilities: Quoting Anna Fry et al. (2017) in the American Journal of Epidemiology: "UK Biobank is not representative of the sampling population; there is evidence of a 'healthy volunteer' selection bias. Nonetheless, valid assessment of exposure-disease relationships may be widely generalizable and does not require participants to be representative of the population at large." Regarding computational boundaries: HumanPen Start Project accepts Excel, CSV, Word, PDF, and zip archives up to 5 GB total per project, executing statistical and data analysis in an isolated sandbox using CPU-based Python or R (analyses originally done in commercial SPSS or Stata are executed reproducibly in Python or R; no GPU training). Registration-gated and restricted databases must be exported by the user under their own license or data transfer agreement before uploading. Individual-level UK Biobank participant data is governed by UK Biobank's Material Transfer Agreement and the DNAnexus-powered UK Biobank Research Analysis Platform (`UKB-RAP`), which strictly prohibits unauthorized external downloads or third-party uploads; researchers must execute individual-level UKB analyses within `UKB-RAP` or authorized enclaves, utilizing external environments only for permitted open public-use CDC NHANES data, synthetic benchmark cohorts, or permitted aggregate summary outputs. Projects confirm requirements and wait for user plan approval before work starts, are reviewed by a verification stage before delivery, and data are encrypted in transit, isolated per project, never used for model training, and kept 6 months (180 days) after last activity with a 3-day reminder and anytime deletion.

Translating these complex cohort workflows into reproducible, audit-ready manuscripts requires a structured execution framework. Attach your data and papers, describe what you need, approve the plan before work starts, and get the reviewed report, charts, and code ready to preview online or download. This end-to-end reproducibility architecture is exemplified in the live public demonstration project on HumanPen Start Project (the International Stroke Trial secondary analysis covering 19,435 patients), where an audited R verification script (`check_with_R.R`) cross-checks Python outputs against R `glm` and `survival` Cox models, illustrating how an automated review verifies analytical logic and code execution. Researchers can request revisions inside the same project while retaining previous versions for complete version auditability across journal revision rounds.

When preparing observational epidemiology manuscripts for peer-reviewed journals, doctoral dissertations, or research grants, deliverables generated through HumanPen Start Project serve strictly as reproducible methodological scaffolds and learning reference drafts. Investigating researchers retain primary personal responsibility for upholding cohort data user agreements, verifying survey weight assignments, testing model proportionality and non-linearity assumptions, and complying with STROBE reporting guidelines for observational studies. Adhering to these computational and governance standards ensures that public health cohort investigations withstand rigorous data editorial audits and advance robust scientific understanding.

Frequently Asked Questions About NHANES and UK Biobank Cohort Workflows

Why must subpopulation filtering use subset() on svydesign objects rather than filtering before svydesign?

In complex multistage survey designs, Taylor series linearization standard errors depend directly on the total number of primary sampling units (`PSUs`) and stratification cells across the entire population sampling frame. If you drop non-subpopulation rows from the data frame prior to calling `survey::svydesign`, entire PSUs or strata containing only out-of-scope individuals are eliminated from the design matrix. This artificially reduces sampling degrees of freedom and treats subpopulation sample sizes within PSUs as fixed constants rather than random variables, underestimating standard errors and inflating type I error rates. Calling `subset()` on an instantiated full-sample `svydesign` object zeroes out the weights of out-of-scope respondents while keeping the geometric architecture of all strata and clusters intact.

How do you choose between WTINT2YR, WTMEC2YR, and subsample weights such as WTSAF2YR in NHANES?

CDC NCHS mandates the Smallest Subpopulation Rule: analysts must select the sample weight corresponding to the smallest subpopulation that contains all variables included in the regression model. Use `WTINT2YR` only when every variable in the analysis is derived exclusively from household interview modules (such as sociodemographic factors, medical history questionnaires, or self-reported physical activity). Use `WTMEC2YR` as soon as any variable requires a Mobile Examination Center visit (including body mass index, blood pressure, DXA scans, or standard complete blood counts). Use specialized subsample weights (such as `WTSAF2YR` for morning fasting glucose and lipids, dietary recall weights `WTDRD1` or `WTDR2D`, or environmental chemical weights) whenever a subsample analyte is included in the model, even if all other covariates are interview or MEC variables.

Can UK Biobank disease incidence or prevalence rates be reported as nationally representative UK health statistics?

No. As demonstrated by Fry et al. (2017) in their comprehensive audit of roughly 500,000 UK Biobank participants, the cohort exhibits substantial "healthy volunteer" selection bias resulting from an overall 5.5% response rate. Participants are more likely to be female, less likely to smoke, less likely to be obese, live in less socioeconomically deprived areas, and experience all-cause mortality rates over 45% lower than the UK general population across identical age brackets. Reporting crude disease percentages from UK Biobank as national UK prevalence misinforms public health policy. However, this selection mechanism does not invalidate internal exposure–disease relationships: hazard ratios from Cox proportional hazards models and odds ratios from logistic models remain widely generalizable across diverse human populations without population-weighting adjustments.

What is the data governance boundary between public CDC NHANES data and UK Biobank participant data on HumanPen Start Project?

CDC NHANES continuous survey files and pre-pandemic datasets are open-access public-use microdata releases. Researchers may freely download `.XPT` or CSV files from CDC servers and upload analytical extracts up to 5 GB to HumanPen Start Project for automated survey weighting, variance estimation, and reproducible pipeline construction. In contrast, UK Biobank individual-level genetic and phenotypic records are governed by UK Biobank's Material Transfer Agreement and the DNAnexus-powered `UKB-RAP` enclave. UK Biobank policy strictly forbids exporting or uploading individual-level participant data to unauthorized third-party platforms. Researchers must conduct individual-level UK Biobank computations within `UKB-RAP` or institutionally approved environments, utilizing external analytical environments strictly for public NHANES files, synthetic mock cohorts, or permitted aggregate summary statistics.

Sources and Methodological Literature

The sampling designs, statistical formulas, variance estimation procedures, and cohort governance guidelines presented in this guide are derived directly from official government documentation, peer-reviewed methodological papers, and software reference manuals:

KEEP READING