MIMIC-IV and eICU-CRD Cohort Extraction: Survival Analysis and Bias Control

Building critical care cohorts across MIMIC-IV v3.1 and eICU-CRD requires navigating relational joins, time offsets, and time-dependent treatment windows. This guide details how to extract deduplicated patient cohorts, prevent immortal time bias, and structure reproducible survival analyses.

HumanPen Team

· 13 min read

Core Principles for MIMIC-IV and eICU-CRD Cohort Extraction and Survival Modeling

Extracting observational cohorts from intensive care unit (ICU) electronic health records (EHR) such as PhysioNet MIMIC-IV v3.1 and the multi-center eICU Collaborative Research Database (eICU-CRD v2.0) requires addressing three interconnected architectural challenges: navigating multi-tier relational hierarchies (`subject_id` to `hadm_id` to `stay_id`), synchronizing disparate time structures (shifted calendar timestamps versus ICU admission minute offsets), and preventing immortal time bias in time-dependent treatment evaluations. Without rigorous cohort engineering, researchers frequently encounter duplicate patient representations from repeated hospital readmissions, unlinked laboratory events, and spurious treatment effects that fail validation across independent hospital centers.

Critical Care Cohort Rule: Always enforce first-ICU-stay filtering (`first_icu_stay = true`) to satisfy independence assumptions, anchor baseline organ dysfunction to Sepsis-3 consensus definitions (`SOFA >= 2` combined with suspected infection windows), and define treatment exposure strictly through landmark windows or counting-process intervals (`tstart`, `tstop`, `event`) to eliminate immortal time bias.
DimensionMIMIC-IV v3.1 (Single-Center)eICU-CRD v2.0 (Multi-Center)
Data Source and SettingBeth Israel Deaconess Medical Center, Boston, MA (admissions 2008 to 2022)208 US hospitals across 335 ICU units (200,859 unit encounters, 2014 to 2015)
Relational Identifierssubject_id for patient, hadm_id for admission, stay_id for ICU unit stayuniquepid for patient, patienthealthsystemstayid for hospital stay, patientunitstayid for ICU
Event Timing SystemShifted calendar timestamps with consistent interval preservation across tablesInteger minute offsets from ICU admission (unitadmitoffset = 0; negative = pre-ICU)
Derived ConceptsMIT-LCP/mimic-code concepts for Sepsis-3, SOFA, and icustay_detaileICU derived tables and respiratory/vital sign offset tables via eicu-code
Survival Follow-upIn-hospital mortality and out-of-hospital date of death via state vital recordsIn-hospital and ICU discharge status (unitdischargestatus, hospitaldischargestatus)
Access GovernanceCITI training and PhysioNet Credentialed Health Data License 1.5.0CITI training and PhysioNet Credentialed Health Data License 1.5.0

Establishing an empirical cohort across these databases requires harmonizing patient selection with methodological reporting guidelines. Similar to standardized protocols detailed in our analysis of clinical trial secondary analysis and CONSORT workflows, observational critical care research demands transparent exclusion accounting, pre-specified covariate windowing, and clear separation between baseline adjustment variables and time-dependent treatment exposures.

Relational Schema Hierarchy: MIMIC-IV Modules and Multi-Center eICU-CRD Mapping

The architecture of MIMIC-IV v3.1 separates hospital-wide electronic records from high-frequency intensive care charting. The core database is divided into the `hosp` module (containing hospital-wide encounters, laboratory results, billing codes, and pharmacy orders) and the `icu` module (capturing high-density bed-side telemetry, mechanical ventilation settings, and intravenous continuous infusions derived from the MetaVision clinical information system). Linking these modules demands navigating a strict three-tier relational hierarchy: `subject_id` identifies a unique individual; `hadm_id` identifies a distinct hospitalization episode; and `stay_id` isolates a specific continuous ICU bed assignment.

"The hosp module contains data derived from the hospital wide EHR. These measurements are predominantly recorded during the hospital stay, though some tables include data from outside the hospital as well (e.g. outpatient laboratory tests in labevents). Information includes patient and admission details (patients, admissions, transfers), laboratory measurements (labevents, d_labitems), microbiology cultures (microbiologyevents), provider orders (poe, poe_detail), medication administration (emar, emar_detail), medication prescription (prescriptions, pharmacy), hospital billing information (diagnoses_icd, d_icd_diagnoses, procedures_icd, d_icd_procedures, hcpcsevents, d_hcpcs, drgcodes), and hospital service related information (services)."
  • The Outpatient Laboratory Linkage Pitfall: In MIMIC-IV `hosp.labevents`, blood samples drawn in outpatient clinics or the emergency department before official inpatient bed registration often have `hadm_id IS NULL`. Joining `icustays` to `labevents` exclusively on `hadm_id` silently deletes critical baseline physiological values drawn during initial resuscitation; researchers must join on `subject_id` and filter timestamps using `labevents.charttime BETWEEN icustays.intime - INTERVAL '6' HOUR AND icustays.outtime`.
  • First-ICU-Stay De-duplication Requirement: A single patient (`subject_id`) frequently experiences multiple hospitalizations across the 2008 to 2022 collection window, as well as ICU readmissions within the same hospital stay. Evaluating all ICU admissions as independent records introduces clustered observations and survivorship bias; investigators must restrict their cohort to the patient's first hospitalization and first ICU admission by applying `ROW_NUMBER() OVER (PARTITION BY subject_id ORDER BY admittime, intime) = 1` or selecting `first_icu_stay = true` and `first_hosp_stay = true` from `mimic_derived.icustay_detail`.
  • Sepsis-3 and SOFA Standardization: Never extract sepsis cohorts using retrospective ICD-9 or ICD-10 billing codes (`diagnoses_icd`), which suffer from discharge documentation artifacts and omit acute physiological onset times. Instead, query the official `MIT-LCP/mimic-code` repository tables (`sepsis3` and `sofa`), which implement the Singer et al. (2016) consensus criteria by identifying suspected infection windows (antibiotic administration paired with body fluid culture within `-24` to `+72` hours) alongside acute organ failure defined by a baseline change of `SOFA >= 2`.

When validating prognostic models or treatment effect estimates externally, single-center single-hospital datasets like MIMIC-IV must be paired with geographically diverse cohorts. The eICU Collaborative Research Database provides an ideal validation substrate, capturing 200,859 ICU admissions across 208 non-teaching and academic hospitals. However, transitioning from MIMIC-IV to eICU-CRD requires restructuring time from date-time stamps to relative admission minutes.

"The database comprises 200,859 patient unit encounters for 139,367 unique patients admitted between 2014 and 2015. Patients were admitted to one of 335 units at 208 hospitals located throughout the US. Table 1 provides demographics of the dataset, including hospital level characteristics."
Clinical DomainMIMIC-IV v3.1 Concept and FieldeICU-CRD v2.0 Concept and FieldHarmonization Strategy
Patient Demographicspatients.anchor_age, patients.genderpatient.age (string, > 89 grouped), patient.genderParse eICU text age (> 89 set to 90 or 91) and map binary gender indicators
ICU Admission and Dischargeicustays.intime, icustays.outtimepatient.unitadmitoffset (0), patient.unitdischargeoffsetSet eICU admission as t = 0; convert MIMIC interval to elapsed hours or minutes
Bedside Vital Signsicu.chartevents linking d_items (heart rate, MAP)vitalperiodic, vitalaperiodic tablesMatch vital parameter item codes and aggregate into 1-hour or 4-hour median windows
Laboratory Analyteshosp.labevents (valuenum, itemid)lab table (labresult, labname, labresultoffset)Standardize LOINC or item naming, convert conventional units to SI, filter baseline 24h
Acuity and Organ Failuremimic_derived.sofa, mimic_derived.sepsis3apachePatientResult, customized SOFA queriesExtract component SOFA subscores (respiratory, renal, CNS, coagulation, liver, cardio)
Survival Follow-uppatients.dod (state registry), admissions.deathtimepatient.unitdischargestatus, patient.hospitaldischargestatusLimit survival window to in-hospital or 28-day ICU mortality for cross-database parity

Eliminating Immortal Time Bias: Landmark Windows and Counting-Process Models

A pervasive methodological flaw in published critical care literature is immortal time bias, thoroughly dissected by Lévesque et al. (2010 BMJ). In retrospective ICU studies evaluating pharmacological interventions (such as early beta-blockers, statins, hydrocortisone, or renal replacement therapy), researchers frequently define exposure groups dichotomously as patients who ever received the medication during their ICU stay (`ever_treated = 1`) versus those who never received it (`ever_treated = 0`), measuring overall survival from initial ICU admission (`intime`, `t = 0`). Because a patient initiated on continuous renal replacement therapy at hour 36 had to survive at least 36 hours to receive the treatment, that initial survival interval represents immortal time during which death could never occur by definition. Conversely, patients who suffered fulminant clinical deterioration and died at hour 12 are deterministically classified into the untreated cohort. This misclassification generates an entirely spurious protective hazard ratio (`HR = 0.50` to `0.70`), creating an illusion of therapeutic benefit for entirely inactive or even harmful drugs.

"A common task in survival analysis is the creation of start,stop data sets which have multiple intervals for each subject, along with the covariate values that apply over that interval. This function aids in the creation of such data sets."
  • Landmark Analysis Design: Select a fixed, clinically justified landmark time `t_L` following ICU admission (typically 24 hours or 48 hours). Exclude all patients who die, are discharged, or experience the primary outcome prior to `t_L`. Classify treatment exposure strictly based on whether the therapy was initiated within the predefined assessment interval `[0, t_L]`. Reset the survival clock so that follow-up begins precisely at `t_L`. While this approach removes immortal time completely and allows standard Kaplan-Meier plotting, it discards events occurring prior to the landmark and cannot evaluate dynamic therapy alterations after `t_L`.
  • Counting-Process Time-Dependent Cox Formulation: Model treatment exposure as a time-varying covariate using the counting-process formulation `(tstart, tstop, event)`. Every patient enters the observational risk set at `t = 0` as untreated (`trt = 0`). If and when the therapy is initiated at `t = tx_time`, the patient's record is split into an initial unexposed interval `[0, tx_time)` with `trt = 0` and a subsequent exposed interval `[tx_time, end_time)` with `trt = 1`. In R (`survival` `v3.8-13`), this is constructed via `tmerge(data1 = cohort, data2 = cohort, id = stay_id, death = event(followup_hours, died_28d))` followed by `tmerge(data1 = base_df, data2 = tx_table, id = stay_id, on_drug = tdc(tx_start_hours))` and modeled with `coxph(Surv(tstart, tstop, death) ~ on_drug + age + sofa_0h, data = td_df)`.
  • Python Implementation via Lifelines: In Python, time-varying survival regression is implemented using `lifelines` (`v0.30.3`). The structured counting-process table is passed directly into `lifelines.CoxTimeVaryingFitter().fit(td_df, id_col="stay_id", event_col="death", start_col="tstart", stop_col="tstop")`, allowing robust partial likelihood estimation without artificially discarding early ICU mortality.

Reporting survival analysis from observational critical care data demands rigorous verification of statistical assumptions, as detailed in our guide to Kaplan-Meier and Cox regression survival analysis reporting standards. Investigators must report tests for proportional hazards across non-time-varying baseline covariates (such as Schoenfeld residual diagnostics), present absolute event rates alongside adjusted hazard ratios with 95% confidence intervals, and evaluate competing risks such as ICU discharge or withdrawal of life-sustaining therapy using cumulative incidence functions.

End-to-End Analytical Pipeline: From SQL Concepts to Clinical Study Reporting

Executing a peer-review-grade critical care study requires a cohesive analytical pipeline bridging SQL data extraction, missing data imputation, confounding control, and manuscript generation under STROBE and TRIPOD+AI guidelines. In typical workflows, researchers query BigQuery or local PostgreSQL instances using official `mimic-code` scripts, export de-identified cohort matrices, and conduct downstream statistical modeling in Python or R. Maintaining reproducibility requires documenting all software dependency versions, seed values, and transformation scripts.

"We have received inquiries regarding the use of credentialed data (MIMIC-III, MIMIC-IV, MIMIC-CXR) with online services such as GPT. The PhysioNet Credentialed Data Use Agreement explicitly prohibits sharing access to the data with third parties, including sending it through APIs provided by companies like OpenAI, or using it in online platforms like ChatGPT."
  • SQL Derivation via Official Concepts: Run derived concept scripts directly against the `mimiciv_derived` schema. Extract cohort inclusion criteria using `icustay_detail` for age and length of stay filtering, `sepsis3` for acute infection timing, and `first_day_sofa` for baseline organ failure. Never write custom SQL logic for standardized clinical scores where tested community implementations exist.
  • Principled Missing Data Handling: Clinical EHR data exhibit high rates of missingness in laboratory analytes. Verify missing-at-random (MAR) assumptions rather than performing complete-case deletion, which introduces severe selection bias. Implement Multiple Imputation by Chained Equations (MICE) across 5 to 10 imputed datasets, incorporating the Nelson-Aalen cumulative hazard estimator alongside all baseline covariates into the imputation specification.
  • Confounder Adjustment via PSM or IPTW: Address confounding by indication using Propensity Score Matching (PSM) or Inverse Probability of Treatment Weighting (IPTW). Assess post-matching covariate balance by computing standardized mean differences (SMD), ensuring all critical prognostic covariates achieve an SMD < 0.10 before entering the survival outcome model.
  • Computational Support via HumanPen Start Project: When transitioning extracted cohorts into rigorous statistical modeling and manuscript structures, researchers can initiate an analysis workflow through HumanPen Start Project. Under user-managed data governance and applicable PhysioNet DUAs, investigators attach their own exported data files and relevant literature (supporting Excel, CSV, Word, PDF, and zip files up to 5 GB total per project). The platform confirms detailed study requirements and secures user plan approval before computational work starts. All statistical calculations are executed within an isolated CPU-based Python or R sandbox (reproducing models previously designed in SPSS or Stata; restricted databases must be exported under the researcher's own license, with no GPU training). Every analytical output undergoes a verification stage prior to delivery, allowing iterative revisions within the same project workspace while preserving version history. All assets feature transit encryption, project-level data isolation, a 6-month retention window after last activity with a 3-day deletion reminder, and an explicit policy ensuring uploaded materials are never utilized for model training. Deliverables serve as reproducible research and learning reference scaffolds requiring clinical verification.

For an empirical demonstration of reproducible secondary analysis workflows, examine the clinical research workflow analysis comparing MedIECO and HumanPen Projects and the interactive stroke trial secondary analysis demonstration, which executes generalized linear modeling alongside `survival::coxph` and `survival::survdiff` on the 19,435-patient International Stroke Trial cohort under verified analytical pipelines.

Frequently Asked Questions on Critical Care EHR Cohorts

  • How should researchers handle laboratory records in MIMIC-IV where hadm_id is NULL? In the `hosp.labevents` table, tests performed during emergency department triage or outpatient presentation prior to formal inpatient admission frequently lack a valid `hadm_id`. Rather than discarding these records or inner-joining solely on admission identifiers, link records using `subject_id` and restrict the time interval using `labevents.charttime BETWEEN icustays.intime - INTERVAL '6' HOUR AND icustays.intime + INTERVAL '24' HOUR` to capture true baseline admission laboratory values.
  • How are eICU-CRD relative minute offsets reconciled with MIMIC-IV calendar time? MIMIC-IV uses de-identified, patient-specific shifted calendar timestamps where absolute dates are scrambled but true elapsed durations are preserved. In contrast, eICU-CRD uses an integer offset system where `unitadmitoffset = 0` denotes ICU arrival. To harmonize the two in pooled or validation studies, transform MIMIC-IV timestamps into elapsed hours or minutes relative to `icustays.intime`, standardizing both cohorts onto an identical relative time horizon.
  • When is Landmark Analysis preferred over Time-Dependent Cox regression for ICU exposures? Landmark analysis is optimal when the clinical question centers on a predefined decision window (e.g., evaluating 48-hour resuscitation bundles on subsequent 28-day survival) and when presenting intuitive Kaplan-Meier survival curves is necessary for clinical audiences. Time-dependent Cox regression is essential when therapies are initiated dynamically across the entire ICU stay or when excluding patients who die before a landmark time would induce unmanageable selection bias.
  • What are the data governance boundaries for PhysioNet credentialed datasets under License 1.5.0? Access to full MIMIC-IV and eICU-CRD files requires individual CITI certification and a signed PhysioNet Credentialed Data Use Agreement. Per PhysioNet's official policy, credentialed patient-level microdata must never be uploaded to public third-party LLM APIs. Researchers can develop and debug code locally using the publicly downloadable 100-patient MIMIC-IV Demo, or run vetted scripts within secure, private computing environments where the researcher retains sole credentialed control.

Primary Documentation and Verified Methodological References

KEEP READING