# Kaplan–Meier Survival Analysis

The **Kaplan–Meier estimator** measures the probability of surviving (or remaining event-free) past a given time point. It correctly handles **censored observations** — participants who did not experience the event before the study ended.

---

## 📌 When to Use
- Time-to-event data (e.g. survival time, time to relapse, time to recovery)
- A binary event variable (occurred / did not occur)
- Comparing survival curves between groups (log-rank test)

---

## 📐 Estimator

$$
\hat{S}(t) = \prod_{t_i \leq t} \left(1 - \frac{d_i}{n_i}\right)
$$

Where:
- $d_i$ = number of events at time $t_i$
- $n_i$ = number at risk just before $t_i$

---

## 🔬 What StatInsight Reports
- Kaplan–Meier survival curve per group
- Median survival time with 95% CI per group
- Log-rank test p-value (comparison between groups)
- Number at risk table

---

## 🧩 Group Comparison
When a binary grouping variable is provided, StatInsight automatically runs the **log-rank test** to compare survival curves between groups.

---

## 🧪 Assumptions
- Events are independent
- Censoring is non-informative (censored subjects have the same survival probability as those who remain)
- Survival probabilities are consistent over the study period

---

## 🧠 Interpretation
- **S(t) = 0.7 at 12 months**: 70% of subjects are event-free at 12 months
- **Curves that separate early and remain apart**: strong group difference
- **Log-rank p < 0.05**: statistically significant difference in survival between groups

---

## 🐍 Python Implementation

```python
from lifelines import KaplanMeierFitter
from lifelines.statistics import logrank_test

kmf = KaplanMeierFitter()
kmf.fit(durations=time, event_observed=event)
kmf.plot_survival_function()

result = logrank_test(time_A, time_B, event_A, event_B)
print("p =", result.p_value)
```

---

## 📎 Related Tests

[Mann–Whitney U Test](/statistics/ttests/mann-whitney.md) — non-parametric two-group comparison

[Log-Rank Test](https://lifelines.readthedocs.io/) — automatically included when groups are present
