rstatspython 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rstats/__init__.py +11 -0
- rstats/_data.py +164 -0
- rstats/_posthoc.py +278 -0
- rstats/anova.py +422 -0
- rstats/categorical.py +180 -0
- rstats/descriptive.py +100 -0
- rstats/regression.py +302 -0
- rstats/result.py +68 -0
- rstats/visualization.py +180 -0
- rstatspython-0.1.0.dist-info/METADATA +177 -0
- rstatspython-0.1.0.dist-info/RECORD +13 -0
- rstatspython-0.1.0.dist-info/WHEEL +4 -0
- rstatspython-0.1.0.dist-info/licenses/LICENSE +21 -0
rstats/anova.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
"""ANOVA/ANCOVA reports with explicit designs and sums of squares."""
|
|
2
|
+
|
|
3
|
+
import warnings
|
|
4
|
+
from itertools import combinations
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import pingouin as pg
|
|
9
|
+
from patsy import ModelDesc
|
|
10
|
+
from scipy import stats
|
|
11
|
+
from statsmodels.stats.anova import anova_lm
|
|
12
|
+
|
|
13
|
+
from ._data import (
|
|
14
|
+
alpha_value,
|
|
15
|
+
clean_term,
|
|
16
|
+
complete,
|
|
17
|
+
dataframe,
|
|
18
|
+
factorize,
|
|
19
|
+
levels,
|
|
20
|
+
names,
|
|
21
|
+
numeric,
|
|
22
|
+
parse,
|
|
23
|
+
sample_table,
|
|
24
|
+
)
|
|
25
|
+
from ._posthoc import comparisons, method_name, validate_method
|
|
26
|
+
from .regression import coding_table, fit_ols, ols_diagnostics
|
|
27
|
+
from .result import AnalysisResult
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _group_descriptives(frame, outcome, factors, alpha):
|
|
31
|
+
rows = []
|
|
32
|
+
for keys, chunk in frame.groupby(factors, observed=True, sort=False):
|
|
33
|
+
keys = keys if isinstance(keys, tuple) else (keys,)
|
|
34
|
+
x = chunk[outcome].to_numpy(dtype=float)
|
|
35
|
+
n, mean = len(x), np.mean(x)
|
|
36
|
+
sd = np.std(x, ddof=1) if n > 1 else np.nan
|
|
37
|
+
margin = stats.t.ppf(1 - alpha / 2, n - 1) * sd / np.sqrt(n) if n > 1 else np.nan
|
|
38
|
+
rows.append(
|
|
39
|
+
{
|
|
40
|
+
**dict(zip(factors, keys)),
|
|
41
|
+
"n": n,
|
|
42
|
+
"mean": mean,
|
|
43
|
+
"sd": sd,
|
|
44
|
+
"median": np.median(x),
|
|
45
|
+
"mean_ci_low": mean - margin,
|
|
46
|
+
"mean_ci_high": mean + margin,
|
|
47
|
+
}
|
|
48
|
+
)
|
|
49
|
+
return pd.DataFrame(rows)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _prepare_repeated(data, spec, within, between, subject, missing):
|
|
53
|
+
if subject in spec.predictors or subject == spec.outcome:
|
|
54
|
+
raise ValueError("subject identifies people and must not appear in the model formula.")
|
|
55
|
+
columns = [spec.outcome, *spec.predictors, subject]
|
|
56
|
+
raw = dataframe(data, columns)
|
|
57
|
+
if missing not in {"raise", "drop"}:
|
|
58
|
+
raise ValueError("missing must be 'drop' or 'raise'.")
|
|
59
|
+
numeric(raw[spec.outcome], spec.outcome)
|
|
60
|
+
if np.isinf(raw[spec.outcome].to_numpy(dtype=float, na_value=np.nan)).any():
|
|
61
|
+
raise ValueError("The outcome contains infinite values.")
|
|
62
|
+
identifiable = raw.dropna(subset=[subject])
|
|
63
|
+
if identifiable.duplicated([subject, *within]).any():
|
|
64
|
+
raise ValueError(
|
|
65
|
+
"Duplicate subject-condition cells: aggregate deliberate replicates before aov()."
|
|
66
|
+
)
|
|
67
|
+
for col in between:
|
|
68
|
+
if identifiable.groupby(subject, observed=True)[col].nunique(dropna=True).gt(1).any():
|
|
69
|
+
raise ValueError(f"Between-subject factor {col!r} changes within a subject.")
|
|
70
|
+
expected_cells = int(np.prod([len(levels(raw[col])) for col in within]))
|
|
71
|
+
if not expected_cells or any(len(levels(raw[col])) < 2 for col in within):
|
|
72
|
+
raise ValueError("Each within-subject factor needs at least two observed levels.")
|
|
73
|
+
valid = []
|
|
74
|
+
for sid, chunk in identifiable.groupby(subject, observed=True):
|
|
75
|
+
if len(chunk) == expected_cells and not chunk.isna().any().any():
|
|
76
|
+
valid.append(sid)
|
|
77
|
+
frame = identifiable.loc[identifiable[subject].isin(valid)].copy().reset_index(drop=True)
|
|
78
|
+
excluded_subjects = identifiable[subject].nunique() - len(valid)
|
|
79
|
+
if missing == "raise" and (excluded_subjects or raw.isna().any().any()):
|
|
80
|
+
raise ValueError(
|
|
81
|
+
"Incomplete subjects or missing repeated cells; resolve them or use missing='drop'."
|
|
82
|
+
)
|
|
83
|
+
if len(valid) < 3:
|
|
84
|
+
raise ValueError("Repeated/mixed ANOVA needs at least three complete subjects.")
|
|
85
|
+
if between and frame.groupby(between, observed=True)[subject].nunique().min() < 2:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
"Mixed ANOVA needs at least two complete subjects per between-subject group."
|
|
88
|
+
)
|
|
89
|
+
notes = [
|
|
90
|
+
f"Analyzed {len(valid)} complete subjects ({len(frame)} rows); excluded {excluded_subjects} incomplete subjects and {int(raw[subject].isna().sum())} rows without subject IDs.",
|
|
91
|
+
"Complete-subject deletion can discard substantial information. Consider a mixed-effects model for incomplete longitudinal data.",
|
|
92
|
+
]
|
|
93
|
+
return frame, notes, len(valid), int(excluded_subjects)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def aov(
|
|
97
|
+
formula,
|
|
98
|
+
*,
|
|
99
|
+
data,
|
|
100
|
+
covariates=None,
|
|
101
|
+
type=None,
|
|
102
|
+
method="standard",
|
|
103
|
+
subject=None,
|
|
104
|
+
within=None,
|
|
105
|
+
posthocifsig=False,
|
|
106
|
+
control=None,
|
|
107
|
+
alpha=0.05,
|
|
108
|
+
correction="gg",
|
|
109
|
+
missing="drop",
|
|
110
|
+
):
|
|
111
|
+
"""ANOVA/ANCOVA with factor predictors and optional continuous covariates.
|
|
112
|
+
|
|
113
|
+
``type`` is sums of squares (I/II/III), not design. The ordinary default is
|
|
114
|
+
II. ``within`` plus ``subject`` declares repeated/mixed designs. Numeric
|
|
115
|
+
formula predictors are groups; use ``covariates=['age']`` for ANCOVA.
|
|
116
|
+
|
|
117
|
+
``posthocifsig=True`` means Tukey; a method string selects another procedure.
|
|
118
|
+
Incompatible requests raise an explanation rather than changing the test.
|
|
119
|
+
"""
|
|
120
|
+
alpha_value(alpha)
|
|
121
|
+
if method not in {"standard", "welch"}:
|
|
122
|
+
raise ValueError("method must be 'standard' or 'welch'.")
|
|
123
|
+
if correction not in {"gg", "none"}:
|
|
124
|
+
raise ValueError("correction must be 'gg' or 'none'.")
|
|
125
|
+
if type is not None and (isinstance(type, bool) or type not in {1, 2, 3}):
|
|
126
|
+
raise ValueError("type must be 1, 2, or 3 (sums of squares).")
|
|
127
|
+
spec = parse(formula)
|
|
128
|
+
factors, covars, within = spec.predictors, names(covariates), names(within)
|
|
129
|
+
if not factors or spec.outcome in factors:
|
|
130
|
+
raise ValueError("ANOVA needs at least one grouping predictor distinct from the outcome.")
|
|
131
|
+
if len(set(covars)) != len(covars) or len(set(within)) != len(within):
|
|
132
|
+
raise ValueError("covariates and within must not contain duplicate names.")
|
|
133
|
+
if set(covars) & {spec.outcome, *factors}:
|
|
134
|
+
raise ValueError(
|
|
135
|
+
"Covariates must be separate from the outcome and grouping predictors in the formula."
|
|
136
|
+
)
|
|
137
|
+
if (subject is None) != (not within):
|
|
138
|
+
raise ValueError("Repeated designs require both subject='id' and within='time'.")
|
|
139
|
+
if set(within) - set(factors):
|
|
140
|
+
raise ValueError("within must name grouping predictors in the formula.")
|
|
141
|
+
desc = ModelDesc.from_formula("y ~ " + spec.expression)
|
|
142
|
+
if not any(not t.factors for t in desc.rhs_termlist):
|
|
143
|
+
raise ValueError("aov requires an intercept; use lm for no-intercept models.")
|
|
144
|
+
posthoc = method_name(posthocifsig)
|
|
145
|
+
if method == "welch" and (len(factors) != 1 or covars or within):
|
|
146
|
+
raise ValueError("Welch ANOVA supports one independent grouping factor and no covariates.")
|
|
147
|
+
if method == "welch" and type is not None:
|
|
148
|
+
raise ValueError("Welch ANOVA does not use Type I/II/III sums of squares; omit type=.")
|
|
149
|
+
if method == "welch" and posthoc in {"tukey", "scheffe", "dunnett"}:
|
|
150
|
+
raise ValueError(
|
|
151
|
+
"That post hoc assumes equal variances. After Welch use posthocifsig='games-howell'."
|
|
152
|
+
)
|
|
153
|
+
if method == "welch" and posthoc is not None and posthoc != "games-howell":
|
|
154
|
+
raise ValueError("Welch ANOVA currently supports posthocifsig='games-howell'.")
|
|
155
|
+
between = [f for f in factors if f not in within]
|
|
156
|
+
model = None
|
|
157
|
+
excluded_subjects = 0
|
|
158
|
+
if within:
|
|
159
|
+
if (
|
|
160
|
+
covars
|
|
161
|
+
or type is not None
|
|
162
|
+
or len(within) > 2
|
|
163
|
+
or len(between) > 1
|
|
164
|
+
or (between and len(within) != 1)
|
|
165
|
+
):
|
|
166
|
+
raise ValueError(
|
|
167
|
+
"Supported repeated designs: 1–2 within factors, or 1 within + 1 between; omit covariates and type=."
|
|
168
|
+
)
|
|
169
|
+
expected_terms = {
|
|
170
|
+
frozenset(combo)
|
|
171
|
+
for size in range(1, len(factors) + 1)
|
|
172
|
+
for combo in combinations(spec.tokens, size)
|
|
173
|
+
}
|
|
174
|
+
actual_terms = {
|
|
175
|
+
frozenset(f.name() for f in term.factors) for term in desc.rhs_termlist if term.factors
|
|
176
|
+
}
|
|
177
|
+
if actual_terms != expected_terms:
|
|
178
|
+
raise ValueError(
|
|
179
|
+
"Repeated/mixed ANOVA requires the full factorial formula, e.g. 'score ~ time * group'."
|
|
180
|
+
)
|
|
181
|
+
frame, notes, n_subjects, excluded_subjects = _prepare_repeated(
|
|
182
|
+
data, spec, within, between, subject, missing
|
|
183
|
+
)
|
|
184
|
+
else:
|
|
185
|
+
frame, notes = complete(data, [spec.outcome, *factors, *covars], missing)
|
|
186
|
+
numeric(frame[spec.outcome], spec.outcome)
|
|
187
|
+
if frame[spec.outcome].nunique() < 2:
|
|
188
|
+
raise ValueError("The outcome must vary to compute ANOVA.")
|
|
189
|
+
for col in covars:
|
|
190
|
+
numeric(frame[col], col)
|
|
191
|
+
coding = factorize(frame, factors)
|
|
192
|
+
if within or method == "welch" or type == 3:
|
|
193
|
+
for value in coding.values():
|
|
194
|
+
value["reference"] = (
|
|
195
|
+
"not applicable (sum contrasts)" if type == 3 else "not applicable (effect tests)"
|
|
196
|
+
)
|
|
197
|
+
validate_method(
|
|
198
|
+
posthoc,
|
|
199
|
+
factors=factors,
|
|
200
|
+
covariates=covars,
|
|
201
|
+
repeated=bool(within),
|
|
202
|
+
control=control,
|
|
203
|
+
frame=frame,
|
|
204
|
+
)
|
|
205
|
+
tables = {
|
|
206
|
+
"sample": sample_table(len(data), len(frame)),
|
|
207
|
+
"group_descriptives": _group_descriptives(frame, spec.outcome, factors, alpha),
|
|
208
|
+
"coding": coding_table(coding),
|
|
209
|
+
}
|
|
210
|
+
effect_map = {}
|
|
211
|
+
if within:
|
|
212
|
+
if between:
|
|
213
|
+
raw = pg.mixed_anova(
|
|
214
|
+
data=frame,
|
|
215
|
+
dv=spec.outcome,
|
|
216
|
+
within=within[0],
|
|
217
|
+
between=between[0],
|
|
218
|
+
subject=subject,
|
|
219
|
+
correction=True,
|
|
220
|
+
effsize="np2",
|
|
221
|
+
)
|
|
222
|
+
effect_map = {
|
|
223
|
+
between[0]: [between[0]],
|
|
224
|
+
within[0]: [within[0]],
|
|
225
|
+
"Interaction": [between[0], within[0]],
|
|
226
|
+
}
|
|
227
|
+
notes.append(
|
|
228
|
+
"Mixed-design effect tests use the backend's Type II convention for unequal between-group sample sizes; this can differ from Type III software defaults."
|
|
229
|
+
)
|
|
230
|
+
design = "mixed"
|
|
231
|
+
else:
|
|
232
|
+
raw = pg.rm_anova(
|
|
233
|
+
data=frame,
|
|
234
|
+
dv=spec.outcome,
|
|
235
|
+
within=within,
|
|
236
|
+
subject=subject,
|
|
237
|
+
detailed=True,
|
|
238
|
+
correction=True,
|
|
239
|
+
effsize="np2",
|
|
240
|
+
)
|
|
241
|
+
effect_map = {name: name.split(" * ") for name in raw.Source if name != "Error"}
|
|
242
|
+
design = "repeated"
|
|
243
|
+
tests = raw.rename(
|
|
244
|
+
columns={
|
|
245
|
+
"Source": "effect",
|
|
246
|
+
"SS": "sum_sq",
|
|
247
|
+
"MS": "mean_sq",
|
|
248
|
+
"DF": "df_numerator",
|
|
249
|
+
"DF1": "df_numerator",
|
|
250
|
+
"ddof1": "df_numerator",
|
|
251
|
+
"DF2": "df_denominator",
|
|
252
|
+
"ddof2": "df_denominator",
|
|
253
|
+
"p_unc": "p_uncorrected",
|
|
254
|
+
"p_GG_corr": "p_gg",
|
|
255
|
+
"np2": "partial_eta_squared",
|
|
256
|
+
}
|
|
257
|
+
)
|
|
258
|
+
if "df_denominator" not in tests:
|
|
259
|
+
# Pingouin's detailed one-factor RM table puts the error df on its
|
|
260
|
+
# own row; multi-factor designs carry a denominator on each effect.
|
|
261
|
+
error_df = tests.loc[tests.effect == "Error", "df_numerator"].iloc[0]
|
|
262
|
+
tests["df_denominator"] = np.where(tests.effect == "Error", np.nan, error_df)
|
|
263
|
+
tests["p"] = (
|
|
264
|
+
tests["p_gg"].fillna(tests["p_uncorrected"])
|
|
265
|
+
if correction == "gg" and "p_gg" in tests
|
|
266
|
+
else tests["p_uncorrected"]
|
|
267
|
+
)
|
|
268
|
+
tests["primary_inference"] = np.where(
|
|
269
|
+
tests.get("p_gg", pd.Series(np.nan, index=tests.index)).notna() & (correction == "gg"),
|
|
270
|
+
"Greenhouse–Geisser",
|
|
271
|
+
"uncorrected",
|
|
272
|
+
)
|
|
273
|
+
if "eps" in tests and "df_denominator" in tests:
|
|
274
|
+
tests["df_numerator_gg"] = tests["df_numerator"] * tests["eps"]
|
|
275
|
+
tests["df_denominator_gg"] = tests["df_denominator"] * tests["eps"]
|
|
276
|
+
tables["subjects"] = pd.DataFrame(
|
|
277
|
+
[{"analyzed_subjects": n_subjects, "excluded_subjects": excluded_subjects}]
|
|
278
|
+
)
|
|
279
|
+
notes.extend(
|
|
280
|
+
[
|
|
281
|
+
"Greenhouse–Geisser corrected inference is primary where available unless correction='none'; both p values are shown. No diagnostic-driven switching is performed.",
|
|
282
|
+
"Cell mean CIs are pointwise descriptive intervals, not within-subject contrast intervals.",
|
|
283
|
+
]
|
|
284
|
+
)
|
|
285
|
+
elif method == "welch":
|
|
286
|
+
factor = factors[0]
|
|
287
|
+
if (
|
|
288
|
+
frame.groupby(factor, observed=True)[spec.outcome]
|
|
289
|
+
.agg(["count", "var"])
|
|
290
|
+
.pipe(lambda t: (t["count"] < 2).any() or (t["var"] <= 0).any())
|
|
291
|
+
):
|
|
292
|
+
raise ValueError(
|
|
293
|
+
"Welch ANOVA needs at least two observations and positive variance in each group."
|
|
294
|
+
)
|
|
295
|
+
tests = pg.welch_anova(data=frame, dv=spec.outcome, between=factor).rename(
|
|
296
|
+
columns={
|
|
297
|
+
"Source": "effect",
|
|
298
|
+
"ddof1": "df_numerator",
|
|
299
|
+
"ddof2": "df_denominator",
|
|
300
|
+
"p_unc": "p",
|
|
301
|
+
"np2": "partial_eta_squared",
|
|
302
|
+
}
|
|
303
|
+
)
|
|
304
|
+
effect_map = {factor: [factor]}
|
|
305
|
+
design = "one-way Welch"
|
|
306
|
+
notes.append(
|
|
307
|
+
"Welch ANOVA permits unequal group variances; its denominator degrees of freedom are approximate."
|
|
308
|
+
)
|
|
309
|
+
else:
|
|
310
|
+
fit_spec = parse(formula + "".join(f" + `{c}`" for c in covars))
|
|
311
|
+
backend = fit_spec.backend(factors, sum_contrasts=type == 3)
|
|
312
|
+
with warnings.catch_warnings():
|
|
313
|
+
warnings.simplefilter("error", RuntimeWarning)
|
|
314
|
+
try:
|
|
315
|
+
model = fit_ols(backend, frame)
|
|
316
|
+
raw = anova_lm(model, typ=type or 2)
|
|
317
|
+
except RuntimeWarning as exc:
|
|
318
|
+
raise ValueError(
|
|
319
|
+
"ANOVA inference is undefined; inspect empty cells or a zero residual variance."
|
|
320
|
+
) from exc
|
|
321
|
+
tests = raw.rename(columns={"PR(>F)": "p", "df": "df_numerator"}).copy()
|
|
322
|
+
tests["mean_sq"] = tests.sum_sq / tests.df_numerator
|
|
323
|
+
tests["df_denominator"] = model.df_resid
|
|
324
|
+
tests["partial_eta_squared"] = tests.sum_sq / (tests.sum_sq + model.ssr)
|
|
325
|
+
tests.loc["Residual", ["partial_eta_squared", "df_denominator"]] = np.nan
|
|
326
|
+
for term in raw.index:
|
|
327
|
+
if term not in {"Intercept", "Residual"}:
|
|
328
|
+
members = [f for f in factors if f"Q({f!r})" in term]
|
|
329
|
+
if members:
|
|
330
|
+
effect_map[clean_term(term, fit_spec)] = members
|
|
331
|
+
tests.index = [clean_term(str(term), fit_spec) for term in tests.index]
|
|
332
|
+
tests = tests.rename_axis("effect").reset_index()
|
|
333
|
+
tables["model"] = pd.DataFrame(
|
|
334
|
+
[
|
|
335
|
+
{
|
|
336
|
+
"n": int(model.nobs),
|
|
337
|
+
"F": model.fvalue,
|
|
338
|
+
"df_model": model.df_model,
|
|
339
|
+
"df_residual": model.df_resid,
|
|
340
|
+
"p": model.f_pvalue,
|
|
341
|
+
"r_squared": model.rsquared,
|
|
342
|
+
"adjusted_r_squared": model.rsquared_adj,
|
|
343
|
+
}
|
|
344
|
+
]
|
|
345
|
+
)
|
|
346
|
+
diagnostic_table, diagnostic_notes = ols_diagnostics(model)
|
|
347
|
+
tables["diagnostics"] = diagnostic_table
|
|
348
|
+
notes.extend(diagnostic_notes)
|
|
349
|
+
notes.append(
|
|
350
|
+
f"Type {type or 2} sums of squares; {'sum' if type == 3 else 'treatment'} contrasts. Group descriptives are unadjusted; ANCOVA comparisons use covariate-adjusted marginal means."
|
|
351
|
+
)
|
|
352
|
+
if type == 1:
|
|
353
|
+
notes.append("Type I tests are sequential and depend on formula term order.")
|
|
354
|
+
if any(len(t.factors) > 1 for t in desc.rhs_termlist):
|
|
355
|
+
notes.append(
|
|
356
|
+
"Interpret main effects cautiously when interactions are present. Type II main effects do not adjust for interactions containing that effect."
|
|
357
|
+
)
|
|
358
|
+
design = "ANCOVA" if covars else "between-subjects"
|
|
359
|
+
effect_tests = tests.loc[tests.effect.isin(effect_map)]
|
|
360
|
+
if not np.isfinite(effect_tests["F"]).all() or not np.isfinite(effect_tests["p"]).all():
|
|
361
|
+
raise ValueError(
|
|
362
|
+
"ANOVA returned undefined effect tests; inspect degenerate variances or insufficient replication."
|
|
363
|
+
)
|
|
364
|
+
tables["anova"] = tests
|
|
365
|
+
significant = [effect_map[row.effect] for row in effect_tests.itertuples() if row.p < alpha]
|
|
366
|
+
posthoc_table = comparisons(
|
|
367
|
+
posthoc,
|
|
368
|
+
significant,
|
|
369
|
+
frame=frame,
|
|
370
|
+
outcome=spec.outcome,
|
|
371
|
+
factors=factors,
|
|
372
|
+
covariates=covars,
|
|
373
|
+
model=model,
|
|
374
|
+
alpha=alpha,
|
|
375
|
+
control=control,
|
|
376
|
+
subject=subject,
|
|
377
|
+
within=within,
|
|
378
|
+
)
|
|
379
|
+
if posthoc_table is not None:
|
|
380
|
+
tables["posthoc"] = posthoc_table
|
|
381
|
+
notes.append(
|
|
382
|
+
f"Post hoc method: {posthoc}; comparisons run only for relevant omnibus p < {alpha:g}. Adjustment families include all comparisons generated for each triggering effect."
|
|
383
|
+
)
|
|
384
|
+
if not significant:
|
|
385
|
+
notes.append(
|
|
386
|
+
"No relevant omnibus effect was significant; no post hoc comparisons were run."
|
|
387
|
+
)
|
|
388
|
+
if posthoc in {"fdr-bh", "fdr-by"}:
|
|
389
|
+
notes.append(
|
|
390
|
+
"This is exploratory false-discovery-rate control, not familywise error control. Omnibus gating is an additional selection step, not a guarantee of global error control."
|
|
391
|
+
)
|
|
392
|
+
if posthoc in {"sidak", "holm-sidak"}:
|
|
393
|
+
notes.append(
|
|
394
|
+
"Šidák procedures rely on independence or suitable dependence assumptions; Holm is a safer general-purpose choice under arbitrary dependence."
|
|
395
|
+
)
|
|
396
|
+
if posthoc == "dunnett":
|
|
397
|
+
notes.append(
|
|
398
|
+
"Dunnett probabilities/CIs use numerical multivariate-t integration with a fixed seed; small numerical differences are possible."
|
|
399
|
+
)
|
|
400
|
+
if posthoc not in {"tukey", "games-howell", "dunnett", "scheffe"}:
|
|
401
|
+
notes.append(
|
|
402
|
+
"Post hoc confidence intervals are pointwise; significance uses adjusted p values. Interaction families contain simple effects in each conditioning stratum."
|
|
403
|
+
)
|
|
404
|
+
notes.append(
|
|
405
|
+
"Mean differences are not causal effects unless justified by the study design. Assumption diagnostics never automatically replace the requested test."
|
|
406
|
+
)
|
|
407
|
+
return AnalysisResult(
|
|
408
|
+
f"ANOVA — {design}",
|
|
409
|
+
tables,
|
|
410
|
+
notes,
|
|
411
|
+
{
|
|
412
|
+
"formula": formula,
|
|
413
|
+
"design": design,
|
|
414
|
+
"type": (type or 2) if not within and method != "welch" else None,
|
|
415
|
+
"method": method,
|
|
416
|
+
"alpha": alpha,
|
|
417
|
+
"posthoc": posthoc,
|
|
418
|
+
"coding": coding,
|
|
419
|
+
"covariates": covars,
|
|
420
|
+
},
|
|
421
|
+
model,
|
|
422
|
+
)
|
rstats/categorical.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Frequency tables and categorical tests."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from scipy import stats
|
|
6
|
+
|
|
7
|
+
from ._data import complete, dataframe, parse
|
|
8
|
+
from .result import AnalysisResult
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _variables(formula):
|
|
12
|
+
if isinstance(formula, str) and "~" not in formula:
|
|
13
|
+
return [formula.strip().strip("`")]
|
|
14
|
+
spec = parse(formula)
|
|
15
|
+
if len(spec.predictors) != 1 or any(c in spec.expression for c in "*:+-()"):
|
|
16
|
+
raise ValueError("Use 'row ~ column' for a two-way categorical table.")
|
|
17
|
+
return [spec.outcome, spec.predictors[0]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def table(formula, *, data, percent="valid", missing="drop"):
|
|
21
|
+
"""Counts and percentages: ``table('group ~ passed', data=df, percent='row')``.
|
|
22
|
+
|
|
23
|
+
Missing values are excluded and counted separately. ``percent='valid'``
|
|
24
|
+
uses the valid grand total; row/column/total apply to two-way tables.
|
|
25
|
+
"""
|
|
26
|
+
if percent not in {"valid", "row", "column", "total"}:
|
|
27
|
+
raise ValueError("percent must be 'valid', 'row', 'column', or 'total'.")
|
|
28
|
+
cols = _variables(formula)
|
|
29
|
+
raw = dataframe(data, cols)
|
|
30
|
+
frame, notes = complete(data, cols, missing)
|
|
31
|
+
if len(cols) == 1:
|
|
32
|
+
if percent not in {"valid", "total"}:
|
|
33
|
+
raise ValueError("One-way tables use percent='valid' or 'total'.")
|
|
34
|
+
counts = frame[cols[0]].value_counts(sort=False).rename("count").to_frame()
|
|
35
|
+
counts = counts.loc[counts["count"] > 0]
|
|
36
|
+
percentages = (100 * counts / len(frame)).rename(columns={"count": "percent"})
|
|
37
|
+
denominator = len(frame)
|
|
38
|
+
else:
|
|
39
|
+
counts = pd.crosstab(frame[cols[0]], frame[cols[1]])
|
|
40
|
+
denominator = (
|
|
41
|
+
counts.sum(axis=1)
|
|
42
|
+
if percent == "row"
|
|
43
|
+
else counts.sum(axis=0)
|
|
44
|
+
if percent == "column"
|
|
45
|
+
else counts.to_numpy().sum()
|
|
46
|
+
)
|
|
47
|
+
percentages = counts.div(denominator, axis=0 if percent == "row" else 1) * 100
|
|
48
|
+
notes.append(
|
|
49
|
+
f"Percentages use {'the valid grand total' if percent in {'valid', 'total'} else percent + ' totals'} as denominator."
|
|
50
|
+
)
|
|
51
|
+
return AnalysisResult(
|
|
52
|
+
"Frequency table",
|
|
53
|
+
{
|
|
54
|
+
"counts": counts,
|
|
55
|
+
"percentages": percentages,
|
|
56
|
+
"missing": raw.isna().sum().rename("missing").to_frame(),
|
|
57
|
+
},
|
|
58
|
+
notes,
|
|
59
|
+
{"percent": percent, "denominator": denominator},
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def chisq(formula, *, data=None, expected=None, method="pearson", correction=False, missing="drop"):
|
|
64
|
+
"""Pearson independence/GOF test, or explicit Fisher exact for a 2×2 table.
|
|
65
|
+
|
|
66
|
+
``chisq('group ~ passed', data=df)`` tests independence.
|
|
67
|
+
``chisq([20, 30, 50], expected=[.25, .25, .5])`` tests count proportions.
|
|
68
|
+
"""
|
|
69
|
+
if method not in {"pearson", "fisher"}:
|
|
70
|
+
raise ValueError("method must be 'pearson' or 'fisher'.")
|
|
71
|
+
if not isinstance(correction, bool):
|
|
72
|
+
raise TypeError(
|
|
73
|
+
"correction must be True or False (Yates correction for 2×2 Pearson tests)."
|
|
74
|
+
)
|
|
75
|
+
if isinstance(formula, str):
|
|
76
|
+
cols = _variables(formula)
|
|
77
|
+
if len(cols) != 2:
|
|
78
|
+
raise ValueError(
|
|
79
|
+
"For independence use 'group ~ outcome'; for goodness of fit pass a count vector."
|
|
80
|
+
)
|
|
81
|
+
if expected is not None:
|
|
82
|
+
raise ValueError("expected proportions apply only to goodness-of-fit count vectors.")
|
|
83
|
+
frame, notes = complete(data, cols, missing)
|
|
84
|
+
observed = pd.crosstab(frame[cols[0]], frame[cols[1]])
|
|
85
|
+
if min(observed.shape) < 2:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
"An independence test needs at least two observed levels per variable."
|
|
88
|
+
)
|
|
89
|
+
if correction and observed.shape != (2, 2):
|
|
90
|
+
raise ValueError("Yates correction is supported only for 2×2 tables.")
|
|
91
|
+
chi2, p, dof, exp = stats.chi2_contingency(observed, correction=correction)
|
|
92
|
+
residuals = (observed.to_numpy() - exp) / np.sqrt(exp)
|
|
93
|
+
if method == "fisher":
|
|
94
|
+
if observed.shape != (2, 2) or correction:
|
|
95
|
+
raise ValueError("Fisher's test needs a 2×2 table and correction=False.")
|
|
96
|
+
fisher = stats.fisher_exact(observed.to_numpy())
|
|
97
|
+
summary = {"odds_ratio": fisher.statistic, "p": fisher.pvalue, "n": len(frame)}
|
|
98
|
+
title = "Fisher exact test (two-sided)"
|
|
99
|
+
else:
|
|
100
|
+
summary = {
|
|
101
|
+
"chi2": chi2,
|
|
102
|
+
"df": dof,
|
|
103
|
+
"p": p,
|
|
104
|
+
"n": len(frame),
|
|
105
|
+
"cramers_v": np.sqrt(
|
|
106
|
+
stats.chi2_contingency(observed, correction=False)[0]
|
|
107
|
+
/ (len(frame) * min(np.array(observed.shape) - 1))
|
|
108
|
+
),
|
|
109
|
+
}
|
|
110
|
+
title = "Pearson chi-square test of independence"
|
|
111
|
+
tables = {
|
|
112
|
+
"test": pd.DataFrame([summary]),
|
|
113
|
+
"observed": observed,
|
|
114
|
+
"expected": pd.DataFrame(exp, index=observed.index, columns=observed.columns),
|
|
115
|
+
"pearson_residuals": pd.DataFrame(
|
|
116
|
+
residuals, index=observed.index, columns=observed.columns
|
|
117
|
+
),
|
|
118
|
+
}
|
|
119
|
+
notes.append(
|
|
120
|
+
f"Continuity correction: {'Yates' if correction else 'none'}. Expected counts and residuals describe the independence model."
|
|
121
|
+
)
|
|
122
|
+
else:
|
|
123
|
+
if method != "pearson" or correction:
|
|
124
|
+
raise ValueError("Goodness of fit uses method='pearson', correction=False.")
|
|
125
|
+
obs = np.asarray(formula, dtype=float)
|
|
126
|
+
if (
|
|
127
|
+
obs.ndim != 1
|
|
128
|
+
or len(obs) < 2
|
|
129
|
+
or not np.isfinite(obs).all()
|
|
130
|
+
or (obs < 0).any()
|
|
131
|
+
or obs.sum() <= 0
|
|
132
|
+
or not np.equal(obs, np.floor(obs)).all()
|
|
133
|
+
):
|
|
134
|
+
raise ValueError(
|
|
135
|
+
"Supply at least two nonnegative integer counts with a positive total."
|
|
136
|
+
)
|
|
137
|
+
proportions = (
|
|
138
|
+
np.ones(len(obs)) / len(obs) if expected is None else np.asarray(expected, dtype=float)
|
|
139
|
+
)
|
|
140
|
+
if (
|
|
141
|
+
proportions.shape != obs.shape
|
|
142
|
+
or not np.isfinite(proportions).all()
|
|
143
|
+
or (proportions <= 0).any()
|
|
144
|
+
or not np.isclose(proportions.sum(), 1)
|
|
145
|
+
):
|
|
146
|
+
raise ValueError(
|
|
147
|
+
"expected must contain positive proportions summing to 1, one per category."
|
|
148
|
+
)
|
|
149
|
+
exp = proportions * obs.sum()
|
|
150
|
+
test = stats.chisquare(obs, exp)
|
|
151
|
+
tables = {
|
|
152
|
+
"test": pd.DataFrame(
|
|
153
|
+
[
|
|
154
|
+
{
|
|
155
|
+
"chi2": test.statistic,
|
|
156
|
+
"df": len(obs) - 1,
|
|
157
|
+
"p": test.pvalue,
|
|
158
|
+
"n": int(obs.sum()),
|
|
159
|
+
"cohens_w": np.sqrt(test.statistic / obs.sum()),
|
|
160
|
+
}
|
|
161
|
+
]
|
|
162
|
+
),
|
|
163
|
+
"counts": pd.DataFrame(
|
|
164
|
+
{"observed": obs, "expected": exp, "pearson_residual": (obs - exp) / np.sqrt(exp)}
|
|
165
|
+
),
|
|
166
|
+
}
|
|
167
|
+
title, notes = (
|
|
168
|
+
"Chi-square goodness-of-fit test",
|
|
169
|
+
[
|
|
170
|
+
"Expected proportions must be specified independently of these observations; fitted-probability degrees of freedom are not supported."
|
|
171
|
+
],
|
|
172
|
+
)
|
|
173
|
+
if (exp < 1).any() or (exp < 5).mean() > 0.2:
|
|
174
|
+
notes.append(
|
|
175
|
+
"Sparse expected cells: chi-square asymptotic inference may be unreliable. For a 2×2 table consider method='fisher'."
|
|
176
|
+
)
|
|
177
|
+
notes.append(
|
|
178
|
+
"Independent observations are required; these tests are not for paired categorical measurements."
|
|
179
|
+
)
|
|
180
|
+
return AnalysisResult(title, tables, notes, {"method": method, "correction": correction})
|