Add agent skills under .agents/skills for Codex

Copy of the project skills (.claude/skills is gitignored) so Codex on
other machines picks them up; skills-lock.json records their sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 16:09:25 +00:00
parent 5a6fb2fc8c
commit 954bbf0127
135 changed files with 39094 additions and 0 deletions

View File

@@ -0,0 +1,377 @@
# Statistical Assumptions and Diagnostic Procedures
This document provides comprehensive guidance on checking and validating statistical assumptions for various analyses.
## General Principles
1. **Always check assumptions before interpreting test results**
2. **Use multiple diagnostic methods** (visual + formal tests)
3. **Consider robustness**: Some tests are robust to violations under certain conditions
4. **Document all assumption checks** in analysis reports
5. **Report violations and remedial actions taken**
## Common Assumptions Across Tests
### 1. Independence of Observations
**What it means**: Each observation is independent; measurements on one subject do not influence measurements on another.
**How to check**:
- Review study design and data collection procedures
- For time series: Check autocorrelation (ACF/PACF plots, Durbin-Watson test)
- For clustered data: Consider intraclass correlation (ICC)
**What to do if violated**:
- Use mixed-effects models for clustered/hierarchical data
- Use time series methods for temporally dependent data
- Use generalized estimating equations (GEE) for correlated data
**Critical severity**: HIGH - violations can severely inflate Type I error
---
### 2. Normality
**What it means**: Data or residuals follow a normal (Gaussian) distribution.
**When required**:
- Small-sample normal-theory t/ANOVA inference: the relevant errors (paired differences for paired tests), not arbitrary pooled data
- Linear regression: normal errors support exact finite-sample t/F inference; coefficient estimation itself does not require normal outcomes or predictors
- Some correlation tests (Pearson)
**How to check**:
**Visual methods** (primary):
- Q-Q (quantile-quantile) plot: Points should fall on diagonal line
- Histogram with normal curve overlay
- Kernel density plot
**Formal tests** (secondary):
- Shapiro-Wilk test (good default; scipy handles n up to ~5000 and warns above that)
- Lilliefors test (`statsmodels.stats.diagnostic.lilliefors`) — use this instead of a plain Kolmogorov-Smirnov test, which is invalid when the mean/SD are estimated from the data
- Anderson-Darling test
**Python implementation**:
```python
from scipy import stats
import matplotlib.pyplot as plt
# Shapiro-Wilk test
statistic, p_value = stats.shapiro(data)
# Q-Q plot
stats.probplot(data, dist="norm", plot=plt)
```
**Interpretation guidance**:
- Assess plots, tail behavior, sample balance, dependence and the estimand at every sample size. Formal tests have low power in small samples and detect tiny departures in large samples; non-rejection does not validate a model.
- Look for severe skewness, outliers, or bimodality
**What to do if violated**:
- **Departures**: Evaluate robustness for the target effect and design; there is no universal n=30 threshold. Prespecify robust inference or simulation-based sensitivity. Rank methods change the target and retain assumptions; they are not automatic replacements.
- **Severe violations**:
- Transform data (log, square root, Box-Cox)
- Use non-parametric methods
- Use robust regression methods
- Consider bootstrapping
**Critical severity**: MEDIUM - parametric tests are often robust to mild violations with adequate sample size
---
### 3. Homogeneity of Variance (Homoscedasticity)
**What it means**: Variances are equal across groups or across the range of predictors.
**When required**:
- Pooled Student's t-test and classical equal-variance ANOVA (not Welch tests)
- Usual homoscedastic OLS standard errors; HC3 addresses independent heteroscedastic errors, not clusters
**How to check**:
**Visual methods** (primary):
- Box plots by group (for t-test/ANOVA)
- Residuals vs. fitted values plot (for regression) - should show random scatter
- Scale-location plot (square root of standardized residuals vs. fitted)
**Formal tests** (secondary):
- Levene's test (robust to non-normality)
- Bartlett's test (sensitive to non-normality, not recommended)
- Brown-Forsythe test (median-based version of Levene's)
- Breusch-Pagan test (for regression)
**Python implementation**:
```python
from scipy import stats
import pingouin as pg
# Median-centered Levene is the Brown-Forsythe variance test
statistic, p_value = stats.levene(group1, group2, group3, center='median')
# For regression
# Breusch-Pagan test
# Note: exog must include the constant column (e.g. exog = sm.add_constant(X),
# or pass the fitted model's model.exog)
from statsmodels.stats.diagnostic import het_breuschpagan
_, p_value, _, _ = het_breuschpagan(residuals, exog)
```
**Interpretation guidance**:
- No variance-ratio cutoff certifies validity. Balanced designs can help robustness but do not remove tail, dependence or variance concerns.
- Do not choose pooled versus Welch inference based only on a preliminary variance p-value.
- For regression: Look for funnel patterns in residual plots
**What to do if violated**:
- **t-test**: Use Welch's t-test (does not assume equal variances)
- **ANOVA**: Use Welch's ANOVA or Brown-Forsythe ANOVA
- **Regression**:
- Transform dependent variable (log, square root)
- Use weighted least squares (WLS)
- Use robust standard errors (HC3)
- Use generalized linear models (GLM) with appropriate variance function
**Critical severity**: MEDIUM - tests can be robust with equal sample sizes
---
## Test-Specific Assumptions
### T-Tests
**Assumptions**:
1. Independence of observations
2. Normality (each group for independent t-test; differences for paired t-test)
3. Homogeneity only for pooled Student's independent t-test; Welch permits unequal variances
**Diagnostic workflow**:
```python
import scipy.stats as stats
import pingouin as pg
# Check normality for each group
stats.shapiro(group1)
stats.shapiro(group2)
# Check homogeneity of variance
stats.levene(group1, group2)
# Prespecify inference from the design/estimand rather than the screening p-values:
# Option 1: Welch's t-test (unequal variances)
pg.ttest(group1, group2, correction=True) # correction=True applies Welch's
# (correction='auto' applies Welch only when sample sizes are unequal;
# correction=False forces Student's t-test)
# Option 2: A separately justified rank/distribution question
pg.mwu(group1, group2) # Mann-Whitney U
```
---
### ANOVA
**Assumptions**:
1. Independence of observations within and between groups
2. Normality in each group
3. Homogeneity of variance across groups
**Additional considerations**:
- For repeated measures ANOVA: Sphericity assumption (Mauchly's test)
**Diagnostic workflow**:
```python
import pingouin as pg
from scipy import stats
# Check normality per group
for group in df['group'].unique():
data = df[df['group'] == group]['value']
w, p = stats.shapiro(data)
print(f"{group}: W = {w:.3f}, p = {p:.4f}")
# Check homogeneity of variance
print(pg.homoscedasticity(df, dv='value', group='group'))
# For repeated measures: Check sphericity
# Pingouin 0.7 supports one/two-way sphericity diagnostics; earlier interaction
# corrections had bugs. Specify subject IDs and complete within-subject cells.
```
**What to do if sphericity violated** (repeated measures):
- Prespecify a correction such as Greenhouse-Geisser; Pingouin rm_anova reports GG.
- Do not infer Huynh-Feldt is automatically available from an epsilon threshold.
- Use multivariate approach (MANOVA)
---
### Linear Regression
**Assumptions**:
1. **Mean specification**: Conditional mean is linear in fitted coefficients (can include justified nonlinear predictor terms)
2. **Independence**: Residuals are independent
3. **Homoscedasticity**: Constant variance of residuals
4. **Normality**: Normal errors for exact small-sample conventional inference; fitted residuals are correlated projections, so residual Shapiro is only a screen
5. **Identifiability**: Full-rank design; high collinearity affects precision but is not by itself bias
6. **Exogeneity**: The conditional error mean is zero; residual plots do not establish causal identification
**Diagnostic workflow**:
**1. Linearity**:
```python
import matplotlib.pyplot as plt
import seaborn as sns
# Scatter plots of Y vs each X
# Residuals vs. fitted values (should be randomly scattered)
plt.scatter(fitted_values, residuals)
plt.axhline(y=0, color='r', linestyle='--')
```
**2. Independence**:
```python
from statsmodels.stats.stattools import durbin_watson
# Durbin-Watson test (for time series)
dw_statistic = durbin_watson(residuals)
# Meaningful row order is required; no universal 1.5-2.5 acceptance interval.
# This statistic cannot establish independence, particularly for clustered data.
```
**3. Homoscedasticity**:
```python
# Breusch-Pagan test
# Note: exog must include the constant column (e.g. sm.add_constant(X))
from statsmodels.stats.diagnostic import het_breuschpagan
_, p_value, _, _ = het_breuschpagan(residuals, exog)
# Visual: Scale-location plot
plt.scatter(fitted_values, np.sqrt(np.abs(std_residuals)))
```
**4. Normality of residuals**:
```python
# Q-Q plot of residuals
stats.probplot(residuals, dist="norm", plot=plt)
# Shapiro-Wilk test
stats.shapiro(residuals)
```
**5. Multicollinearity**:
```python
from statsmodels.stats.outliers_influence import variance_inflation_factor
# Calculate VIF for each predictor
vif_data = pd.DataFrame()
vif_data["feature"] = X.columns
vif_data["VIF"] = [variance_inflation_factor(X.values, i) for i in range(len(X.columns))]
# VIF > 10 indicates severe multicollinearity
# VIF > 5 indicates moderate multicollinearity
```
**What to do if violated**:
- **Non-linearity**: Add polynomial terms, use GAM, or transform variables
- **Heteroscedasticity**: Transform Y, use WLS, use robust SE
- **Non-normal residuals**: Transform Y, use robust methods, check for outliers
- **Multicollinearity**: Examine precision and identification; dropping confounders can bias estimates. Regularization changes inference and must match the purpose.
---
### Logistic Regression
**Assumptions**:
1. **Independence**: Observations are independent
2. **Linearity**: Linear relationship between log-odds and continuous predictors
3. **No perfect multicollinearity**: Predictors not perfectly correlated
4. **Information and identification**: Adequate events/non-events for parameters, effect sizes and precision; check separation and convergence. No fixed events-per-variable ratio guarantees valid inference.
**Diagnostic workflow**:
**1. Linearity of logit**:
```python
# Box-Tidwell test: Add interaction with log of continuous predictor
# If interaction is significant, linearity violated
```
**2. Multicollinearity**:
```python
# Use VIF as in linear regression
```
**3. Influential observations**:
```python
# Cook's distance, DFBetas, leverage (statsmodels >= 0.10)
# Do NOT use OLSInfluence on Logit/GLM results; use get_influence(),
# which returns MLEInfluence (Logit) or GLMInfluence (GLM)
influence = model.get_influence()
cooks_d, cooks_p = influence.cooks_distance # tuple: (distances, approximate p-values)
# Outside Gaussian linear models these F-based p-values are approximate.
```
**4. Model fit / calibration**:
```python
# Calibration curve: compare predicted probabilities to observed event rates
# (e.g. sklearn.calibration.calibration_curve), plus the Brier score
# Pseudo R-squared
# Classification metrics (accuracy, AUC-ROC)
# Note: the Hosmer-Lemeshow test is not implemented in scipy/statsmodels
# and is sensitive to the choice of bins; prefer calibration curves
```
---
## Outlier Detection
**Methods**:
1. **Visual**: Box plots, scatter plots
2. **Statistical**:
- Z-scores: |z| > 3 suggests outlier
- IQR method: Values < Q1 - 1.5×IQR or > Q3 + 1.5×IQR
- Modified Z-score using median absolute deviation (robust to outliers)
**For regression**:
- **Leverage**: High leverage points (hat values)
- **Influence**: Cook's distance > 4/n suggests influential point
- **Outliers**: Studentized residuals > ±3
**What to do**:
1. Investigate data entry errors
2. Consider if outliers are valid observations
3. Report sensitivity analysis (results with and without outliers)
4. Use robust methods if outliers are legitimate
---
## Sample Size Considerations
### Design-specific planning
Plan using the target effect or desired interval width, variance, prevalence, number of fitted parameters, clustering and attrition. Generic n=30/n=50 or events-per-variable thresholds do not establish power, robustness or model reliability. Simulate the actual planned estimator/design when closed-form assumptions do not apply.
### Small Sample Considerations
For small samples:
- Assumptions become more critical
- Use exact tests when available (Fisher's exact, exact logistic regression)
- Consider non-parametric alternatives
- Use permutation tests or bootstrap methods
- Be conservative with interpretation
---
## Reporting Assumption Checks
When reporting analyses, include:
1. **Statement of assumptions checked**: List all assumptions tested
2. **Methods used**: Describe visual and formal tests employed
3. **Results of diagnostic tests**: Report test statistics and p-values
4. **Assessment**: State evidence of departures and limits of the screens; never equate non-rejection with verified assumptions
5. **Actions taken**: If violated, describe remedial actions (transformations, alternative tests, robust methods)
**Example reporting statement**:
> "Normality was assessed using Shapiro-Wilk tests and Q-Q plots. Data for Group A (W = 0.97, p = .18) and Group B (W = 0.96, p = .12) showed no significant departure from normality. Homogeneity of variance was assessed using Levene's test, which was non-significant (F(1, 58) = 1.23, p = .27), providing no detected departure from equal variances at this sample size. Non-rejection does not verify equality; the prespecified Welch test and design review were retained."
## Current API sources
Reviewed 2026-10-01: [SciPy Shapiro](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.shapiro.html) requires at least three observations and warns that n>5000 p-values may be inaccurate; [Levene](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.levene.html) defaults to median centering. [statsmodels Breusch-Pagan](https://www.statsmodels.org/stable/generated/statsmodels.stats.diagnostic.het_breuschpagan.html) defaults to the Koenker variant (`robust=True`), needs an intercept, and also returns the finite-sample F variant; report which one is used. [Durbin-Watson](https://www.statsmodels.org/stable/generated/statsmodels.stats.stattools.durbin_watson.html) is a statistic of adjacent residuals, not an independence certificate.

View File

@@ -0,0 +1,188 @@
# Bayesian Statistical Analysis
Reviewed 2026-10-01 for PyMC 6.3.2 and ArviZ 1.3.0 (Python 3.12+). The examples are local statistical APIs, with no authentication or service endpoint. PyMC returns xarray `DataTree` groups such as `posterior`, `sample_stats`, `observed_data` and `posterior_predictive`. ArviZ's current API is split across `arviz-stats` and `arviz-plots`, re-exported by `arviz`.
The model fragments below require finite, aligned data supplied by the analyst. Their API mechanics were exercised on small synthetic datasets with short native PyMC NUTS chains, using the Python PyTensor backend on the reviewed Mac. Those runs do not establish convergence or validate the scientific models. On this host C linking failed with missing `-ld64`; `PYTENSOR_FLAGS=cxx=` was an explicit runtime workaround, not evidence of successful C-backend execution.
## Questions, priors and uncertainty
Bayes' theorem gives posterior density proportional to likelihood times prior density. A posterior probability statement is conditional on that likelihood, prior, sampling design and available data. A continuous prior generally assigns zero probability to an exact point null: posterior draws cannot by themselves give a Bayes factor for that null.
Specify the estimand, units, independent sampling unit, censoring/missingness and dependence before choosing a model. Small samples may be weakly identified and sensitive to priors; Bayesian inference does not create information absent from the data.
- Scale priors using meaningful units and external knowledge. A Normal(0, 10) prior is not universally weakly informative. Using the same data to tune priors is an empirical choice that must be disclosed.
- A HalfNormal or HalfCauchy prior on `sigma` is a prior on standard deviation, not variance. Very heavy tails can cause computational problems.
- A flat prior over the real line is improper, not a proper Uniform(-infinity, infinity) distribution; it can yield an improper posterior or undefined marginal likelihood.
- Examine prior predictions, fit the prespecified model, and repeat with scientifically plausible alternative priors. Similar outputs across a few priors do not prove robustness to model misspecification.
- Sequential analysis needs an explicit stopping/decision rule. A fixed-prior Bayes factor has different optional-stopping properties from a posterior-threshold rule; there is no blanket exemption from calibration or multiplicity concerns.
## Two independent normal groups
This estimates a mean difference under a shared residual SD; it is not Welch's unequal-variance model. Set the prior scales to the measurement units. For unequal variances, model separate SDs and state the resulting model.
```python
import numpy as np
import pymc as pm
import arviz as az
with pm.Model() as group_model:
mu1 = pm.Normal('mu1', mu=0, sigma=10)
mu2 = pm.Normal('mu2', mu=0, sigma=10)
sigma = pm.HalfNormal('sigma', sigma=10)
pm.Normal('y1', mu=mu1, sigma=sigma, observed=group1)
pm.Normal('y2', mu=mu2, sigma=sigma, observed=group2)
pm.Deterministic('diff', mu1 - mu2)
trace = pm.sample(2000, tune=1000, chains=4, cores=1,
random_seed=42, nuts_sampler='pymc')
# Explicit interval probability/type; avoid rounded diagnostics for decisions.
print(az.summary(trace, var_names=['mu1', 'mu2', 'diff'],
ci_prob=0.95, ci_kind='eti', round_to='none'))
draws = trace.posterior['diff'].values
print(f"P(mu1 > mu2 | data, model) = {np.mean(draws > 0):.3f}")
az.plot_dist(trace, var_names=['diff'], ci_prob=0.95, ci_kind='eti')
```
A posterior directional probability is not a one-sided Bayes factor. Pingouin 0.7 intentionally omits the `BF10` column for a one-sided `ttest`. Its two-sided default uses the documented JZS prior on standardized effect (Cauchy scale `r=0.707`):
```python
import pingouin as pg
result = pg.ttest(group1, group2, correction=False, r=0.707)
bf10 = float(result['BF10'].iloc[0]) # default output may be a formatted string
```
BF10 is the ratio of the data's marginal likelihoods under H1 and H0. Posterior odds equal BF10 times prior odds. BF10=3 means threefold evidence for H1 relative to H0 under those models; it does not by itself mean H1 is three times as probable. Conventional labels (3–10 moderate, 10–30 strong, 30–100 very strong, >100 extreme) are reporting conventions. State both models, priors and sensitivity. The BF printed beside a Welch statistic is not an unequal-variance Bayesian model comparison.
## Credible intervals and practical equivalence
An equal-tailed 95% interval has 2.5% in each tail. A highest-density region favors high-density values and may be disconnected for multimodal posteriors; a single shortest interval need not contain every mode. Neither interval proves the model is correct.
```python
posterior_samples = trace.posterior['diff']
eti = posterior_samples.quantile([0.025, 0.975], dim=('chain', 'draw'))
hdi = az.hdi(posterior_samples, prob=0.95, dim=['chain', 'draw'])
# Define a negligible raw-unit difference BEFORE looking at the result.
rope_lower, rope_upper = -0.1, 0.1
in_rope = ((posterior_samples >= rope_lower) &
(posterior_samples <= rope_upper)).mean().item()
print(f"Posterior probability inside the prespecified ROPE: {in_rope:.3f}")
```
The ROPE must match the parameter's units: raw mean difference and standardized d cannot use the same threshold without justification. A posterior-mass decision rule and an HDI-inside-ROPE rule are distinct. Prespecify the rule and assess its consequences rather than presenting 95% as a universal decision threshold.
## Hierarchical group comparisons / Bayesian ANOVA
Use integer `group_idx` aligned with `y`, ranging from 0 to `n_groups-1`. The noncentered parameterization below gives partial pooling of group means. Prior scales remain illustrative; compare pooling assumptions and within-group residual distributions.
```python
with pm.Model() as hierarchical_model:
mu_global = pm.Normal('mu_global', mu=0, sigma=10)
sigma_between = pm.HalfNormal('sigma_between', sigma=5)
sigma_within = pm.HalfNormal('sigma_within', sigma=5)
z_group = pm.Normal('z_group', mu=0, sigma=1, shape=n_groups)
group_means = pm.Deterministic('group_means', mu_global + sigma_between * z_group)
pm.Normal('y_obs', mu=group_means[group_idx], sigma=sigma_within, observed=y)
group_trace = pm.sample(2000, tune=1000, chains=4, cores=1,
random_seed=42, nuts_sampler='pymc')
contrast_1_2 = (group_trace.posterior['group_means'].isel(group_means_dim_0=0)
- group_trace.posterior['group_means'].isel(group_means_dim_0=1))
```
The hierarchy models group intercepts only. Repeated measures may need subject effects, slopes or residual correlation; cluster identity is not optional. Contrasts are posterior estimates, not automatically Bayes factors or multiplicity-calibrated decisions.
## Correlation with uncertainty in location and scale
Standardizing observed data does not make population means and variances known. Infer those nuisance parameters rather than fixing covariance diagonals to one. Here `xy` contains two columns in reasonable units; prior scales must be adapted to those units.
```python
xy = np.column_stack([x, y])
with pm.Model() as correlation_model:
mu = pm.Normal('mu', mu=0, sigma=10, shape=2)
chol, corr, sds = pm.LKJCholeskyCov(
'chol', n=2, eta=2, sd_dist=pm.HalfNormal.dist(sigma=10), compute_corr=True)
pm.Deterministic('rho', corr[0, 1])
pm.MvNormal('xy_obs', mu=mu, chol=chol, observed=xy)
correlation_trace = pm.sample(2000, tune=1000, chains=4, cores=1,
random_seed=42, nuts_sampler='pymc')
print(az.summary(correlation_trace, var_names=['rho'], ci_prob=0.95))
```
The bivariate normal likelihood is a substantive assumption; this is not a distribution-free rank correlation model. LKJ `eta=2` shrinks correlation toward zero.
## Regression, posterior prediction and restoration
`X` is an n-by-p numeric array, `y` an aligned length-n array, and `X_new` has the same p features/coding. Fit any preprocessing on the training data and reuse it. `pm.Data` can change length, not rank; models using named observation coordinates also need updated coordinates via `pm.set_data(..., coords=...)`.
```python
with pm.Model() as regression_model:
X_data = pm.Data('X', X)
alpha = pm.Normal('alpha', mu=0, sigma=10)
beta = pm.Normal('beta', mu=0, sigma=10, shape=X.shape[1])
sigma = pm.HalfNormal('sigma', sigma=10)
mu = alpha + pm.math.dot(X_data, beta)
pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, shape=mu.shape)
regression_trace = pm.sample(2000, tune=1000, chains=4, cores=1,
random_seed=42, nuts_sampler='pymc')
ppc = pm.sample_posterior_predictive(regression_trace, random_seed=43)
try:
pm.set_data({'X': X_new})
predictions = pm.sample_posterior_predictive(
regression_trace, predictions=True, random_seed=44)
finally:
pm.set_data({'X': X})
az.plot_ppc_dist(ppc, var_names=['y_obs'], num_samples=100)
# Noisy future observations are in a separate predictions group.
predictive_interval = predictions.predictions['y_obs'].quantile(
[0.025, 0.975], dim=('chain', 'draw'))
```
Observed-outcome predictions include residual noise. A posterior interval for the latent mean would be narrower and answers a different question. Do not compare changed-length predictions with the training outcomes as a posterior predictive check.
## Model comparison
PSIS-LOO estimates predictive performance, not evidence for a point null. Compare models for the **same observed outcomes, rows and likelihood units**, with aligned pointwise log-likelihood coordinates. Ordinary observation-wise LOO is inappropriate when prediction targets new clusters or future dependent observations; use the appropriate grouped/temporal validation design.
```python
with regression_model: # training inputs must have been restored
pm.compute_log_likelihood(regression_trace, var_names=['y_obs'])
loo = az.loo(regression_trace, var_name='y_obs', pointwise=True)
print(f"Expected log predictive density: {loo.elpd:.2f}") # higher is better
print(loo.pareto_k, loo.good_k, loo.warning)
```
Investigate Pareto-k values above `good_k`, including refitting troublesome observations or suitable cross-validation. Differences small relative to their uncertainty do not identify a unique best model. For multiple prepared traces, `az.compare({'model1': trace1, 'model2': trace2}, var_name='y_obs')` reports rankings and stacking weights; stacking weights are not posterior model probabilities. ArviZ 1 removed `az.waic`; do not use an old WAIC fallback snippet. Default ArviZ intervals are configuration-dependent (89% in the reviewed defaults), so request `ci_prob=0.95` when needed.
## Diagnostics and posterior predictive checks
- Use multiple independently initialized chains (usually at least four). Inspect finite rank-normalized R-hat, bulk/tail ESS and MCSE for every reported estimand; R-hat near 1, commonly below 1.01, is a screening target, not proof of convergence or identifiability.
- Tail precision requires enough effective draws. An ESS cutoff does not establish precision for an extreme posterior probability. NaN diagnostics are unavailable/failed, not passed.
- Inspect divergences, energy/BFMI and tree-depth warnings when using HMC; trace/rank plots can reveal slow exploration. Solve model geometry/identification problems rather than merely increasing draws.
- Compare posterior replicated data with features relevant to the question: spread, tails, zeros, groups and dependence, not only the overall mean.
```python
print(az.summary(regression_trace, kind='diagnostics', round_to='none'))
az.plot_trace(regression_trace)
az.plot_rank(regression_trace)
az.plot_forest(regression_trace, var_names=['beta'], ci_probs=[0.5, 0.95])
pp = ppc.posterior_predictive['y_obs']
# Mean over observation dimensions, retain chain/draw before aggregating.
obs_dims = [dim for dim in pp.dims if dim not in ('chain', 'draw')]
pred_means = pp.mean(dim=obs_dims)
posterior_predictive_tail = (pred_means >= np.mean(y)).mean().item()
```
This posterior predictive tail area reuses the observed data through the posterior and is not a uniformly calibrated frequentist p-value. Visual distributional checks also do not certify predictive calibration.
## Reporting
Report likelihood, parameterization, prior units/hyperparameters, missingness and dependence handling, chains/tune/draws, sampler/backend and package versions. State the interval type/probability, estimand units, posterior diagnostic results, sensitivity checks and predictive discrepancies. Report a Bayes factor only if actually calculated under explicitly described models; posterior sample fractions do not supply it. Report Bayesian intervals as credible intervals (CrI), not frequentist confidence intervals (CI).
For other front ends, [Bambi](https://bambinos.github.io/bambi/) provides formula-based modeling and [CmdStanPy](https://mc-stan.org/cmdstanpy/) interfaces to Stan (requires a separate CmdStan toolchain). These optional tools are not required or runtime-validated by this workflow. Do not describe PyStan as discontinued; [PyStan 3](https://pystan.readthedocs.io/en/latest/) is a separate supported interface with its own platform requirements.
## Primary API sources
- [PyMC sample](https://www.pymc.io/projects/docs/en/stable/api/generated/pymc.sample.html), [data](https://www.pymc.io/projects/docs/en/stable/api/generated/pymc.Data.html), [posterior prediction](https://www.pymc.io/projects/docs/en/stable/api/generated/pymc.sample_posterior_predictive.html), [LKJ covariance](https://www.pymc.io/projects/docs/en/stable/api/distributions/generated/pymc.LKJCholeskyCov.html).
- [ArviZ summary](https://python.arviz.org/projects/stats/en/stable/api/generated/arviz_stats.summary.html), [HDI](https://python.arviz.org/projects/stats/en/stable/api/generated/arviz_stats.hdi.html), [LOO](https://python.arviz.org/projects/stats/en/stable/api/generated/arviz_stats.loo.html), [comparison](https://python.arviz.org/projects/stats/en/stable/api/generated/arviz_stats.compare.html), [PPC plotting](https://python.arviz.org/projects/plots/en/stable/api/generated/arviz_plots.plot_ppc_dist.html).
- [Pingouin Bayes factor](https://pingouin-stats.org/generated/pingouin.bayesfactor_ttest.html).

View File

@@ -0,0 +1,656 @@
# Effect Sizes and Power Analysis
This document provides guidance on calculating, interpreting, and reporting effect sizes, as well as conducting power analyses for study planning.
## Why Effect Sizes Matter
1. **Statistical significance ≠ practical significance**: p-values measure incompatibility with a null model under its assumptions, not existence or magnitude
2. **Sample size dependent**: With large samples, trivial effects become "significant"
3. **Interpretation**: Effect sizes provide magnitude and practical importance
4. **Meta-analysis**: Effect sizes enable combining results across studies
5. **Power analysis**: Required for sample size determination
**Golden rule**: ALWAYS report effect sizes alongside p-values.
---
## Effect Sizes by Analysis Type
### T-Tests and Mean Differences
#### Cohen's d (Standardized Mean Difference)
**Formula**:
- Independent groups: d = (M₁ - M₂) / SD_pooled
- Paired groups: specify the standardizer. d_z = M_diff / SD_diff; d_av = M_diff / sqrt((SD_pre² + SD_post²)/2). These are different effects.
**Interpretation** (Cohen, 1988):
- Small: |d| = 0.20
- Medium: |d| = 0.50
- Large: |d| = 0.80
**Context-dependent interpretation**:
- Justify a smallest scientifically meaningful effect from the outcome, intervention and context; no discipline-wide threshold is universally meaningful.
- In medicine: Small effect sizes can be clinically important
**Python calculation**:
```python
import pingouin as pg
import numpy as np
# Independent t-test with effect size
result = pg.ttest(group1, group2, correction=False)
cohens_d = pg.compute_effsize(group1, group2, eftype='cohen') # signed; ttest returns abs(d)
# (pingouin 0.6.0 renamed columns; on 0.5.x use 'p-val', 'cohen-d', 'CI95%', 'p-unc')
# Manual calculation
mean_diff = np.mean(group1) - np.mean(group2)
n1, n2 = len(group1), len(group2)
pooled_std = np.sqrt(((n1 - 1) * np.var(group1, ddof=1) + (n2 - 1) * np.var(group2, ddof=1)) / (n1 + n2 - 2))
cohens_d = mean_diff / pooled_std
# Paired t-test
result = pg.ttest(pre, post, paired=True)
d_av = pg.compute_effsize(pre, post, paired=True, eftype='cohen')
d_z = pg.compute_effsize(pre, post, paired=True, eftype='cohen_dz')
```
**Confidence intervals for independent pooled d** (approximate parametric interval; supply analyzed, non-missing sample sizes; do not reuse this formula for d_av or assume unequal-variance validity):
```python
import pingouin as pg
# compute_effsize_from_t returns only the point estimate;
# get the CI separately with compute_esci
d = pg.compute_effsize(group1, group2, eftype='cohen')
ci = pg.compute_esci(stat=d, nx=len(group1), ny=len(group2),
eftype='cohen', confidence=0.95)
```
---
#### Hedges' g (Bias-Corrected d)
**Why use it**: Cohen's d has slight upward bias with small samples (n < 20)
**Formula**: g = d × correction_factor, where correction_factor = 1 - 3/(4df - 1)
**Python calculation**:
```python
# pg.ttest output has no Hedges' g column; compute it directly
hedges_g = pg.compute_effsize(group1, group2, eftype='hedges')
```
**Use Hedges' g when**:
- Sample sizes are small (n < 20 per group)
- Conducting meta-analyses (standard in meta-analysis)
---
#### Glass's Δ (Delta)
**When to use**: When one group is a control with known variability
**Formula**: Δ = (M₁ - M₂) / SD_control
**Use cases**:
- Clinical trials (use control group SD)
- When treatment affects variability
---
### ANOVA
#### Eta-squared (η²)
**What it measures**: Proportion of total variance explained by factor
**Formula**: η² = SS_effect / SS_total
**Interpretation**:
- Small: η² = 0.01 (1% of variance)
- Medium: η² = 0.06 (6% of variance)
- Large: η² = 0.14 (14% of variance)
**Limitation**: In multi-factor designs each effect's η² shrinks as other factors are added (orthogonal decompositions give additive shares; Type II/III sums in unbalanced designs need not add to total SS); it is partial η² that can sum to > 1.0 across factors
**Python calculation**:
```python
import pingouin as pg
# One-way ANOVA (detailed=True is required for the SS column)
aov = pg.anova(dv='value', between='group', data=df, detailed=True)
eta_squared = aov['SS'][0] / aov['SS'].sum()
# Or read pingouin's np2 column, which is PARTIAL eta-squared:
partial_eta_sq = aov['np2'][0]
# np2 coincides with classical eta-squared only for one-way (single-factor) designs
```
---
#### Partial Eta-squared (η²_p)
**What it measures**: Proportion of variance explained by factor, excluding other factors
**Formula**: η²_p = SS_effect / (SS_effect + SS_error)
**Interpretation**: Same benchmarks as η²
**When to use**: Multi-factor ANOVA (standard in factorial designs)
**Limitation**: Across factors, partial η² values can sum to > 1.0 — they are not additive shares of total variance
**Python calculation**:
```python
aov = pg.anova(dv='value', between=['factor1', 'factor2'], data=df)
# pingouin reports partial eta-squared by default
partial_eta_sq = aov['np2']
```
---
#### Omega-squared (ω²)
**What it measures**: Less biased estimate of population variance explained
**Why use it**: η² overestimates effect size; ω² provides better population estimate
**Formula**: ω² = (SS_effect - df_effect × MS_error) / (SS_total + MS_error)
**Interpretation**: Same benchmarks as η², but typically smaller values
**Python calculation** (one-way table with effect row first and residual row last; the estimator can be negative, so state any truncation convention):
```python
def omega_squared(aov_table):
ss_effect = aov_table.loc[0, 'SS']
ss_total = aov_table['SS'].sum()
ms_error = aov_table.loc[aov_table.index[-1], 'MS'] # Residual MS
df_effect = aov_table.loc[0, 'DF']
omega_sq = (ss_effect - df_effect * ms_error) / (ss_total + ms_error)
return omega_sq
```
---
#### Cohen's f
**What it measures**: Effect size for ANOVA (analogous to Cohen's d)
**Formula**: f = √(η² / (1 - η²))
**Interpretation**:
- Small: f = 0.10
- Medium: f = 0.25
- Large: f = 0.40
**Python calculation**:
```python
eta_squared = 0.06 # From ANOVA
cohens_f = np.sqrt(eta_squared / (1 - eta_squared))
```
**Use in power analysis**: Required for ANOVA power calculations
---
### Correlation
#### Pearson's r / Spearman's ρ
**Interpretation**:
- Small: |r| = 0.10
- Medium: |r| = 0.30
- Large: |r| = 0.50
**Important notes**:
- For Pearson correlation in simple OLS with an intercept, r² equals R². Spearman ρ² concerns ranks and is not raw-outcome variance explained.
- Pearson r = 0.30 gives r² = 0.09; association is not causal explanation.
- Consider direction (positive/negative) and context
**Python calculation**:
```python
import pingouin as pg
# Pearson correlation with CI
result = pg.corr(x, y, method='pearson')
r = result['r'].values[0]
ci = result['CI95'].values[0] # pingouin 0.6.0 renamed CI95% to CI95
# Spearman correlation
result = pg.corr(x, y, method='spearman')
rho = result['r'].values[0]
```
---
### Regression
#### R² (Coefficient of Determination)
**What it measures**: Proportion of variance in Y explained by model
**Interpretation**:
- Small: R² = 0.02
- Medium: R² = 0.13
- Large: R² = 0.26
**Context-dependent**:
- Interpret R² relative to outcome variability, measurement error and purpose; no field-wide cutoff establishes fit or predictive performance. Evaluate predictions on held-out data when prediction is the goal.
**Python calculation**:
```python
import statsmodels.api as sm
# Using statsmodels (add_constant adds the intercept column)
model = sm.OLS(y, sm.add_constant(X)).fit()
r_squared = model.rsquared
adjusted_r_squared = model.rsquared_adj
# Manual
r_squared = 1 - (SS_residual / SS_total)
```
---
#### Adjusted R²
**Why use it**: R² artificially increases when adding predictors; adjusted R² penalizes model complexity
**Formula**: R²_adj = 1 - (1 - R²) × (n - 1) / (n - k - 1)
**When to use**: Always report alongside R² for multiple regression
---
#### Standardized Regression Coefficients (β)
**What it measures**: Effect of one-SD change in predictor on outcome (in SD units)
**Interpretation**: Conditional on all included predictors and their coding; β has no universal small/medium/large thresholds and is not Cohen's d.
**Python calculation**:
```python
import statsmodels.api as sm
# Numeric predictor DataFrame, each column nonconstant; standardize columnwise
X_std = (X - X.mean()) / X.std()
y_std = (y - y.mean()) / y.std()
model = sm.OLS(y_std, sm.add_constant(X_std)).fit()
beta = model.params
```
---
#### f² (Cohen's f-squared for Regression)
**What it measures**: Effect size for individual predictors or model comparison
**Formula**: f² = (R²_AB - R²_A) / (1 - R²_AB)
Where:
- R²_AB = R² for full model with predictor
- R²_A = R² for reduced model without predictor
**Interpretation**:
- Small: f² = 0.02
- Medium: f² = 0.15
- Large: f² = 0.35
**Python calculation**:
```python
# Compare two nested models
import statsmodels.api as sm
# Same observations and outcome in both models; include intercepts
model_full = sm.OLS(y, sm.add_constant(X_full)).fit()
model_reduced = sm.OLS(y, sm.add_constant(X_reduced)).fit()
r2_full = model_full.rsquared
r2_reduced = model_reduced.rsquared
f_squared = (r2_full - r2_reduced) / (1 - r2_full)
```
---
### Categorical Data Analysis
#### Cramér's V
**What it measures**: Association strength for χ² test (works for any table size)
**Formula**: V = √(χ² / (n × (k - 1)))
Where k = min(rows, columns)
**Interpretation** (benchmarks depend on df* = min(rows, columns) − 1):
| df* | Small | Medium | Large |
|-----|-------|--------|-------|
| 1 (2×2) | 0.10 | 0.30 | 0.50 |
| 2 | 0.07 | 0.21 | 0.35 |
| 3 | 0.06 | 0.17 | 0.29 |
**For 2×2 tables**: Use phi coefficient (φ)
**Python calculation**:
```python
import numpy as np
from scipy.stats.contingency import association
# Cramér's V
cramers_v = association(contingency_table, method='cramer')
# Phi coefficient (2x2): |phi| equals Cramér's V for a 2x2 table.
# Caution: method='pearson' is Pearson's contingency coefficient, NOT phi.
a, b, c, d = np.asarray(contingency_table, dtype=float).ravel()
phi = (a * d - b * c) / np.sqrt((a + b) * (c + d) * (a + c) * (b + d)) # signed phi
```
---
#### Odds Ratio (OR) and Risk Ratio (RR)
**For 2×2 contingency tables**:
| | Outcome + | Outcome - |
|-----------|-----------|-----------|
| Exposed | a | b |
| Unexposed | c | d |
**Odds Ratio**: OR = (a/b) / (c/d) = ad / bc
**Interpretation**:
- OR = 1: No association
- OR > 1: Positive association (increased odds)
- OR < 1: Negative association (decreased odds)
- OR = 2: Twice the odds
- OR = 0.5: Half the odds
**Risk Ratio**: RR = (a/(a+b)) / (c/(c+d))
**When to use**:
- Cohort studies: Use RR (more interpretable)
- Case-control studies: Use OR (RR not available)
- Logistic regression: OR is natural output
**Python calculation**:
```python
import numpy as np
from scipy import stats
import statsmodels.api as sm
# From contingency table
odds_ratio = (a * d) / (b * c)
# For a 2x2 table with method=None, Fisher returns sample OR and p-value (no CI);
# larger/resampled tables have a different statistic. Require nonnegative integer counts.
table = np.array([[a, b], [c, d]])
oddsratio, pvalue = stats.fisher_exact(table)
# Odds-ratio confidence interval (scipy >= 1.10; conditional MLE estimate)
or_result = stats.contingency.odds_ratio(table)
ci = or_result.confidence_interval(confidence_level=0.95)
# From logistic regression
model = sm.Logit(y_binary, sm.add_constant(X)).fit()
odds_ratios = np.exp(model.params) # Exponentiate coefficients
ci = np.exp(model.conf_int()) # Exponentiate CIs
```
---
### Nonparametric Effect Sizes
**Rank-biserial correlation (r_rb)**: Effect size for Mann-Whitney U and Wilcoxon signed-rank tests (range −1 to 1; interpret |r_rb| roughly like r). Returned by `pg.mwu` and `pg.wilcoxon` as the `RBC` column.
**Common-language effect size (CLES)**: P(X > Y) + 0.5 P(X = Y) for independent group draws (0.5 is no directional superiority, not proof of identical distributions). Returned by `pg.mwu` as `CLES`.
**r = z / √N**: Classic effect size when a z approximation is reported for Mann-Whitney/Wilcoxon (small 0.10, medium 0.30, large 0.50).
**Epsilon-squared (ε²)**: Effect size for Kruskal-Wallis: ε² = H × (n + 1) / (n² − 1).
**Python calculation**:
```python
import numpy as np
import pandas as pd
import pingouin as pg
res = pg.mwu(group1, group2)
print(res[['U_val', 'p_val', 'RBC', 'CLES']])
# Kruskal-Wallis with epsilon-squared
df = pd.DataFrame({'value': np.concatenate([group1, group2, group3]),
'group': np.repeat(['a', 'b', 'c'],
[len(group1), len(group2), len(group3)])})
kw = pg.kruskal(df, dv='value', between='group')
H, n = kw['H'].values[0], len(df)
epsilon_sq = H * (n + 1) / (n**2 - 1)
```
---
### Bayesian Evidence (Not an Effect Size)
#### Bayes Factor (BF)
**What it measures**: Ratio of evidence for alternative vs. null hypothesis
**Interpretation**:
- BF₁₀ = 1: Equal evidence for H₁ and H₀
- BF₁₀ = 3: the data have 3× greater marginal likelihood under H₁ than H₀ (moderate evidence)
- BF₁₀ = 10: the data have 10× greater marginal likelihood under H₁ than H₀ (strong evidence)
- BF₁₀ > 100: Decisive evidence for H₁ (30-100 counts as "very strong" on the Jeffreys scale)
- BF₁₀ = 0.33: the data have about 3× greater marginal likelihood under H₀ than H₁
- BF₁₀ = 0.10: the data have 10× greater marginal likelihood under H₀ than H₁
Posterior odds = Bayes factor × prior odds; BF alone is not posterior model probability. For the full Jeffreys interpretation table and BF reporting language, see `bayesian_statistics.md`.
**Python calculation**:
```python
import pingouin as pg
# Pingouin 0.5+: two-sided BF10 on independent t-tests; use BayesFactor/JASP/PyMC for full inference
result = pg.ttest(group1, group2, correction=False)
bf10 = float(result['BF10'].values[0]) # formatted string in default Pingouin output
```
---
### Bootstrap Confidence Intervals
When no analytic CI exists for an effect size (or its assumptions are doubtful), bootstrap one:
```python
import numpy as np
from scipy import stats
def cohen_d(x, y):
nx, ny = len(x), len(y)
sp = np.sqrt(((nx - 1) * np.var(x, ddof=1) + (ny - 1) * np.var(y, ddof=1))
/ (nx + ny - 2))
return (np.mean(x) - np.mean(y)) / sp
boot = stats.bootstrap((group1, group2), cohen_d, n_resamples=9999,
method='BCa', rng=np.random.default_rng(42))
print(boot.confidence_interval) # 95% BCa CI by default
```
Resample the sampling unit: correlations and paired effects require `paired=True`, and clustered designs require cluster resampling. BCa can be undefined for degenerate/discrete samples; inspect warnings, finite interval endpoints and Monte Carlo stability. More resamples cannot fix the wrong design.
---
## Power Analysis
### Concepts
**Statistical power**: Probability of rejecting a specified null under a specified alternative effect, variance and design (1 - β).
**Conventional standards**:
- Power = 0.80 (80% chance of detecting effect)
- α = 0.05 (5% Type I error rate)
**Four interconnected parameters** (given 3, can solve for 4th):
1. Sample size (n)
2. Effect size (d, f, etc.)
3. Significance level (α)
4. Power (1 - β)
---
### A Priori Power Analysis (Planning)
**Purpose**: Determine required sample size before study
**Steps**:
1. Specify expected effect size (from literature, pilot data, or minimum meaningful effect)
2. Set α level (typically 0.05)
3. Set desired power (typically 0.80)
4. Calculate required n
**Python implementation**:
```python
from statsmodels.stats.power import (
tt_ind_solve_power,
zt_ind_solve_power,
FTestAnovaPower,
NormalIndPower
)
# T-test power analysis
n_required = tt_ind_solve_power(
effect_size=0.5, # Cohen's d
alpha=0.05,
power=0.80,
ratio=1.0, # Equal group sizes
alternative='two-sided'
)
# ANOVA power analysis (kwarg is k_groups, not ngroups)
anova_power = FTestAnovaPower()
n_total = anova_power.solve_power(
effect_size=0.25, # Cohen's f
k_groups=3,
alpha=0.05,
power=0.80
)
# Returns the TOTAL sample size across all groups:
# f = 0.25, k = 3 -> ~158 total; round UP to 53/group, implemented total 159
import math
planned_n_per_group = math.ceil(n_required)
planned_anova_per_group = math.ceil(n_total / 3)
# Correlation power analysis
from pingouin import power_corr
n_required = power_corr(r=0.30, power=0.80, alpha=0.05)
```
---
### Post Hoc Power Analysis (After Study)
**⚠️ CAUTION**: Post hoc power is controversial and often not recommended
**Why it's problematic**:
- Observed power is a direct function of p-value
- If p > 0.05, power is always low
- Provides no additional information beyond p-value
- Can be misleading
**When it might be acceptable**:
- Study planning for future research
- Using effect size from multiple studies (not just your own)
- Explicit goal is sample size for replication
**Better alternatives**:
- Report confidence intervals for effect sizes
- Conduct sensitivity analysis
- Report minimum detectable effect size
---
### Sensitivity Analysis
**Purpose**: Determine minimum detectable effect size given study parameters
**When to use**: After study is complete, to understand study's capability
**Python implementation**:
```python
# What effect size could we detect with n=50 per group?
detectable_effect = tt_ind_solve_power(
effect_size=None, # Solve for this
nobs1=50,
alpha=0.05,
power=0.80,
ratio=1.0,
alternative='two-sided'
)
print(f"With n=50 per group, we could detect d ≥ {detectable_effect:.2f}")
```
---
## Reporting Effect Sizes
Numerical prose templates below are illustrative, not computed study results; use the actual fitted estimates and interval method.
### APA Style Guidelines
**T-test example**:
> "Group A (M = 75.2, SD = 8.5) scored significantly higher than Group B (M = 68.3, SD = 9.2), t(98) = 3.82, p < .001, d = 0.77, 95% CI [0.36, 1.18]."
**ANOVA example**:
> "There was a significant main effect of treatment condition on test scores, F(2, 87) = 8.45, p < .001, η²p = .16. Post hoc comparisons using Tukey's HSD revealed..."
**Correlation example**:
> "There was a moderate positive correlation between study time and exam scores, r(148) = .42, p < .001, 95% CI [.27, .55]."
**Regression example**:
> "The regression model significantly predicted exam scores, F(3, 146) = 45.2, p < .001, R² = .48. Study hours (β = .52, p < .001) and prior GPA (β = .31, p < .001) were significant predictors."
**Bayesian example**: See `bayesian_statistics.md` (Reporting Bayesian Results) for Bayes Factor and posterior reporting templates.
---
## Effect Size Pitfalls
1. **Don't only rely on benchmarks**: Context matters; small effects can be meaningful
2. **Report confidence intervals**: CIs show precision of effect size estimate
3. **Distinguish statistical vs. practical significance**: Large n can make trivial effects "significant"
4. **Consider cost-benefit**: Even small effects may be valuable if intervention is low-cost
5. **Multiple outcomes**: Effect sizes vary across outcomes; report all
6. **Don't cherry-pick**: Report effects for all planned analyses
7. **Publication bias**: Published effects are often overestimated
---
## Quick Reference Table
| Analysis | Effect Size | Small | Medium | Large |
|----------|-------------|-------|--------|-------|
| T-test | Cohen's d | 0.20 | 0.50 | 0.80 |
| ANOVA | η², ω² | 0.01 | 0.06 | 0.14 |
| ANOVA | Cohen's f | 0.10 | 0.25 | 0.40 |
| Correlation | r, ρ | 0.10 | 0.30 | 0.50 |
| Regression | R² | 0.02 | 0.13 | 0.26 |
| Regression | f² | 0.02 | 0.15 | 0.35 |
| Chi-square (df* = 1, 2×2) | Cramér's V, φ | 0.10 | 0.30 | 0.50 |
| Chi-square (df* = 2) | Cramér's V | 0.07 | 0.21 | 0.35 |
| Chi-square (df* = 3) | Cramér's V | 0.06 | 0.17 | 0.29 |
*Note*: df* = min(rows, columns) − 1.
---
## Current API Sources
Reviewed 2026-10-01: [Pingouin effect sizes](https://pingouin-stats.org/generated/pingouin.compute_effsize.html), [approximate effect intervals](https://pingouin-stats.org/generated/pingouin.compute_esci.html), [SciPy bootstrap](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bootstrap.html), [statsmodels power](https://www.statsmodels.org/stable/stats.html#power-and-sample-size-calculations).
## Resources
- Cohen, J. (1988). *Statistical Power Analysis for the Behavioral Sciences* (2nd ed.)
- Lakens, D. (2013). Calculating and reporting effect sizes
- Ellis, P. D. (2010). *The Essential Guide to Effect Sizes*

View File

@@ -0,0 +1,487 @@
# Statistical Reporting Standards
All numerical prose examples here are illustrative formatting templates, not computed results from a common dataset. Replace numbers, software versions, priors and diagnostic claims with the actual analysis.
This document provides guidelines for reporting statistical analyses according to APA (American Psychological Association) style and general best practices for academic publications.
## General Principles
1. **Transparency**: Report enough detail for replication
2. **Completeness**: Include all planned analyses and outcomes
3. **Honesty**: Report non-significant findings and violations
4. **Clarity**: Write for your audience, define technical terms
5. **Reproducibility**: Provide code, data, or supplements when possible
---
## Pre-Registration and Planning
### What to Report (Ideally Before Data Collection)
1. **Hypotheses**: Clearly stated, directional when appropriate
2. **Sample size justification**: Power analysis or other rationale
3. **Data collection stopping rule**: When will you stop collecting data?
4. **Variables**: All variables collected (not just those analyzed)
5. **Exclusion criteria**: Rules for excluding participants/data points
6. **Statistical analyses**: Planned tests, including:
- Primary analysis
- Secondary analyses
- Exploratory analyses (labeled as such)
- Handling of missing data
- Multiple comparison corrections
- Assumption checks
**Why pre-register?**
- Prevents HARKing (Hypothesizing After Results are Known)
- Distinguishes confirmatory from exploratory analyses
- Increases credibility and reproducibility
**Platforms**: OSF, AsPredicted, ClinicalTrials.gov
---
## Methods Section
### Participants
**What to report**:
- Total N, including excluded participants
- Relevant demographics (age, gender, etc.)
- Recruitment method
- Inclusion/exclusion criteria
- Attrition/dropout with reasons
**Example**:
> "Participants were 150 undergraduate students (98 female, 52 male; M_age = 19.4 years, SD = 1.2, range 18-24) recruited from psychology courses in exchange for course credit. Five participants were excluded due to incomplete data (n = 3) or failing attention checks (n = 2), resulting in a final sample of 145."
### Design
**What to report**:
- Study design (between-subjects, within-subjects, mixed)
- Independent variables and levels
- Dependent variables
- Control variables/covariates
- Randomization procedure
- Blinding (single-blind, double-blind)
**Example**:
> "A 2 (feedback: positive vs. negative) × 2 (timing: immediate vs. delayed) between-subjects factorial design was used. Participants were randomly assigned to conditions using a computer-generated randomization sequence. The primary outcome was task performance measured as number of correct responses (0-20 scale)."
### Measures
**What to report**:
- Full name of measure/instrument
- Number of items
- Scale/response format
- Scoring method
- Reliability (Cronbach's α, ICC, etc.)
- Validity evidence (if applicable)
**Example**:
> "Depression was assessed using the Beck Depression Inventory-II (BDI-II; Beck et al., 1996), a 21-item self-report measure rated on a 4-point scale (0-3). Total scores range from 0 to 63, with higher scores indicating greater depression severity. The BDI-II demonstrated excellent internal consistency in this sample (α = .91)."
### Procedure
**What to report**:
- Step-by-step description of what participants did
- Timing and duration
- Instructions given
- Any manipulations or interventions
**Example**:
> "Participants completed the study online via Qualtrics. After providing informed consent, they completed demographic questions, were randomly assigned to one of four conditions, completed the experimental task (approximately 15 minutes), and finished with the outcome measures and debriefing. The entire session lasted approximately 30 minutes."
### Data Analysis
**What to report**:
- Software used (with version)
- Significance level (α)
- Tail(s) of tests (one-tailed or two-tailed)
- Assumption checks conducted
- Missing data handling
- Outlier treatment
- Multiple comparison corrections
- Effect size measures used
**Example**:
> "All analyses were conducted using Python 3.12 with Pingouin 0.7.0, SciPy 1.18.1, and statsmodels 0.15.0. An alpha level of .05 was used for all significance tests. Assumptions of normality and homogeneity of variance were assessed using Shapiro-Wilk and Levene's tests, respectively. Missing data (< 2% for all variables) were handled using listwise deletion. Flagged observations were reviewed against source records; valid observations were retained, with prespecified robust sensitivity analyses. For the primary ANOVA, partial eta-squared (η²_p) is reported as the effect size measure. Post hoc comparisons used Tukey's HSD to control family-wise error rate."
---
## Results Section
### Descriptive Statistics
**What to report**:
- Sample size (for each group if applicable)
- Measures of central tendency (M, Mdn)
- Measures of variability (SD, IQR, range)
- Confidence intervals (when appropriate)
**Example (continuous outcome)**:
> "Group A (n = 48) had a mean score of 75.2 (SD = 8.5, 95% CI [72.7, 77.7]), while Group B (n = 52) scored 68.3 (SD = 9.2, 95% CI [65.7, 70.9])."
**Example (categorical outcome)**:
> "Of the 145 participants, 89 (61.4%) chose Option A, 42 (29.0%) chose Option B, and 14 (9.7%) chose Option C."
**Tables for descriptive statistics**:
- Use tables for multiple variables or groups
- Include M, SD, and n (minimum)
- Can include range, skewness, kurtosis if relevant
---
### Assumption Checks
**What to report**:
- Which assumptions were tested
- Results of diagnostic tests
- Evidence of departures, and limits of the checks
- Actions taken if violated
**Example**:
> "Normality was assessed using Shapiro-Wilk tests. Data for Group A (W = 0.97, p = .18) and Group B (W = 0.96, p = .12) did not significantly deviate from normality. The median-centered Levene screen did not reject equal variances, F(1, 98) = 1.23, p = .27. Non-rejection did not establish equality; prespecified Welch inference was retained, with Q-Q plots and design reviewed."
**Example (violated)**:
> "Shapiro-Wilk tests indicated significant departure from normality for Group C (W = 0.89, p = .003). The prespecified estimand and tail behavior were reviewed; any alternative rank analysis was labeled as a separate distributional sensitivity analysis, not a replacement mean test selected by this p-value."
---
### Inferential Statistics
#### T-Tests
**What to report**:
- Test statistic (t)
- Degrees of freedom
- p-value (exact if p ≥ .001, otherwise p < .001)
- Effect size (Cohen's d or Hedges' g) with CI
- Direction of effect
- Whether test was one- or two-tailed
**Format**: t(df) = value, p = value, d = value, 95% CI [lower, upper]
**Example (independent t-test)**:
> "Group A (M = 75.2, SD = 8.5) scored significantly higher than Group B (M = 68.3, SD = 9.2), t(98) = 3.82, p < .001, d = 0.77, 95% CI [0.36, 1.18], two-tailed."
**Example (paired t-test)**:
> "Scores increased significantly from pretest (M = 65.4, SD = 10.2) to posttest (M = 71.8, SD = 9.7), t(49) = 4.21, p < .001, d = 0.64, 95% CI [0.33, 0.95]."
**Example (Welch's t-test)**:
> "Due to unequal variances, Welch's t-test was used. Group A scored significantly higher than Group B, t(94.3) = 3.65, p < .001, d = 0.74."
**Example (non-significant)**:
> "There was no significant difference between Group A (M = 72.1, SD = 8.3) and Group B (M = 70.5, SD = 8.9), t(98) = 0.91, p = .36, d = 0.18, 95% CI [-0.21, 0.57]."
---
#### ANOVA
**What to report**:
- F statistic
- Degrees of freedom (effect, error)
- p-value
- Effect size (η², η²_p, or ω²)
- Means and SDs for all groups
- Prespecified contrasts and multiplicity-adjusted post hoc families, including non-significant results
**Format**: F(df_effect, df_error) = value, p = value, η²_p = value
**Example (one-way ANOVA)**:
> "There was a significant main effect of treatment condition on test scores, F(2, 147) = 8.45, p < .001, η²_p = .10. Post hoc comparisons using Tukey's HSD revealed that Condition A (M = 78.2, SD = 7.3) scored significantly higher than Condition B (M = 71.5, SD = 8.1, p = .002, d = 0.87) and Condition C (M = 70.1, SD = 7.9, p < .001, d = 1.07). Conditions B and C did not differ significantly (p = .52, d = 0.18)."
**Example (factorial ANOVA)**:
> "A 2 (feedback: positive vs. negative) × 2 (timing: immediate vs. delayed) between-subjects ANOVA revealed a significant main effect of feedback, F(1, 146) = 12.34, p < .001, η²_p = .08, but no significant main effect of timing, F(1, 146) = 2.10, p = .15, η²_p = .01. The interaction was significant, F(1, 146) = 6.78, p = .01, η²_p = .04. Simple effects analysis showed that positive feedback improved performance for immediate timing (M_diff = 8.2, p < .001) but not for delayed timing (M_diff = 1.3, p = .42)."
**Example (repeated measures ANOVA)**:
> "Mauchly's test indicated that the assumption of sphericity was violated, χ²(2) = 8.45, p = .01, therefore Greenhouse-Geisser corrected degrees of freedom are reported (ε = 0.87). A one-way repeated measures ANOVA revealed a significant effect of time point on anxiety scores, F(1.74, 85.26) = 15.67, p < .001, η²_p = .24. Pairwise comparisons with Bonferroni correction showed..."
(Note: the corrected df are the uncorrected df multiplied by ε: 2 × 0.87 = 1.74 and 98 × 0.87 = 85.26.)
---
#### Correlation
**What to report**:
- Correlation coefficient (r or ρ)
- Sample size
- p-value
- Direction and strength
- Confidence interval
- Coefficient of determination (r²) if relevant
**Format**: r(df) = value, p = value, 95% CI [lower, upper]
**Example (Pearson)**:
> "There was a moderate positive correlation between study time and exam score, r(148) = .42, p < .001, 95% CI [.27, .55], indicating that 18% of the variance in exam scores was shared with study time (r² = .18)."
**Example (Spearman)**:
> "A Spearman rank-order correlation revealed a significant positive association between class rank and motivation, ρ = .38, n = 120, p < .001, 95% CI [.21, .52]."
**Example (non-significant)**:
> "There was no significant correlation between age and reaction time, r(98) = -.12, p = .23, 95% CI [-.31, .08]."
---
#### Regression
**What to report**:
- Overall model fit (R², adjusted R², F-test)
- Coefficients (B, SE, β, t, p) for each predictor
- Effect sizes
- Confidence intervals for coefficients
- Variance inflation factors (if multicollinearity assessed)
**Format**: B = value, SE = value, β = value, t = value, p = value, 95% CI [lower, upper]
**Example (simple regression)**:
> "Simple linear regression showed that study hours significantly predicted exam scores, F(1, 148) = 42.5, p < .001, R² = .22. Specifically, each additional hour of study was associated with a 2.4-point increase in exam score (B = 2.40, SE = 0.37, β = .47, t = 6.52, p < .001, 95% CI [1.67, 3.13])."
**Example (multiple regression)**:
> "Multiple linear regression was conducted to predict exam scores from study hours, prior GPA, and attendance. The overall model was significant, F(3, 146) = 45.2, p < .001, R² = .48, adjusted R² = .47. Study hours (B = 1.80, SE = 0.31, β = .35, t = 5.78, p < .001, 95% CI [1.18, 2.42]) and prior GPA (B = 8.52, SE = 1.95, β = .28, t = 4.37, p < .001, 95% CI [4.66, 12.38]) were significant predictors, but attendance was not (B = 0.15, SE = 0.12, β = .08, t = 1.25, p = .21, 95% CI [-0.09, 0.39]). Multicollinearity was not a concern, as all VIF values were below 1.5."
**Example (logistic regression)**:
> "Logistic regression was conducted to predict pass/fail status from study hours. The overall model was significant, χ²(1) = 28.7, p < .001, Nagelkerke R² = .31. Each additional study hour increased the odds of passing by 1.35 times (OR = 1.35, 95% CI [1.18, 1.54], p < .001). The model correctly classified 76% of cases (sensitivity = 81%, specificity = 68%)."
---
#### Chi-Square Tests
**What to report**:
- χ² statistic
- Degrees of freedom
- p-value
- Effect size (Cramér's V or φ)
- Observed and expected frequencies (or percentages)
**Format**: χ²(df, N = total) = value, p = value, Cramér's V = value
**Example (2×2)**:
> "A chi-square test of independence revealed a significant association between treatment group and outcome, χ²(1, N = 150) = 8.45, p = .004, φ = .24. Specifically, 72% of participants in the treatment group improved compared to 48% in the control group."
**Example (larger table)**:
> "A chi-square test examined the relationship between education level (high school, bachelor's, graduate) and political affiliation (liberal, moderate, conservative). The association was significant, χ²(4, N = 300) = 18.7, p = .001, Cramér's V = .18, indicating a small to moderate association."
**Example (Fisher's exact)**:
> "Due to expected cell counts below 5, Fisher's exact test was used. The association between treatment and outcome was significant, p = .018 (two-tailed), OR = 3.42, 95% CI [1.21, 9.64]."
---
#### Non-Parametric Tests
**Mann-Whitney U**:
> "A Mann-Whitney U test indicated that Group A (Mdn = 75, IQR = 10) had significantly higher scores than Group B (Mdn = 68, IQR = 12), U = 845, z = 3.21, p = .001, r = .32."
**Wilcoxon signed-rank**:
> "A Wilcoxon signed-rank test showed that scores increased significantly from pretest (Mdn = 65, IQR = 15) to posttest (Mdn = 72, IQR = 14), z = 3.89, p < .001, r = .39."
**Kruskal-Wallis**:
> "A Kruskal-Wallis test revealed significant differences among the three conditions, H(2) = 15.7, p < .001, ε² = .09 (epsilon-squared). Follow-up pairwise comparisons with Bonferroni correction showed..."
---
#### Bayesian Statistics
**What to report**:
- Prior distributions used
- Posterior estimates (mean/median, credible intervals)
- Bayes Factor (if hypothesis testing)
- Convergence diagnostics (R-hat, ESS)
- Posterior predictive checks
**Example (Bayesian t-test)**:
> "A Bayesian independent samples t-test was conducted using weakly informative priors (Normal(0, 1) for mean difference). The posterior distribution of the mean difference had a mean of 6.8 (95% credible interval [3.2, 10.4]), indicating that Group A scored higher than Group B. The Bayes Factor BF₁₀ = 45.3 provided very strong evidence for a difference between groups. There was a 99.8% posterior probability that Group A's mean exceeded Group B's mean."
**Example (Bayesian regression)**:
> "A Bayesian linear regression was fitted with weakly informative priors (Normal(0, 10) for coefficients, Half-Cauchy(0, 5) for residual SD). The model showed that study hours credibly predicted exam scores (β = 0.52, 95% CrI [0.38, 0.66]; 0 not included in the credible interval). All convergence diagnostics were satisfactory (R-hat < 1.01, ESS > 1000 for all parameters). Posterior predictive checks indicated adequate model fit."
(Write "95% CrI" or "95% credible interval" for Bayesian intervals to distinguish them from frequentist confidence intervals.)
---
## Effect Sizes
### Always Report
**Why**:
- p-values don't indicate magnitude
- Required by APA and most journals
- Essential for meta-analysis
- Informs practical significance
**Which effect size?**
- T-tests: Cohen's d or Hedges' g
- ANOVA: η², η²_p, or ω²
- Correlation: r (already is an effect size)
- Regression: β (standardized), R², f²
- Chi-square: Cramér's V or φ
**With confidence intervals**:
- Always report CIs for effect sizes when possible
- Shows precision of estimate
- More informative than point estimate alone
---
## Figures and Tables
### When to Use Tables vs. Figures
**Tables**:
- Exact values needed
- Many variables/conditions
- Descriptive statistics
- Regression coefficients
- Correlation matrices
**Figures**:
- Patterns and trends
- Distributions
- Interactions
- Comparisons across groups
- Time series
### Figure Guidelines
**General**:
- Clear, readable labels
- Sufficient font size (≥ 10pt)
- High resolution (≥ 300 dpi for publications)
- Monochrome-friendly (colorblind-accessible)
- Error bars (SE or 95% CI; specify which!)
- Legend when needed
**Common figure types**:
- Bar charts: Group comparisons (include error bars)
- Box plots: Distributions, outliers
- Scatter plots: Correlations, relationships
- Line graphs: Change over time, interactions
- Violin plots: Smoothed distributions; bandwidth and sample size matter, and raw points can be more informative for small samples
**Example figure caption**:
> "Figure 1. Mean exam scores by study condition. Error bars represent 95% confidence intervals. * p < .05, ** p < .01, *** p < .001."
### Table Guidelines
**General**:
- Clear column and row labels
- Consistent decimal places (usually 2)
- Horizontal lines only (not vertical)
- Notes below table for clarifications
- Statistical symbols in italics (p, M, SD, F, t, r)
**Example table**:
**Table 1**
*Descriptive Statistics and Intercorrelations*
| Variable | M | SD | 1 | 2 | 3 |
|----------|---|----|----|----|----|
| 1. Study hours | 5.2 | 2.1 | — | | |
| 2. Prior GPA | 3.1 | 0.5 | .42** | — | |
| 3. Exam score | 75.3 | 10.2 | .47*** | .52*** | — |
*Note*. N = 150. ** p < .01. *** p < .001.
---
## Common Mistakes to Avoid
1. **Reporting p = .000**: Report p < .001 instead
2. **Omitting effect sizes**: Always include them
3. **Not reporting assumption checks**: Describe tests and outcomes
4. **Confusing statistical and practical significance**: Discuss both
5. **Only reporting significant results**: Report all planned analyses
6. **Using "prove" or "confirm"**: Use "support" or "consistent with"
7. **Saying "marginally significant" for .05 < p < .10**: Either significant or not
8. **Reporting only one decimal for p-values**: APA style uses two or three decimals (p = .03 or p = .034, not p = .0)
9. **Not specifying one- vs. two-tailed**: Always clarify
10. **Inconsistent rounding**: Be consistent throughout
---
## Null Results
### How to Report Non-Significant Findings
**Don't say**:
- "There was no effect"
- "X and Y are unrelated"
- "Groups are equivalent"
**Do say**:
- "There was no significant difference"
- "The effect was not statistically significant"
- "We did not find evidence for a relationship"
**Include**:
- Exact p-value (not just "ns" or "p > .05")
- Effect size (shows magnitude even if not significant)
- Confidence interval (may include meaningful values)
- Prespecified design power or sensitivity calculation; do not use observed-effect power to explain a null finding
**To claim equivalence**: p > .05 is not evidence of equivalence. Run an equivalence test (TOST) against a pre-specified smallest effect size of interest, or a Bayesian ROPE analysis (see bayesian_statistics.md):
```python
import pingouin as pg
# TOST: is the group difference within +/- 0.5 raw units?
print(pg.tost(group_a, group_b, bound=0.5, correction=True))
# Reject both one-sided nulls at the prespecified alpha; report bounds and assumptions.
```
**Example**:
> "Contrary to our hypothesis, there was no significant difference in creativity scores between the music (M = 72.1, SD = 8.3) and silence (M = 70.5, SD = 8.9) conditions, t(98) = 0.91, p = .36, d = 0.18, 95% CI [-0.21, 0.57]. A post hoc sensitivity analysis revealed that the study had 80% power to detect an effect of d = 0.57 or larger, characterizing design sensitivity; the confidence interval, rather than observed power, shows which effect magnitudes remain compatible with the data."
---
## Reproducibility
### Materials to Share
1. **Data**: De-identified raw data (or aggregate if sensitive)
2. **Code**: Analysis scripts
3. **Materials**: Stimuli, measures, protocols
4. **Supplements**: Additional analyses, tables
**Where to share**:
- Open Science Framework (OSF)
- GitHub (for code)
- Journal supplements
- Institutional repository
**In paper**:
> "Data, analysis code, and materials are available at https://osf.io/xxxxx/"
---
## Checklist for Statistical Reporting
- [ ] Sample size and demographics
- [ ] Study design clearly described
- [ ] All measures described with reliability
- [ ] Procedure detailed
- [ ] Software and versions specified
- [ ] Alpha level stated
- [ ] Assumption checks reported
- [ ] Descriptive statistics (M, SD, n)
- [ ] Test statistics with df and p-values
- [ ] Effect sizes with confidence intervals
- [ ] All planned analyses reported (including non-significant)
- [ ] Figures/tables properly formatted and labeled
- [ ] Multiple comparisons corrections described
- [ ] Missing data handling explained
- [ ] Limitations discussed
- [ ] Data/code availability statement
---
## Additional Resources
- APA Publication Manual (7th edition)
- CONSORT 2025 (for randomized trials; use appropriate extensions)
- STROBE guidelines (for observational studies)
- PRISMA guidelines (for systematic reviews/meta-analyses)
- Wilkinson & Task Force on Statistical Inference (1999). Statistical methods in psychology journals.
Reviewed 2026-10-01 against [APA JARS](https://apastyle.apa.org/jars), [CONSORT 2025](https://www.consort-spirit.org/_files/ugd/b5740e_a6856e5e2cf94a1db5a8005853404160.pdf), and [Pingouin TOST](https://pingouin-stats.org/generated/pingouin.tost.html). Statistical reporting does not by itself establish scientific validity, and journal-specific instructions may differ.

View File

@@ -0,0 +1,133 @@
# Statistical Test Selection Guide
Choose a model for the estimand, sampling unit and dependence structure. A Shapiro-Wilk/Levene p-value is not an automatic switch between tests. The routes below are candidates whose assumptions must match the study.
## Decision Tree for Test Selection
### 1. Comparing Groups
#### Two Independent Groups
- **Independent mean contrast**: Welch's t-test (`pg.ttest(..., correction=True)`); pooled Student's test only with justified common variance
- **Rank/distribution contrast**: Mann-Whitney U (Wilcoxon rank-sum); a median shift interpretation requires comparable distributional shapes
- **Binary outcome**: Chi-square test or Fisher's exact test (if expected counts < 5)
- **Ordinal outcome**: Mann-Whitney U test
#### Two Paired/Dependent Groups
- **Paired mean contrast**: Paired t-test on aligned within-subject differences; assess differences, not marginal normality
- **Symmetric paired difference distribution**: Wilcoxon signed-rank; otherwise consider a sign test for the prespecified median-difference question
- **Binary outcome**: McNemar's test
- **Ordinal outcome**: Signed-rank only when difference magnitudes and symmetry are meaningful; consider a sign test or ordinal model otherwise
#### Three or More Independent Groups
- **Continuous outcome, normally distributed, equal variances**: One-way ANOVA
- **Continuous outcome, normally distributed, unequal variances**: Welch's ANOVA
- **Independent rank/distribution contrast**: Kruskal-Wallis H; a median interpretation requires comparable shapes
- **Binary/categorical outcome**: Chi-square test
- **Ordinal outcome**: Kruskal-Wallis H test
#### Three or More Paired/Dependent Groups
- **Repeated continuous means**: Repeated measures ANOVA with suitable covariance/sphericity correction, or a mixed model
- **Complete blocks/repeated rank contrast**: Friedman test; missing/unequal visits may require a model
- **Binary outcome**: Cochran's Q test
#### Multiple Factors (Factorial Designs)
- **Continuous outcome**: Two-way ANOVA (or higher-way ANOVA)
- **With covariates**: ANCOVA
- **Mixed within and between factors**: Mixed ANOVA
### 2. Relationships Between Variables
#### Two Continuous Variables
- **Linear association**: Pearson correlation; usual small-sample parametric inference assumes an appropriate joint model
- **Monotone rank association**: Spearman rank correlation, selected by the estimand rather than a marginal normality test
- **Rank-based data**: Spearman or Kendall's tau
#### One Continuous Outcome, One or More Predictors
- **Single continuous predictor**: Simple linear regression
- **Multiple continuous/categorical predictors**: Multiple linear regression
- **Categorical predictors**: ANOVA/ANCOVA framework
- **Non-linear relationships**: Polynomial regression or generalized additive models (GAM)
#### Binary Outcome
- **Single predictor**: Logistic regression
- **Multiple predictors**: Multiple logistic regression
- **Rare events**: Exact logistic regression or Firth's method
#### Count Outcome
- **Poisson-distributed**: Poisson regression
- **Overdispersed counts**: Negative binomial regression
- **Excess zeros with a justified separate structural-zero process**: Zero-inflated Poisson/negative binomial; many zeros alone do not establish zero inflation
#### Time-to-Event Outcome
- **Comparing survival curves**: Log-rank test
- **Modeling with covariates**: Cox proportional hazards regression
- **Parametric survival models**: Weibull, exponential, log-normal
### 3. Agreement and Reliability
#### Inter-Rater Reliability
- **Categorical ratings, 2 raters**: Cohen's kappa
- **Categorical ratings, >2 raters**: Fleiss' kappa or Krippendorff's alpha
- **Continuous ratings**: Intraclass correlation coefficient (ICC)
#### Test-Retest Reliability
- **Continuous measurements**: Choose and report an ICC model (agreement/consistency, single/average, random/fixed raters); Pearson correlation alone does not measure agreement
- **Internal consistency**: Cronbach's alpha
#### Agreement Between Methods
- **Continuous measurements**: Bland-Altman analysis
- **Categorical classifications**: Cohen's kappa
### 4. Categorical Data Analysis
#### Contingency Tables
- **2x2 table**: Chi-square test or Fisher's exact test
- **Larger than 2x2**: Chi-square when expected counts support the approximation; current SciPy also supports generalized exact/resampling procedures
- **Ordered categories**: Cochran-Armitage trend test
- **Paired categories**: McNemar's test (2x2) or McNemar-Bowker test (larger)
### 5. Bayesian Alternatives
Any of the above tests can be performed using Bayesian methods:
- **Group comparisons**: Bayesian t-test, Bayesian ANOVA
- **Correlations**: Bayesian correlation
- **Regression**: Bayesian linear/logistic regression
**Advantages of Bayesian approaches:**
- Provides probability of hypotheses given data
- Naturally incorporates prior information
- Provides credible intervals instead of confidence intervals
- No p-value interpretation issues
## Key Considerations
### Sample Size
- No universal n=30 rule establishes validity or power. For small samples assess model assumptions; exact/permutation methods need exchangeability, tie handling and the correct sampling unit
- Very large samples: Even small effects may be statistically significant; focus on effect sizes
### Multiple Comparisons
- When conducting multiple tests, adjust for multiple comparisons using:
- Bonferroni correction (conservative)
- Holm-Bonferroni (less conservative)
- False Discovery Rate (FDR) control (Benjamini-Hochberg)
- Tukey HSD for post-hoc ANOVA comparisons
### Missing Data
- Complete case analysis (listwise deletion)
- Multiple imputation
- Maximum likelihood methods
- Ensure missing data mechanism is understood (MCAR, MAR, MNAR)
### Effect Sizes
- Always report effect sizes alongside p-values
- See `effect_sizes_and_power.md` for guidance
### Study Design Considerations
- Randomized controlled trials: Standard parametric/non-parametric tests
- Observational studies: Consider confounding and use regression/matching
- Clustered/nested data: Use mixed-effects models or GEE
- Time series: Use time series methods (ARIMA, etc.)
## Implementation sources and limits
Reviewed 2026-10-01: [SciPy Mann-Whitney](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mannwhitneyu.html), [Wilcoxon](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.wilcoxon.html), [Pingouin repeated measures](https://pingouin-stats.org/generated/pingouin.rm_anova.html). Small tied samples need an appropriate permutation/asymptotic method; the default automatic method is not universally exact. Compute rounded difference scores when floating-point subtraction creates spurious distinct ranks. Survival, Firth/exact logistic, agreement, missing-data and complex factorial routes here are design guidance, not executed implementations.