alterlab-missing-data

$npx mdskill add AlterLab-IEU/AlterLab-Academic-Skills/alterlab-missing-data

Handles missing data using MICE or FIML with proper pooling.

  • Forces explicit MCAR/MAR/MNAR mechanism statement before imputation.
  • Uses statsmodels MICE in Python or R mice via Rscript.
  • Warns that single imputation understates standard errors without Rubin's rules.
  • Returns pooled estimates and standard errors from multiple imputations.

SKILL.md

.github/skills/alterlab-missing-dataView on GitHub ↗
---
name: alterlab-missing-data
description: "Handles missing data with principled methods — forces an explicit MCAR / MAR / MNAR mechanism statement, then applies multiple imputation by chained equations (MICE) with Rubin's-rules pooling of estimates and standard errors, or full-information maximum likelihood (FIML) where a likelihood/SEM model applies. Uses statsmodels MICE / MICEData in Python or the field-standard R mice via Rscript, and warns that single (mean/regression) imputation and scikit-learn's IterativeImputer return one completed dataset without Rubin's-rules pooling, so they understate standard errors if used as multiple imputation. Use when a dataset has missing values, when choosing an imputation strategy, or when reporting how missingness was handled. For general modeling on complete data prefer alterlab-statistical-analysis; for latent-variable models with FIML prefer alterlab-sem-psychometrics. Part of the AlterLab Academic Skills suite."
license: MIT
allowed-tools: Read Bash(python:*)
compatibility: "Requires (declare in-session, no runtime install on Anthropic API): Python statsmodels>=0.14 (statsmodels.imputation.mice), pandas; scikit-learn IterativeImputer only for single imputation (NOT Rubin pooling) — OR the field-standard R mice>=3.19 via Rscript (mice/with/pool). Runs locally via `uv run python` / `Rscript`; no API key."
metadata:
    skill-author: AlterLab
    version: "1.0.0"
    depends_on: "alterlab-statistical-analysis (complete-data modeling), alterlab-sem-psychometrics (FIML for latent models); audited by alterlab-ssci-inference-gate"
---

# Missing Data — Name the Mechanism, Impute Multiply, Pool by Rubin's Rules

**Skill type: ANALYSIS MODULE.** Missing data is not a nuisance to delete or fill with a mean.
The discipline: state the **missingness mechanism**, then use a method whose uncertainty is honest —
multiple imputation with **Rubin's-rules pooling**, or FIML. The dangerous shortcut is single
imputation, which treats guessed values as observed and understates standard errors.

## Core Mission

```
STATE THE MECHANISM (MCAR / MAR / MNAR). MULTIPLY IMPUTE AND POOL BY RUBIN'S RULES —
SINGLE IMPUTATION FAKES CERTAINTY IT DOESN'T HAVE.
```

## When to Use This Skill

- "My dataset has missing values — how should I handle them?"
- "Should I use multiple imputation? How many imputations?"
- "How do I pool results across imputed datasets?"
- "Is mean imputation / listwise deletion okay here?"

### Does NOT Trigger

| The request is really about… | Route to | Why not this skill |
|---|---|---|
| Modeling on already-complete data | `alterlab-statistical-analysis` / `alterlab-statsmodels` | No missingness to handle. |
| FIML inside an SEM / latent-variable model | `alterlab-sem-psychometrics` | That skill fits the latent model with FIML. |
| Survey weights / design (a different kind of "adjustment") | `alterlab-survey-analysis` | Design-based inference, not imputation. |
| Whether the study design is sound | `alterlab-ssci-design-gate` | Design routing. |

## Step 1 — state the mechanism (Rubin)

| Mechanism | Meaning | Consequence |
|-----------|---------|-------------|
| **MCAR** | missingness independent of everything | listwise deletion is unbiased (but wasteful) |
| **MAR** | missingness depends on *observed* data | MI / FIML are valid (the workhorse assumption) |
| **MNAR** | missingness depends on the *unobserved* value itself | needs a selection / pattern-mixture model + sensitivity analysis |

The mechanism is an **assumption**, largely untestable (MAR vs MNAR especially) — state it and
justify it; inspect the missingness pattern (`mice::md.pattern`) and test MCAR (Little's test) as
supporting evidence, not proof.

## Step 2 — multiple imputation with Rubin's-rules pooling

Create m completed datasets (each imputes with added noise reflecting uncertainty), analyze each,
then **pool**: the point estimate is the mean across imputations; the SE combines *within*-imputation
and *between*-imputation variance (Rubin's rules), so it honestly reflects imputation uncertainty.

**Python — statsmodels MICE:**
```python
from statsmodels.imputation import mice
imp = mice.MICEData(df)                                  # chained-equations imputer over the frame
fit = mice.MICE("y ~ x1 + x2", sm.OLS, imp).fit(n_burnin=10, n_imputations=20)
fit.summary()                                            # pooled estimates + SEs (Rubin's rules)
```

**R — mice (field standard):**
```r
library(mice)
md.pattern(data)                                         # inspect the missingness pattern
imp  <- mice(data, m = 20, method = "pmm")               # m completed datasets
fit  <- with(imp, lm(y ~ x1 + x2))
summary(pool(fit))                                       # Rubin's-rules pooling (fmi, lambda, df)
```

**FIML** — for likelihood/SEM models under MAR, full-information ML uses all available data without
explicit imputation; route to `alterlab-sem-psychometrics` when the model is latent-variable.

## The single-imputation trap (verified caveat)

- **Mean / regression / single imputation** treats imputed values as if observed → **biased,
  understated SEs**. Not acceptable as a final analysis.
- **scikit-learn `IterativeImputer`** returns a **single** completed dataset and does **not** pool by
  Rubin's rules — the sklearn docs say so explicitly. It is fine for a prediction pipeline, but using
  it as "multiple imputation" for inference understates uncertainty. If you must, run it repeatedly
  with `sample_posterior=True` and different seeds and pool manually — but `mice`/statsmodels MICE do
  this correctly out of the box.

## How many imputations (m)

Rule of thumb: m at least the **percentage of incomplete cases** (higher fraction of missing
information → larger m); modern guidance often uses m ≈ 20–50. Report m and the fraction of missing
information (FMI).

## Reporting checklist

```
MECHANISM:   MCAR / MAR / MNAR — stated and justified; pattern inspected (md.pattern)
METHOD:      MICE (m, imputation model) with Rubin's-rules pooling | FIML | (deletion only if MCAR)
POOLING:     estimates + SEs pooled by Rubin's rules; report FMI
SENSITIVITY: for MNAR, a sensitivity analysis (selection / pattern-mixture)
```

## References

- `references/mechanisms_and_pooling.md` — MCAR/MAR/MNAR detail, Rubin's-rules math, FIML vs MI, m guidance, the sklearn caveat.

Part of the AlterLab Academic Skills suite.

More from AlterLab-IEU/AlterLab-Academic-Skills

SkillDescription
alterlab-abm-mesaBuilds agent-based models of social systems with Mesa 3 — the current AgentSet API (model.agents.shuffle_do('step'), auto-assigned unique_id, mandatory super().__init__(seed=...)), cell spaces (mesa.discrete_space OrthogonalMooreGrid / classic mesa.space grids), the DataCollector, batch_run parameter sweeps, and SolaraViz — for emergence, segregation, diffusion, opinion dynamics, and cooperation models. It uses the Mesa 3.x API (the old mesa.time schedulers like RandomActivation are removed) and treats the model as a generative theory to be validated, not just run. Use when the request mentions an agent-based model, Mesa, simulating interacting agents, or emergent macro behavior from micro rules. For discrete-event (queueing/process) simulation prefer alterlab-simpy; for reinforcement learning prefer alterlab-stable-baselines3. Part of the AlterLab Academic Skills suite.
alterlab-academic-careerPrepares academic career documents and professional-development materials for faculty and researchers. Use when drafting academic CVs, research statements, teaching philosophies, diversity statements, faculty-position cover letters, tenure dossiers, promotion narratives, academic portfolios, or mentorship statements, and when planning conference-networking strategy, building academic web presence, setting up ORCID profiles, or understanding impact metrics. Part of the AlterLab Academic Skills suite.
alterlab-accreditation-aolScaffolds program-level Assurance-of-Learning (AoL) documentation for AACSB (2020 Standard 5) and ABET (Criterion 3 Student Outcomes, Criterion 4 Continuous Improvement) accreditation — program learning outcomes / competency goals, curriculum-to-outcome mapping matrices, direct- and indirect-assessment plans, rubric design, and closing-the-loop continuous-improvement narratives — and validates the structure of an outcome-mapping matrix with scripts/aol_matrix.py. Use when the user needs AACSB or ABET assurance-of-learning material, a program-learning-outcomes set, a curriculum/outcome map or coverage matrix, a direct/indirect assessment plan, a closing-the-loop report, or accreditation self-study text. For single-course design or course rubrics prefer alterlab-teaching-design; for post-award grant reports prefer alterlab-grant-reporting. Part of the AlterLab Academic Skills suite.
alterlab-adaptyvSubmits and tracks protein-testing experiments on the Adaptyv Bio Foundry cloud lab (wet-lab validation), and optimizes protein sequences before submission with computational tools (NetSolP, SoluProt, SolubleMPNN, ESM). Use when designing proteins that need wet-lab validation - binding/affinity screening, expression testing, thermostability, or fluorescence assays - or when submitting experiments to the Foundry API, browsing the target catalog, tracking experiment status, retrieving results, or pre-screening sequences for solubility/expression. Triggers on "Adaptyv", "Foundry API", "cloud lab", "biolayer interferometry / BLI", "wet-lab validation". Part of the AlterLab Academic Skills suite.
alterlab-aeonRuns time series machine learning with the aeon library — classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search via scikit-learn compatible APIs. Use when working with temporal data, sequential patterns, or time-indexed observations (univariate or multivariate) that need specialized algorithms beyond standard ML approaches. Part of the AlterLab Academic Skills suite.
alterlab-akademik-tesvikComputes the annual Turkish academic-incentive (akademik teşvik) score for Devlet (state) university öğretim elemanı (academic staff) from a classified activity list, applying the verified Akademik Teşvik Ödeneği Yönetmeliği (2018/11834) Faaliyet Hesaplama Tablosu headline puanları (Proje 20, Araştırma 15, Yayın 30, Patent 30, Atıf 30, Tebliğ 20, Ödül 20) with the k (author-count), p (Q1 1/Q2 0.8/Q3 0.5/Q4 0.25), and r (project-role) coefficients via türü puanı = Σ(faaliyet oranları) × headline (MADDE 8/2), then enforcing the per-type headline ceilings, the 100 cap (MADDE 8/3), and the net-30 payment gate (MADDE 10/3) in a deterministic scripts/tesvik_score.py. Use when the user wants to calculate akademik teşvik puanı, check the en az 30 (net-30) threshold, apply TABLO 4 ceilings, or estimate teşvik eligibility; keeps its coefficients separate from doçentlik scoring. For doçentlik point eligibility prefer alterlab-docentlik-eligibility. Part of the AlterLab Academic Skills suite.
alterlab-alpha-vantageAccesses real-time and historical stock market data, forex rates, cryptocurrency prices, commodities, economic indicators, and 50+ technical indicators via the Alpha Vantage API (requires a free API key from alphavantage.co). Use when fetching stock prices (OHLCV), company fundamentals (income statement, balance sheet, cash flow), earnings, options data, market news/sentiment, insider transactions, GDP, CPI, treasury yields, gold/silver/oil prices, Bitcoin/crypto prices, forex exchange rates, or calculating technical indicators (SMA, EMA, MACD, RSI, Bollinger Bands). Part of the AlterLab Academic Skills suite.
alterlab-alphafoldPredict protein 3D structures with AlphaFold2 via ColabFold — MMseqs2-accelerated MSAs, monomer and AlphaFold2-Multimer complex folding, and confidence-based validation (pLDDT, pTM/ipTM, PAE). Use when folding a protein sequence or complex from FASTA, generating a predicted structure with confidence metrics, ranking models, or checking self-consistency of a design. For co-folding a protein WITH a small-molecule ligand or predicting binding affinity prefer alterlab-boltz; for antibody–antigen or one-FASTA multi-entity complexes prefer alterlab-chai; to LOOK UP an already-computed structure prefer alterlab-alphafold-db; for ESM embeddings or inverse folding prefer alterlab-esm. Part of the AlterLab Academic Skills suite.
alterlab-alphafold-dbAccess the AlphaFold DB of 200M+ AI-PREDICTED protein structures — retrieve models by UniProt accession, download PDB/mmCIF files, and analyze prediction confidence metrics (pLDDT, PAE). Use when a UniProt ID needs a computationally predicted 3D structure or when no experimental structure exists, for homology modeling, protein engineering, or structure-based drug discovery; for EXPERIMENTALLY determined structures (X-ray, cryo-EM, NMR) prefer alterlab-pdb, and for protein sequences, annotations, or accession ID mapping prefer alterlab-uniprot instead. Part of the AlterLab Academic Skills suite.
alterlab-anndataBuild, slice, concatenate, read, and write AnnData annotated data matrices (obs, var, X, layers, obsm, uns) — the scverse data STRUCTURE, not an analysis pipeline. Use when creating or wrangling .h5ad/zarr files, managing cell and gene annotations, concatenating batches, or handling layers/obsm/backed-mode; for the QC, normalization, clustering, UMAP, and differential-expression analysis pipeline prefer alterlab-scanpy instead, and for RNA velocity from spliced/unspliced layers prefer alterlab-scvelo instead. Part of the AlterLab Academic Skills suite.