How to Clean and Weight CHARLS, CFPS, and HRS Longitudinal Panels
Merging multi-wave CHARLS, CFPS, or HRS data demands rigorous handling of spouse age eligibility, oversampled provincial frames, missing sentinels, and complex survey weights. Here is how to structure an end-to-end longitudinal workflow that withstands peer review.
HumanPen Team
· 13 min read
Harmonizing Longitudinal Aging and Household Panel Surveys: CHARLS, CFPS, and HRS
Empirical investigations in public health, health economics, gerontology, and family sociology rely heavily on large-scale longitudinal microdata archives, most prominently the China Health and Retirement Longitudinal Study (`CHARLS`, covering respondents aged 45 and older across six waves), the China Family Panel Studies (`CFPS`, tracking all-age households, adults, and children biennially), and the US Health and Retirement Study (`HRS` and the cumulative `RAND HRS Longitudinal File`, tracking respondents aged 51 and older across sixteen biennial waves from 1992 to 2022). Navigating these multi-gigabyte survey archives requires a disciplined four-stage pipeline: harmonizing longitudinal person keys across evolving multi-wave releases, recoding Stata extended missing values and negative survey sentinels using Python `pyreadstat`, defining complex multi-stage survey design weights with stratum nesting in R `survey::svydesign(..., nest = TRUE)`, and modeling non-random panel dropout through Inverse Probability of Attrition Weighting (`IPAW`).
Core takeaway: The most frequent methodological errors in CHARLS, CFPS, and HRS manuscripts stem from overlooking core survey design architecture: analyzing non-age-eligible spouses as target aging respondents, pooling CFPS data without national post-stratification weights that correct for its five oversampled large provinces, and subsetting raw data frames prior to defining survey design objects. Constructing design objects on the complete sample and executing subpopulation analysis strictly via domain estimation preserves design geometry and ensures unbiased standard errors.
While comparative platforms such as the Gateway to Global Aging Data (`https://g2aging.org/`) provide valuable harmonized indices across international aging studies, researchers testing custom behavioral, clinical, or policy mechanisms must directly process raw survey waves. Unweighted ordinary least squares regressions or naive listwise deletion of incomplete records inevitably introduce severe sample selection bias, distorted parameter estimates, and deflated standard errors. Establishing reproducible end-to-end analytical pipelines—moving deterministically from raw microdata archives to peer-reviewed regression tables—follows the rigorous data governance principles outlined in our methodological guide on building reproducible empirical papers from public microdata.
Multi-Wave Merging and Missing-Value Protocol in Stata DTA and Python Pyreadstat
Constructing longitudinal panel trajectories begins with identifier verification across survey waves. In CHARLS, individuals are tracked using composite `ID` variables linking community, household, and individual records from the 2011 baseline through the 2021–2023 Wave 6 national release. In CFPS, individuals maintain an invariant personal identifier `pid`, but household identifiers diverge over time: baseline households are designated by `fid10`, whereas subsequent household splits and formations receive wave-specific `fid` codes. In HRS and RAND HRS, the invariant longitudinal individual key is `HHIDPN`, formed by concatenating the six-digit household identifier `HHID` and three-digit person number `PN`. Merging datasets across waves without explicitly validating these keys leads to catastrophic record misalignment across waves.
| Longitudinal Survey and Gateway Resource | Target Cohort and Survey Coverage | Unique Panel Subject Identifiers | Missing Value Sentinels and Stata Encoding | Critical Longitudinal Data Cleaning Trap |
|---|---|---|---|---|
| CHARLS (Peking University) | Chinese residents aged 45 and older and spouses of any age across 28 provinces (Wave 1 in 2011 through Wave 6 in 2021-2023) | Household and individual ID (combined community, household, and person key) | Stata extended missing codes (.d for don't know, .r for refusal, .s for skip, .m for missing) | Retaining non-age-eligible spouses under age 45 without explicit age filtering |
| CFPS (ISSS Peking University) | All-age Chinese communities, families, and individuals (baseline in 2010 with biennial waves through 2022) | Permanent person identifier pid (with fid10 at baseline and branching fid at follow-up waves) | Negative numeric sentinels (-8 for don't know, -9 for refusal, -1 for missing, -2 for not applicable) | Unweighted pooling of the 5 oversampled large provinces (Shanghai, Liaoning, Henan, Gansu, Guangdong) |
| HRS and RAND HRS (UM and RAND) | US adults aged 51 and older across 7 entry cohorts and spouses of any age (16 core waves across 1992-2022) | Concatenated longitudinal identifier HHIDPN (combining household HHID and person PN) | Stata extended missing codes in core files and pre-imputed economic variables in RAND releases | Reusing PSU identifier RAEHSAMP across strata RAESTRAT without setting nest = TRUE |
| Gateway to Global Aging Data (Harmonized CHARLS and HRS) | Internationally harmonized aging cohorts spanning CHARLS, HRS, SHARE, and ELSA releases | Standardized respondent and spouse identifiers (ID and HHIDPN) | Pre-harmonized clean missing indicators with standardized longitudinal variable names | Assuming pre-calculated survey weights account for custom multi-wave subpopulation attrition |
A second critical data cleaning pitfall lies in software handling of missing-value encodings. Stata `.dta` files utilized by CHARLS and HRS employ extended missing values (`.d` for don't know, `.r` for refusal, `.s` for skip logic, `.m` for missing). When loading `.dta` files into Python using `pyreadstat.read_dta(..., user_missing=True)`, these codes are preserved within `meta.missing_user_values` rather than silently transformed into generic null values. Conversely, CFPS utilizes negative numeric sentinels (`-8` for don't know, `-9` for refusal, `-1` for missing, `-2` for not applicable). If an analyst fails to recode negative sentinels to `np.nan` before computing arithmetic means or running regressions, Python interprets `-9` as a literal numeric income, cognitive score, or CES-D depression score. Researchers evaluating incomplete observations should benchmark their strategy against the diagnostic standards outlined in our guide on handling missing data with MICE versus complete case analysis.
- Construct Invariant Longitudinal Identifiers: Verify that individual trajectories merge strictly on validated person keys (`ID` in CHARLS, `pid` in CFPS, `HHIDPN` in HRS), tracking branching family identifiers (`fid`) separately from person records.
- Recode Stata Extended Missing Values and Negative Sentinels: Configure `pyreadstat.read_dta(..., user_missing=True)` to audit survey non-response reasons, and systematically replace CFPS negative sentinels (`-8`, `-9`, `-1`, `-2`) with null floating-point values before mathematical operations.
- Filter Target Age Cohorts While Auditing Spouse Inclusion: Explicitly enforce survey age eligibility thresholds (`age >= 45` in CHARLS; `age >= 51` or `age > 50` in HRS) to separate target aging respondents from non-age-eligible interview spouses.
- Harmonize Measurement Scales and Recall Intervals Across Waves: Reconcile evolving survey instruments, questionnaire skip patterns, and diagnostic scales (such as ADL/IADL functional limitations and CES-D depression batteries) to ensure longitudinal construct validity across panel waves.
Complex Survey Design, Post-Stratification Weights, and Subpopulation Domain Analysis in R Survey
Observational surveys never represent simple random samples; inferring population parameters requires modeling their multi-stage probability designs. As documented in the CHARLS cohort profile by Zhao et al. (2014), CHARLS selected 150 county-level units across 28 provinces using probability-proportional-to-size (`PPS`) sampling, followed by 450 villages/resident committees, surveying roughly 10,000 households and 17,500 individuals at baseline. CFPS employs a three-stage implicit stratification design covering 25 provinces/municipalities (Xie and Hu, 2014), but critically incorporates five oversampled large provincial frames (Shanghai, Liaoning, Henan, Gansu, Guangdong) alongside a small 20-province frame. HRS employs a multi-stage area probability design with geographical stratification, clustering, and oversampling of Black and Hispanic adults and Florida residents (Sonnega et al., 2014).
Methodological note: Quoting the official R survey package documentation by Thomas Lumley (2004): "By default, svydesign assumes that all PSUs, even those in different strata, have a unique value of the id variable. This allows some data errors to be detected. If your PSUs reuse the same identifiers across strata then set nest=TRUE." In HRS, primary sampling units (`RAEHSAMP`) are numbered 1 and 2 within each sampling stratum (`RAESTRAT`). Omitting `nest = TRUE` mistakenly pools all cluster 1s nationwide into a single giant cluster. Furthermore, analysts must never pre-filter data frames before calling `svydesign`; subpopulation analyses must be executed on the full-sample design object using `subset(des, age >= 45)` to retain empty strata and compute correct Taylor-series standard errors.
Weight selection must align with the specific analytical sample and survey design. In CFPS, analyzing the pooled sample without post-stratification weights heavily over-represents the five oversampled provinces; researchers must apply national rescaled cross-sectional or panel weights (`nat`) to generate nationally representative estimates. In CHARLS, researchers must select between individual survey weights (`ind_weight` with or without household and individual non-response adjustments) and specialized biomarker/blood weights depending on the clinical outcomes examined. In HRS, under-51 spouses receive zero respondent weight (`RwWTRESP = 0`) until they age into eligibility. In R, generalized linear models for complex survey data should be estimated using `survey::svyglm(..., family = quasibinomial())` or `quasipoisson()` to account for survey weighting while preventing non-integer pseudo-count warnings, presenting baseline characteristics in accordance with standard reporting practices for Table 1 baseline characteristics and standardized mean differences in observational studies.
- Initialize Full-Sample Survey Design Objects: Define the sampling architecture on the unedited, full-sample dataset using `survey::svydesign(ids = ~psu, strata = ~strata, weights = ~weight, nest = TRUE, data = full_df)`.
- Execute Subpopulation Filtering Exclusively via Domain Subsetting: Apply `subset(design_object, age >= 45)` directly to the instantiated survey design to preserve stratum degrees of freedom and Taylor-series linearization matrices.
- Adjust for Singleton Sampling Strata: Declare `options(survey.lonely.psu = "adjust")` or `"certainty"` in R to prevent execution errors when subpopulation filtering isolates a single PSU within a stratum.
- Specify Quasi-Likelihood Families for Survey GLMs: Estimate regression equations using `survey::svyglm` with `quasibinomial()` or `quasipoisson()` link functions to yield design-consistent point estimates and robust sandwich standard errors.
Panel Attrition Bias, Inverse Probability Weighting, and End-to-End Execution in HumanPen Start Project
Over multi-wave longitudinal follow-up—spanning up to six waves in CHARLS, seven waves in CFPS, and sixteen waves across thirty years in HRS—panel attrition from biological mortality, physical relocation, cognitive impairment, and survey refusal inevitably erodes sample integrity. Analyzing only respondents who survive and participate across all waves (complete-case panel analysis) induces severe survivor bias and attrition selection bias. To restore population representativeness, researchers must implement stabilized Inverse Probability of Attrition Weighting (`IPAW`). For each wave `t`, analysts model the conditional probability of retention `P(R_it = 1 | R_it-1 = 1, L_it-1)` using pooled logistic regressions conditioned on baseline sociodemographics, functional status, and prior health indicators `L_it-1`. The cumulative longitudinal weight compounds as `w_i_total = w_i0 × ∏_t w_it_IPAW`, with extreme weights trimmed at the 1st and 99th percentiles to avoid variance inflation.
Platform capabilities and boundaries: HumanPen Start Project supports Excel, CSV, Word, PDF, and zip archives up to 5 GB total per project, executing statistical and data analysis in an isolated sandbox using Python or R (analyses originally done in commercial SPSS or Stata are executed reproducibly in Python or R). Registration-gated databases such as CHARLS, CFPS, HRS, CNKI, or Wind must be exported by the user under their own data agreement before uploading; GPU training is not supported. Projects confirm requirements and wait for user plan approval before work starts, are reviewed by an automated second 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.
Executing these multi-wave cleaning, weighting, and econometric pipelines requires an integrated, verifiable research environment. 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), where a standalone R verification script (`check_with_R.R`) cross-checks Python outputs against R `glm` logistic and `survival` Cox regression models, illustrating how an audited R cross-check script accompanies the report. Researchers can request revisions inside the same project while retaining previous versions, ensuring full auditability across journal revision rounds.
When preparing manuscripts for peer review, doctoral dissertations, or scientific grants, deliverables generated through HumanPen Start Project serve strictly as reproducible methodological scaffolds and learning reference drafts. Academic researchers maintain primary personal responsibility for verifying survey data user agreements, auditing model specifications, inspecting code logic, and validating causal identification assumptions. Adhering to these computational standards guarantees that longitudinal microdata investigations withstand rigorous data editorial audits and advance robust scientific understanding.
Frequently Asked Questions About CHARLS, CFPS, and HRS Longitudinal Workflows
Why do respondents under age 45 appear in CHARLS and under age 50 in HRS datasets?
Both CHARLS and HRS employ household-based sampling protocols where the age-eligible primary respondent and their spouse or partner are interviewed together, regardless of the spouse's age. Furthermore, HRS utilizes a steady-state replenishment design where new birth cohorts are enrolled every six years at ages 51 to 56. Spouses who have not yet reached the age eligibility threshold receive an individual respondent weight of zero (`RwWTRESP = 0`) until they age into the cohort. Analysts studying aging populations must explicitly filter the sample for `age >= 45` in CHARLS or `age >= 51` (or `age > 50`) in HRS to prevent non-age-eligible spouses from biasing age-specific estimates.
Why does unweighted regression on CFPS data introduce severe geographic bias?
The CFPS sampling frame intentionally oversamples five large provinces (Shanghai, Liaoning, Henan, Gansu, Guangdong) to allow for independent provincial-level population inference, alongside a nationally representative small frame covering twenty additional provinces. In an unweighted pooled sample, individuals from these five provinces represent a much larger share of observations than their true proportion in the national Chinese population. To make valid national inferences, researchers must incorporate CFPS national post-stratification cross-sectional or panel weights (`nat`), which rescale provincial contributions to reflect true census distributions.
Why must subpopulation filtering use subset() on svydesign objects rather than filtering before svydesign?
In complex multi-stage survey sampling, the standard errors of estimators depend on the total number of primary sampling units (`PSUs`) and stratification cells in the population sampling frame. If a researcher drops non-subpopulation rows from the data frame before calling `survey::svydesign`, entire PSUs or strata containing only out-of-scope respondents are deleted from the design matrix. This artificially reduces degrees of freedom and biases Taylor-series linearization variance calculations. Calling `subset()` on an instantiated full-sample `svydesign` object zeroes out the weights of out-of-scope units while preserving the full geometric structure of clusters and strata.
How do you prevent negative survey sentinels from contaminating statistical calculations in Python?
Survey organizations frequently encode non-substantive responses using negative integers (such as `-8` for don't know, `-9` for refusal, `-1` for missing, and `-2` for not applicable in CFPS) or Stata extended missing values (`.d`, `.r`, `.s`, `.m` in CHARLS and HRS). When reading Stata `.dta` files with `pyreadstat.read_dta(..., user_missing=True)`, extended missing codes are captured in `meta.missing_user_values`. However, negative integer sentinels are treated as valid numeric values by default in pandas and numpy. Researchers must execute explicit dictionary mapping or `.replace()` transformations to recode all negative sentinels to `np.nan` before computing summary statistics, scales, or regression models.
Sources and Methodological Literature
The survey cohort profiles, sampling architectures, and computational implementations detailed in this guide are drawn directly from peer-reviewed methodological papers, official survey portal documentation, and statistical software reference manuals:
- Zhao et al. (2014, International Journal of Epidemiology) — Cohort Profile: The China Health and Retirement Longitudinal Study (CHARLS) — Foundational cohort profile documenting PPS sampling, county and village selection, and baseline survey design; supported by the Official CHARLS Portal (Peking University) and the CHARLS Data Release Index.
- Xie & Hu (2014, Chinese Sociological Review) — An Introduction to the China Family Panel Studies (CFPS) — Reference introduction detailing three-stage sampling, five-province oversampling, and multi-module survey structures; supported by the Official CFPS Portal (ISSS, Peking University) and the CFPS Public Data Access Documentation.
- Sonnega et al. (2014, International Journal of Epidemiology) — Cohort Profile: The Health and Retirement Study (HRS) — Cohort profile detailing multi-stage area probability sampling, steady-state replenishment cohorts, and weight design; supported by the RAND HRS Longitudinal File Documentation Portal.
- Gateway to Global Aging Data (USC CESR / NIA) — Harmonized data portal providing cross-national harmonized variables, codebooks, and survey documentation across CHARLS, HRS, SHARE, and ELSA; supported by the Harmonized Data Overview.
- Lumley (2004, Journal of Statistical Software) — Analysis of Complex Survey Samples — Foundational methodology for complex survey analysis in R, supplemented by CRAN manuals for survey::svydesign, survey::svyglm, and the R Survey Package Homepage.
- Pyreadstat Documentation & GitHub Repository (Fajardo / Roche) — Technical reference for reading SAS, SPSS, and Stata `.dta` files in Python with user-defined missing value handling; supported by the Pyreadstat GitHub Repository.
KEEP READING