rstatspython 0.1.0__tar.gz → 0.1.1__tar.gz
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.
- {rstatspython-0.1.0 → rstatspython-0.1.1}/PKG-INFO +12 -10
- {rstatspython-0.1.0 → rstatspython-0.1.1}/README.md +10 -8
- {rstatspython-0.1.0 → rstatspython-0.1.1}/docs/api.md +4 -2
- {rstatspython-0.1.0 → rstatspython-0.1.1}/docs/publishing.md +6 -5
- {rstatspython-0.1.0 → rstatspython-0.1.1}/docs/validation.md +16 -6
- {rstatspython-0.1.0 → rstatspython-0.1.1}/examples/quickstart.ipynb +1 -1
- {rstatspython-0.1.0 → rstatspython-0.1.1}/pyproject.toml +2 -2
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/__init__.py +1 -1
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/anova.py +62 -1
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/categorical.py +41 -25
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/test_behavior.py +31 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tools/build_teaching.py +1 -1
- {rstatspython-0.1.0 → rstatspython-0.1.1}/.gitignore +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/LICENSE +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/docs/Rstats-quickstart.pptx +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/docs/anova.md +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/docs/statistics.md +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/examples/anova-report.html +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/examples/longitudinal.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/examples/regression-report.html +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/examples/students.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/_data.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/_posthoc.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/descriptive.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/regression.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/result.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/src/rstats/visualization.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/conftest.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/R-extended-session.txt +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/R-session.txt +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/README.md +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/ancova.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/ancova_posthoc_BH.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/ancova_posthoc_BY.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/ancova_posthoc_bonferroni.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/ancova_posthoc_holm.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/chisq.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/dunnett.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/extended.R +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/factorial.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/games_howell.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/generate.R +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/gg_epsilon.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/gof.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/lm_multiple_coefficients.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/lm_multiple_model.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/lm_simple_coefficients.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/lm_simple_model.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/logistic_coefficients.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/logistic_model.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/mixed.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/oneway.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/repeated_one.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/repeated_two.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/repeated_two.csv.expected +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/scheffe.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/tukey.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/type1.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/type2.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/type3.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/reference/welch.csv +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/test_r_reference.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tests/test_visualization.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tools/check_deck.py +0 -0
- {rstatspython-0.1.0 → rstatspython-0.1.1}/tools/execute_notebook.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: rstatspython
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.1
|
|
4
4
|
Summary: Familiar commands. Complete statistical reports.
|
|
5
5
|
Project-URL: Repository, https://github.com/drdanrb/Rstats
|
|
6
6
|
Author: Rstats contributors
|
|
@@ -16,7 +16,7 @@ Requires-Dist: matplotlib>=3.9
|
|
|
16
16
|
Requires-Dist: numpy>=2.0
|
|
17
17
|
Requires-Dist: pandas<4,>=2.2
|
|
18
18
|
Requires-Dist: patsy>=1.0
|
|
19
|
-
Requires-Dist: pingouin<0.
|
|
19
|
+
Requires-Dist: pingouin<0.7,>=0.6.1
|
|
20
20
|
Requires-Dist: scipy>=1.16
|
|
21
21
|
Requires-Dist: seaborn>=0.13.2
|
|
22
22
|
Requires-Dist: statsmodels<0.16,>=0.14.4
|
|
@@ -45,11 +45,10 @@ otherwise require several separate calls. Plot independently with `vis()`.
|
|
|
45
45
|
## Install
|
|
46
46
|
|
|
47
47
|
Python 3.12+; see CI for tested versions. This is an early research/teaching
|
|
48
|
-
release
|
|
49
|
-
`rstats` PyPI package.** Install directly from GitHub:
|
|
48
|
+
release. Install [rstatspython from PyPI](https://pypi.org/project/rstatspython/):
|
|
50
49
|
|
|
51
50
|
```bash
|
|
52
|
-
python -m pip install
|
|
51
|
+
python -m pip install -U rstatspython
|
|
53
52
|
```
|
|
54
53
|
|
|
55
54
|
Or from the root of the supplied source checkout:
|
|
@@ -64,11 +63,13 @@ is required to use the library. In Colab, prefix the installation command with
|
|
|
64
63
|
**Runtime → Run all**. The notebook installs Rstats if necessary and downloads
|
|
65
64
|
the synthetic example data automatically; no file uploads are needed.
|
|
66
65
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
66
|
+
For Colab, use version 0.1.1 or newer. If version 0.1.0 upgraded pandas in your
|
|
67
|
+
session, start a fresh runtime or run
|
|
68
|
+
`%pip install -U "rstatspython>=0.1.1" "pandas==2.2.3"` and restart the session.
|
|
69
|
+
The PyPI distribution is `rstatspython` and the import is `rstats`.
|
|
70
|
+
To install the development version instead, use
|
|
71
|
+
`python -m pip install git+https://github.com/drdanrb/Rstats.git`.
|
|
72
|
+
See the [publishing instructions](docs/publishing.md) for maintaining releases.
|
|
72
73
|
|
|
73
74
|
## One-line analyses
|
|
74
75
|
|
|
@@ -79,6 +80,7 @@ import rstats as rs
|
|
|
79
80
|
df = pd.read_csv("https://raw.githubusercontent.com/drdanrb/Rstats/main/examples/students.csv")
|
|
80
81
|
|
|
81
82
|
rs.descriptives(data=df, columns=["score", "study_hours"], by="group")
|
|
83
|
+
rs.table("group", data=df)
|
|
82
84
|
rs.table("group ~ passed", data=df, percent="row")
|
|
83
85
|
rs.chisq("group ~ passed", data=df)
|
|
84
86
|
rs.aov("score ~ group", data=df, posthocifsig=True)
|
|
@@ -12,11 +12,10 @@ otherwise require several separate calls. Plot independently with `vis()`.
|
|
|
12
12
|
## Install
|
|
13
13
|
|
|
14
14
|
Python 3.12+; see CI for tested versions. This is an early research/teaching
|
|
15
|
-
release
|
|
16
|
-
`rstats` PyPI package.** Install directly from GitHub:
|
|
15
|
+
release. Install [rstatspython from PyPI](https://pypi.org/project/rstatspython/):
|
|
17
16
|
|
|
18
17
|
```bash
|
|
19
|
-
python -m pip install
|
|
18
|
+
python -m pip install -U rstatspython
|
|
20
19
|
```
|
|
21
20
|
|
|
22
21
|
Or from the root of the supplied source checkout:
|
|
@@ -31,11 +30,13 @@ is required to use the library. In Colab, prefix the installation command with
|
|
|
31
30
|
**Runtime → Run all**. The notebook installs Rstats if necessary and downloads
|
|
32
31
|
the synthetic example data automatically; no file uploads are needed.
|
|
33
32
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
33
|
+
For Colab, use version 0.1.1 or newer. If version 0.1.0 upgraded pandas in your
|
|
34
|
+
session, start a fresh runtime or run
|
|
35
|
+
`%pip install -U "rstatspython>=0.1.1" "pandas==2.2.3"` and restart the session.
|
|
36
|
+
The PyPI distribution is `rstatspython` and the import is `rstats`.
|
|
37
|
+
To install the development version instead, use
|
|
38
|
+
`python -m pip install git+https://github.com/drdanrb/Rstats.git`.
|
|
39
|
+
See the [publishing instructions](docs/publishing.md) for maintaining releases.
|
|
39
40
|
|
|
40
41
|
## One-line analyses
|
|
41
42
|
|
|
@@ -46,6 +47,7 @@ import rstats as rs
|
|
|
46
47
|
df = pd.read_csv("https://raw.githubusercontent.com/drdanrb/Rstats/main/examples/students.csv")
|
|
47
48
|
|
|
48
49
|
rs.descriptives(data=df, columns=["score", "study_hours"], by="group")
|
|
50
|
+
rs.table("group", data=df)
|
|
49
51
|
rs.table("group ~ passed", data=df, percent="row")
|
|
50
52
|
rs.chisq("group ~ passed", data=df)
|
|
51
53
|
rs.aov("score ~ group", data=df, posthocifsig=True)
|
|
@@ -32,7 +32,7 @@ counts, valid percentages, and missing n. Undefined quantities remain missing.
|
|
|
32
32
|
|
|
33
33
|
## `table(formula, *, data, percent="valid", missing="drop")`
|
|
34
34
|
|
|
35
|
-
`"group"` produces a one-way table
|
|
35
|
+
`"group"` or `"~ group"` produces a one-way table. `"group ~ passed"` produces a two-way
|
|
36
36
|
table with the left side as rows and right side as columns.
|
|
37
37
|
`percent="valid"`/`"total"` uses the valid grand total; `"row"` and `"column"`
|
|
38
38
|
use their respective two-way totals. Counts, percentages, and variable-specific
|
|
@@ -46,7 +46,9 @@ Yates correction on a 2×2 table; the association effect size remains uncorrecte
|
|
|
46
46
|
`method="fisher"` requests a two-sided 2×2 Fisher exact test with sample odds
|
|
47
47
|
ratio. Fisher does not use a continuity correction.
|
|
48
48
|
|
|
49
|
-
For goodness of fit, pass
|
|
49
|
+
For goodness of fit against equal proportions, pass a single column, for example
|
|
50
|
+
`rs.chisq("group", data=df)`. To specify unequal expected probabilities, pass
|
|
51
|
+
counts directly in the same order as the probabilities:
|
|
50
52
|
|
|
51
53
|
```python
|
|
52
54
|
rs.chisq([20, 30, 50], expected=[.25, .25, .5])
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# Publish Rstats to PyPI
|
|
2
2
|
|
|
3
3
|
The distribution name is **rstatspython**; Python code still uses
|
|
4
|
-
`import rstats as rs`.
|
|
5
|
-
|
|
4
|
+
`import rstats as rs`. Version **0.1.0** was published successfully on
|
|
5
|
+
[PyPI](https://pypi.org/project/rstatspython/0.1.0/) on 1 December 2026.
|
|
6
|
+
The initial Trusted Publisher setup below is complete for this project.
|
|
6
7
|
|
|
7
8
|
## One-time owner setup
|
|
8
9
|
|
|
@@ -48,9 +49,9 @@ python -m pip install rstatspython==0.1.0
|
|
|
48
49
|
python -c "import rstats as rs; print(rs.__version__)"
|
|
49
50
|
```
|
|
50
51
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
The README and notebook now use `pip install rstatspython`; a fresh registry
|
|
53
|
+
installation has been verified. The GitHub development installation remains
|
|
54
|
+
available as an alternative.
|
|
54
55
|
|
|
55
56
|
## Later versions
|
|
56
57
|
|
|
@@ -35,7 +35,6 @@ statistical failures; they are not globally hidden by Rstats.
|
|
|
35
35
|
|
|
36
36
|
- A live Google Colab session.
|
|
37
37
|
- Native Windows/macOS execution or PowerPoint rendering.
|
|
38
|
-
- PyPI publication or installation by distribution name from PyPI.
|
|
39
38
|
- External academic peer review or exhaustive design coverage.
|
|
40
39
|
|
|
41
40
|
The included notebook is prepared for Colab use: it installs Rstats if needed
|
|
@@ -57,8 +56,19 @@ Git bundle preserves the initial commit/history and can be restored with:
|
|
|
57
56
|
git clone Rstats.bundle Rstats
|
|
58
57
|
```
|
|
59
58
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
The
|
|
59
|
+
## PyPI publication — 1 December 2026
|
|
60
|
+
|
|
61
|
+
Version **0.1.0** was published as
|
|
62
|
+
[`rstatspython`](https://pypi.org/project/rstatspython/0.1.0/) using Trusted
|
|
63
|
+
Publishing. The [release workflow](https://github.com/drdanrb/Rstats/actions/runs/46704841874)
|
|
64
|
+
passed tests, build, metadata validation, and upload.
|
|
65
|
+
|
|
66
|
+
A separate Python 3.12 environment installed the package explicitly from
|
|
67
|
+
`https://pypi.org/simple`. Package metadata, import location, and version were
|
|
68
|
+
checked. Descriptives, frequencies, chi-square, ANOVA with Tukey, OLS, logistic
|
|
69
|
+
regression, and a saved boxplot all executed successfully against the public
|
|
70
|
+
teaching dataset. The README and teaching notebook now install from PyPI.
|
|
71
|
+
Actual execution inside Google Colab remains unverified.
|
|
72
|
+
|
|
73
|
+
See [publishing.md](publishing.md) for maintaining releases. The unrelated
|
|
74
|
+
`rstats` distribution must not be used as an installation shortcut.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "rstatspython"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.1"
|
|
8
8
|
description = "Familiar commands. Complete statistical reports."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.12"
|
|
@@ -13,7 +13,7 @@ authors = [{name = "Rstats contributors"}]
|
|
|
13
13
|
dependencies = [
|
|
14
14
|
"numpy>=2.0", "pandas>=2.2,<4", "scipy>=1.16",
|
|
15
15
|
"statsmodels>=0.14.4,<0.16", "patsy>=1.0",
|
|
16
|
-
"pingouin>=0.6,<0.
|
|
16
|
+
"pingouin>=0.6.1,<0.7", "seaborn>=0.13.2", "matplotlib>=3.9",
|
|
17
17
|
]
|
|
18
18
|
classifiers = [
|
|
19
19
|
"Development Status :: 3 - Alpha",
|
|
@@ -8,6 +8,7 @@ import pandas as pd
|
|
|
8
8
|
import pingouin as pg
|
|
9
9
|
from patsy import ModelDesc
|
|
10
10
|
from scipy import stats
|
|
11
|
+
from scipy.linalg import helmert
|
|
11
12
|
from statsmodels.stats.anova import anova_lm
|
|
12
13
|
|
|
13
14
|
from ._data import (
|
|
@@ -27,6 +28,59 @@ from .regression import coding_table, fit_ols, ols_diagnostics
|
|
|
27
28
|
from .result import AnalysisResult
|
|
28
29
|
|
|
29
30
|
|
|
31
|
+
def _repeated_corrections(tests, frame, outcome, subject, within, between, effects):
|
|
32
|
+
"""Compute corrections on orthonormal within-subject contrasts."""
|
|
33
|
+
index = [subject, *between]
|
|
34
|
+
wide = frame.pivot(index=index, columns=within, values=outcome).sort_index(axis=1)
|
|
35
|
+
if between:
|
|
36
|
+
wide = wide - wide.groupby(level=between[0], observed=True).transform("mean")
|
|
37
|
+
residual_df = len(wide) - (frame[between[0]].nunique() if between else 1)
|
|
38
|
+
for row in tests.itertuples():
|
|
39
|
+
factors = [factor for factor in within if factor in effects.get(row.effect, [])]
|
|
40
|
+
if not factors:
|
|
41
|
+
continue
|
|
42
|
+
profiles = wide
|
|
43
|
+
if len(within) == 2 and len(factors) == 1:
|
|
44
|
+
profiles = wide.T.groupby(level=factors[0], observed=True).mean().T
|
|
45
|
+
contrast = helmert(frame[factors[0]].nunique(), full=False)
|
|
46
|
+
if len(factors) == 2:
|
|
47
|
+
contrast = np.kron(contrast, helmert(frame[factors[1]].nunique(), full=False))
|
|
48
|
+
dimension = contrast.shape[0]
|
|
49
|
+
tests.loc[row.Index, "eps"] = 1.0
|
|
50
|
+
if dimension == 1:
|
|
51
|
+
continue
|
|
52
|
+
covariance = np.cov(profiles.to_numpy(dtype=float) @ contrast.T, rowvar=False)
|
|
53
|
+
trace = np.trace(covariance)
|
|
54
|
+
if trace <= 0:
|
|
55
|
+
continue
|
|
56
|
+
epsilon = min(1.0, trace**2 / (dimension * np.sum(covariance**2)))
|
|
57
|
+
tests.loc[row.Index, "eps"] = epsilon
|
|
58
|
+
tests.loc[row.Index, "p_gg"] = stats.f.sf(
|
|
59
|
+
row.F, row.df_numerator * epsilon, row.df_denominator * epsilon
|
|
60
|
+
)
|
|
61
|
+
# Mauchly's chi-square approximation uses the residual covariance df.
|
|
62
|
+
sign, log_det = np.linalg.slogdet(covariance)
|
|
63
|
+
if sign <= 0 or residual_df < dimension:
|
|
64
|
+
continue
|
|
65
|
+
log_w = min(0.0, log_det - dimension * np.log(trace / dimension))
|
|
66
|
+
d = dimension
|
|
67
|
+
scale = residual_df - (2 * d**2 + d + 2) / (6 * d)
|
|
68
|
+
chi_square = -scale * log_w
|
|
69
|
+
df = d * (d + 1) / 2 - 1
|
|
70
|
+
second_order = (
|
|
71
|
+
(d + 2)
|
|
72
|
+
* (d - 1)
|
|
73
|
+
* (d - 2)
|
|
74
|
+
* (2 * d**3 + 6 * d**2 + 3 * wide.shape[1] + 2)
|
|
75
|
+
/ (288 * (d * scale) ** 2)
|
|
76
|
+
)
|
|
77
|
+
p = stats.chi2.sf(chi_square, df)
|
|
78
|
+
p += second_order * (stats.chi2.sf(chi_square, df + 4) - p)
|
|
79
|
+
tests.loc[row.Index, "W_spher"] = np.exp(log_w)
|
|
80
|
+
tests.loc[row.Index, "p_spher"] = p
|
|
81
|
+
tests.loc[row.Index, "sphericity"] = bool(p > 0.05)
|
|
82
|
+
|
|
83
|
+
|
|
30
84
|
def _group_descriptives(frame, outcome, factors, alpha):
|
|
31
85
|
rows = []
|
|
32
86
|
for keys, chunk in frame.groupby(factors, observed=True, sort=False):
|
|
@@ -216,7 +270,7 @@ def aov(
|
|
|
216
270
|
within=within[0],
|
|
217
271
|
between=between[0],
|
|
218
272
|
subject=subject,
|
|
219
|
-
correction=
|
|
273
|
+
correction=False,
|
|
220
274
|
effsize="np2",
|
|
221
275
|
)
|
|
222
276
|
effect_map = {
|
|
@@ -260,6 +314,13 @@ def aov(
|
|
|
260
314
|
# own row; multi-factor designs carry a denominator on each effect.
|
|
261
315
|
error_df = tests.loc[tests.effect == "Error", "df_numerator"].iloc[0]
|
|
262
316
|
tests["df_denominator"] = np.where(tests.effect == "Error", np.nan, error_df)
|
|
317
|
+
if between or len(within) == 2:
|
|
318
|
+
# Pingouin 0.6 supports Colab's dependencies but uses a different
|
|
319
|
+
# covariance for mixed designs and two-factor interactions.
|
|
320
|
+
tests = tests.drop(
|
|
321
|
+
columns=["p_gg", "sphericity", "W_spher", "p_spher"], errors="ignore"
|
|
322
|
+
)
|
|
323
|
+
_repeated_corrections(tests, frame, spec.outcome, subject, within, between, effect_map)
|
|
263
324
|
tests["p"] = (
|
|
264
325
|
tests["p_gg"].fillna(tests["p_uncorrected"])
|
|
265
326
|
if correction == "gg" and "p_gg" in tests
|
|
@@ -9,17 +9,28 @@ from .result import AnalysisResult
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
def _variables(formula):
|
|
12
|
-
if isinstance(formula, str)
|
|
13
|
-
|
|
12
|
+
if isinstance(formula, str):
|
|
13
|
+
formula = formula.strip()
|
|
14
|
+
if formula.startswith("~"):
|
|
15
|
+
formula = formula[1:].strip()
|
|
16
|
+
if "~" not in formula and formula:
|
|
17
|
+
return [formula.strip("`")]
|
|
14
18
|
spec = parse(formula)
|
|
15
|
-
if len(spec.
|
|
16
|
-
raise ValueError("Use '
|
|
19
|
+
if len(spec.tokens) != 1 or spec.expression != next(iter(spec.tokens)):
|
|
20
|
+
raise ValueError("Use 'group' or '~ group' for one variable, or 'group ~ passed' for two.")
|
|
21
|
+
if spec.outcome == spec.predictors[0]:
|
|
22
|
+
raise ValueError("Use two distinct columns for a two-way categorical table.")
|
|
17
23
|
return [spec.outcome, spec.predictors[0]]
|
|
18
24
|
|
|
19
25
|
|
|
26
|
+
def _contingency(frame, cols):
|
|
27
|
+
return frame.groupby(cols, observed=True).size().unstack(fill_value=0)
|
|
28
|
+
|
|
29
|
+
|
|
20
30
|
def table(formula, *, data, percent="valid", missing="drop"):
|
|
21
|
-
"""Counts and percentages
|
|
31
|
+
"""Counts and percentages for one column or a two-column formula.
|
|
22
32
|
|
|
33
|
+
Use ``table('group', data=df)`` or ``table('group ~ passed', data=df)``.
|
|
23
34
|
Missing values are excluded and counted separately. ``percent='valid'``
|
|
24
35
|
uses the valid grand total; row/column/total apply to two-way tables.
|
|
25
36
|
"""
|
|
@@ -36,7 +47,7 @@ def table(formula, *, data, percent="valid", missing="drop"):
|
|
|
36
47
|
percentages = (100 * counts / len(frame)).rename(columns={"count": "percent"})
|
|
37
48
|
denominator = len(frame)
|
|
38
49
|
else:
|
|
39
|
-
counts =
|
|
50
|
+
counts = _contingency(frame, cols)
|
|
40
51
|
denominator = (
|
|
41
52
|
counts.sum(axis=1)
|
|
42
53
|
if percent == "row"
|
|
@@ -64,6 +75,7 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
|
|
|
64
75
|
"""Pearson independence/GOF test, or explicit Fisher exact for a 2×2 table.
|
|
65
76
|
|
|
66
77
|
``chisq('group ~ passed', data=df)`` tests independence.
|
|
78
|
+
``chisq('group', data=df)`` tests goodness of fit against equal proportions.
|
|
67
79
|
``chisq([20, 30, 50], expected=[.25, .25, .5])`` tests count proportions.
|
|
68
80
|
"""
|
|
69
81
|
if method not in {"pearson", "fisher"}:
|
|
@@ -72,28 +84,25 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
|
|
|
72
84
|
raise TypeError(
|
|
73
85
|
"correction must be True or False (Yates correction for 2×2 Pearson tests)."
|
|
74
86
|
)
|
|
75
|
-
if isinstance(formula, str)
|
|
76
|
-
|
|
77
|
-
if len(cols) != 2:
|
|
78
|
-
raise ValueError(
|
|
79
|
-
"For independence use 'group ~ outcome'; for goodness of fit pass a count vector."
|
|
80
|
-
)
|
|
87
|
+
cols = _variables(formula) if isinstance(formula, str) else []
|
|
88
|
+
if len(cols) == 2:
|
|
81
89
|
if expected is not None:
|
|
82
90
|
raise ValueError("expected proportions apply only to goodness-of-fit count vectors.")
|
|
83
91
|
frame, notes = complete(data, cols, missing)
|
|
84
|
-
observed =
|
|
92
|
+
observed = _contingency(frame, cols)
|
|
93
|
+
counts = observed.to_numpy(dtype=np.int64)
|
|
85
94
|
if min(observed.shape) < 2:
|
|
86
95
|
raise ValueError(
|
|
87
96
|
"An independence test needs at least two observed levels per variable."
|
|
88
97
|
)
|
|
89
98
|
if correction and observed.shape != (2, 2):
|
|
90
99
|
raise ValueError("Yates correction is supported only for 2×2 tables.")
|
|
91
|
-
chi2, p, dof, exp = stats.chi2_contingency(
|
|
92
|
-
residuals = (
|
|
100
|
+
chi2, p, dof, exp = stats.chi2_contingency(counts, correction=correction)
|
|
101
|
+
residuals = (counts - exp) / np.sqrt(exp)
|
|
93
102
|
if method == "fisher":
|
|
94
103
|
if observed.shape != (2, 2) or correction:
|
|
95
104
|
raise ValueError("Fisher's test needs a 2×2 table and correction=False.")
|
|
96
|
-
fisher = stats.fisher_exact(
|
|
105
|
+
fisher = stats.fisher_exact(counts)
|
|
97
106
|
summary = {"odds_ratio": fisher.statistic, "p": fisher.pvalue, "n": len(frame)}
|
|
98
107
|
title = "Fisher exact test (two-sided)"
|
|
99
108
|
else:
|
|
@@ -103,8 +112,7 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
|
|
|
103
112
|
"p": p,
|
|
104
113
|
"n": len(frame),
|
|
105
114
|
"cramers_v": np.sqrt(
|
|
106
|
-
|
|
107
|
-
/ (len(frame) * min(np.array(observed.shape) - 1))
|
|
115
|
+
np.sum(residuals**2) / (len(frame) * min(np.array(observed.shape) - 1))
|
|
108
116
|
),
|
|
109
117
|
}
|
|
110
118
|
title = "Pearson chi-square test of independence"
|
|
@@ -122,7 +130,16 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
|
|
|
122
130
|
else:
|
|
123
131
|
if method != "pearson" or correction:
|
|
124
132
|
raise ValueError("Goodness of fit uses method='pearson', correction=False.")
|
|
125
|
-
|
|
133
|
+
labels = None
|
|
134
|
+
notes = []
|
|
135
|
+
if cols:
|
|
136
|
+
frame, notes = complete(data, cols, missing)
|
|
137
|
+
frequencies = frame[cols[0]].value_counts(sort=False)
|
|
138
|
+
frequencies = frequencies[frequencies > 0]
|
|
139
|
+
labels = frequencies.index
|
|
140
|
+
obs = frequencies.to_numpy(dtype=float)
|
|
141
|
+
else:
|
|
142
|
+
obs = np.asarray(formula, dtype=float)
|
|
126
143
|
if (
|
|
127
144
|
obs.ndim != 1
|
|
128
145
|
or len(obs) < 2
|
|
@@ -161,14 +178,13 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
|
|
|
161
178
|
]
|
|
162
179
|
),
|
|
163
180
|
"counts": pd.DataFrame(
|
|
164
|
-
{"observed": obs, "expected": exp, "pearson_residual": (obs - exp) / np.sqrt(exp)}
|
|
181
|
+
{"observed": obs, "expected": exp, "pearson_residual": (obs - exp) / np.sqrt(exp)},
|
|
182
|
+
index=labels,
|
|
165
183
|
),
|
|
166
184
|
}
|
|
167
|
-
title
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
"Expected proportions must be specified independently of these observations; fitted-probability degrees of freedom are not supported."
|
|
171
|
-
],
|
|
185
|
+
title = "Chi-square goodness-of-fit test"
|
|
186
|
+
notes.append(
|
|
187
|
+
"Expected proportions must be specified independently of these observations; fitted-probability degrees of freedom are not supported."
|
|
172
188
|
)
|
|
173
189
|
if (exp < 1).any() or (exp < 5).mean() > 0.2:
|
|
174
190
|
notes.append(
|
|
@@ -212,6 +212,37 @@ def test_descriptives_missing_constant_and_categories():
|
|
|
212
212
|
assert_allclose(frequencies.percent.sum(), 100)
|
|
213
213
|
|
|
214
214
|
|
|
215
|
+
@pytest.mark.parametrize("formula", ["study group", "~ `study group`"])
|
|
216
|
+
def test_one_way_frequency_and_goodness_of_fit(formula):
|
|
217
|
+
df = pd.DataFrame(
|
|
218
|
+
{"study group": pd.Categorical(["a", "a", "a", "b", None], categories=["b", "a", "unused"])}
|
|
219
|
+
)
|
|
220
|
+
report = rs.table(formula, data=df)
|
|
221
|
+
assert report.tables["counts"]["count"].to_dict() == {"a": 3, "b": 1}
|
|
222
|
+
assert report.tables["percentages"]["percent"].to_dict() == {"a": 75, "b": 25}
|
|
223
|
+
assert report.tables["missing"].iloc[0, 0] == 1
|
|
224
|
+
test = rs.chisq(formula, data=df)
|
|
225
|
+
assert test.tables["test"].iloc[0]["chi2"] == pytest.approx(1)
|
|
226
|
+
assert test.tables["counts"]["observed"].to_dict() == {"a": 3, "b": 1}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def test_chisq_with_nullable_columns_and_unused_levels():
|
|
230
|
+
df = pd.DataFrame(
|
|
231
|
+
{
|
|
232
|
+
"group": pd.Categorical(
|
|
233
|
+
["a"] * 10 + ["b"] * 10 + ["unused"], categories=["b", "a", "unused"]
|
|
234
|
+
),
|
|
235
|
+
"passed": pd.array(
|
|
236
|
+
[True] * 8 + [False] * 2 + [True] * 2 + [False] * 8 + [None], dtype="boolean"
|
|
237
|
+
),
|
|
238
|
+
}
|
|
239
|
+
)
|
|
240
|
+
result = rs.chisq("group ~ passed", data=df)
|
|
241
|
+
assert list(result.tables["observed"].index) == ["b", "a"]
|
|
242
|
+
assert result.tables["observed"].loc["a", True] == 8
|
|
243
|
+
assert result.tables["test"].iloc[0]["chi2"] == pytest.approx(7.2)
|
|
244
|
+
|
|
245
|
+
|
|
215
246
|
def test_frequency_denominators_and_fisher():
|
|
216
247
|
df = pd.DataFrame({"a": ["a", "a", "b", "b", "b", None], "b": [0, 1, 0, 0, 1, 0]})
|
|
217
248
|
row = rs.table("a ~ b", data=df, percent="row")
|
|
@@ -61,7 +61,7 @@ def notebook():
|
|
|
61
61
|
"# Rstats: one line, a full report\n\nChoose **Runtime → Run all** in Google Colab. The first cell installs Rstats if needed; the next cell loads synthetic teaching datasets automatically. No file uploads or R installation are needed."
|
|
62
62
|
),
|
|
63
63
|
nbf.v4.new_code_cell(
|
|
64
|
-
"import importlib.util\n\nif importlib.util.find_spec('rstats') is None:\n %pip install -q
|
|
64
|
+
"import importlib.util\n\nif importlib.util.find_spec('rstats') is None:\n %pip install -q rstatspython"
|
|
65
65
|
),
|
|
66
66
|
nbf.v4.new_code_cell(
|
|
67
67
|
"%matplotlib inline\nfrom pathlib import Path\nimport pandas as pd\nimport rstats as rs\n\nexamples = Path('examples') if Path('examples/students.csv').exists() else Path('.')\nsource = str(examples) if (examples / 'students.csv').exists() else 'https://raw.githubusercontent.com/drdanrb/Rstats/main/examples'\ndf = pd.read_csv(f'{source}/students.csv')\nlong_df = pd.read_csv(f'{source}/longitudinal.csv')\nlong_df['time'] = pd.Categorical(long_df['time'], categories=['baseline', 'midterm', 'final'], ordered=True)\ndf.head()"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|