# Chi-Square Test of Independence

The **Chi-Square Test of Independence** evaluates whether two categorical variables are statistically associated.

Example questions:
- Is gender related to preference?
- Is treatment type associated with recovery category?

---

# 📌 When to Use
Use this test when:
- Both variables are **categorical**
- Data is in **frequency counts**
- You want to test whether categories are **independent** or **associated**

---

# 📐 How the Test Works (Simple)

The test compares:
- **Observed frequencies** \( O \)
- **Expected frequencies** if variables were independent \( E \)

Test statistic:

$$
\chi^2 = \sum \frac{(O - E)^2}{E}
$$

Expected cell value:

$$
E_{ij} = \frac{(\text{Row total}) (\text{Column total})}{\text{Grand total}}
$$

Degrees of freedom:

$$
df = (r - 1)(c - 1)
$$

---

# 🔬 Numerical Example

| Group | Yes | No |
|-------|-----|----|
| A     | 30  | 20 |
| B     | 10  | 40 |

Totals:
- Row totals: 50, 50  
- Column totals: 40, 60  
- Grand total: 100  

Expected for cell (A, Yes):

$$
E_{A, Yes} = \frac{50 \times 40}{100} = 20
$$

Compute each cell contribution:

(A, Yes): $ (30 - 20)^2 / 20 = 5$

(A, No): $ (20 - 30)^2 / 30 = 3.33$

(B, Yes): $ (10 - 20)^2 / 20 = 5$

(B, No): $ (40 - 30)^2 / 30 = 3.33$


_Total:_
$ \chi^2 = 16.66 $

---

# 🧪 Assumptions
- Data are counts (not means)
- Expected counts ≥ 5 in most cells
- Categories are mutually exclusive

---

# 🧠 Interpretation
A large chi-square value → observed counts differ greatly from expected → **variables are not independent**.

StatInsight provides:
- Test statistic  
- p-value  
- Contingency table  
- Interpretation text  

---

# 🐍 Python Implementation

SciPy:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html

Used in StatInsight:
```python
from scipy.stats import chi2_contingency
chi2, p, dof, expected = chi2_contingency(table)
```

# 📎 Related Tests

- [Multiple Logistic Regression](regression/logistic.md)

- [Multinomial Logistic Regression](regression/multinomial-logistic.md)
