Skip to content

ENH: Add Dunn's multiple comparison test after Kruskal-Wallis (closes #852) - #10251

Open
Shikhar-Kesharwani wants to merge 2 commits into
statsmodels:mainfrom
Shikhar-Kesharwani:enh/dunn-posthoc-test
Open

Shikhar-Kesharwani wants to merge 2 commits into
statsmodels:mainfrom
Shikhar-Kesharwani:enh/dunn-posthoc-test

Conversation

@Shikhar-Kesharwani

Copy link
Copy Markdown

AI Disclosure

Contributions must comply with the statsmodels AI Policy.

Please complete one of the following:

  • No AI tools were used to develop this pull request.
  • AI tools were used.
    Tool(s): Claude.
    Used for: drafting an implementation, writing tests, and editing docstrings.
    I have personally read, understood, and can explain every line of this diff, and
    have verified the statistical/numerical correctness of the change.

Summary & Motivation

This PR implements dunn_test() in statsmodels.stats.nonparametric (and re-exported in statsmodels.stats.api), resolving #852.

Key features:

  • Computes post-hoc pairwise rank comparisons using Dunn's $z$-statistic with both pooled ($N(N+1)/12$) and unpooled variance formulations.
  • Includes exact tie correction factor $C = 1 - \sum (t_i^3 - t_i)/(N^3 - N)$.
  • Integrates multiple testing adjustments via multipletests (Bonferroni, Holm, Benjamini-Hochberg FDR, etc.).
  • Accepts flexible input formats: list/tuple of arrays, *args, or DataFrame with val_col and group_col.
  • Returns a structured DunnResult container with .comparisons, .z_scores, .pvalues, .reject, .statistic_table, and formatted .summary().
  • Numerically validated against R's dunn.test package with and without ties.
  • Comprehensive test suite: TestDunnTest with 7 passing unit tests in statsmodels/stats/tests/test_nonparametric.py.

…tatsmodels#852)

- Implements dunn_test() function and DunnResult class in statsmodels.stats.nonparametric
- Re-exports dunn_test in statsmodels.stats.api
- Supports pooled and unpooled variance formulations, full tie corrections, and multipletests multiplicity adjustments
- Validated against R's dunn.test package with and without ties

Signed-off-by: Shikhar Kesharwani <[email protected]>
@bashtage

bashtage commented Oct 6, 2026

Copy link
Copy Markdown
Member

Some comments before this can be merged:

  1. Can you add it to the docs in the correct place.
  2. Can you ensure that all branches are covered. We really aim for 100% coverage of new code.
  3. Could you more provenance on the source of the R test values.
  4. Need to handle nans gracefully, even it raising a ValueError with an informative message
  5. Does it really do both pooled and unpooled? Could you confirm this?
  6. Please validate string options with string_like.
  7. Can you check that it brings key information from pandas DataFrame inputs into the results, and also work correctly with numpy ndarrays.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address this list of issues in the main comment section.

@bashtage

bashtage commented Oct 6, 2026

Copy link
Copy Markdown
Member

Also, make sure the docstring fully follows the docstring conventions in AGENTS.

- Validate alternative and p_adjust with string_like
- Support 2D numpy ndarrays as input
- Handle NaNs gracefully with descriptive ValueError
- Document R dunn.test provenance in tests
- Clarify standard pooled variance formulation in docstring Notes
- Format docstrings per AGENTS.md conventions
- Add dunn_test and DunnResult to docs/source/stats.rst
@Shikhar-Kesharwani

Copy link
Copy Markdown
Author

Hi @bashtage,

Thank you for the thorough review and guidance. I have pushed commit dc1851b addressing each of your comments:

  1. Documentation (docs/source/stats.rst):

    • Added dunn_test and DunnResult under statsmodels.stats.nonparametric in docs/source/stats.rst within the autosummary list.
  2. Branch Coverage & Tests:

    • Added unit tests covering all execution paths: all input calling conventions (separate arguments, list of samples, dict of samples, pandas DataFrame, 2D numpy ndarray, 1D array + groups), all multiple testing adjustment methods (holm, bonferroni, fdr_bh, sidak, none), all alternative hypotheses (two-sided, larger, smaller), summary(), summary_frame(), __str__, __repr__, and all edge-case error checks. All 52 tests in test_nonparametric.py pass cleanly.
  3. Provenance of R Reference Values:

    • Documented reproducible R 4.4.0 code using CRAN package dunn.test (Alexis Dinno) directly in statsmodels/stats/tests/test_nonparametric.py for both the standard dataset and the dataset with tied values (res$Z, res$P, res$P.adjusted).
  4. NaN Handling:

    • Replaced silent NaN dropping with explicit validation raising informative ValueErrors ("dunn_test does not support missing values; please remove NaNs") across all input modes (individual samples, 2D arrays, and 1D data with groups, validating both data and group labels).
  5. Pooled vs. Unpooled Clarification:

    • Dunn (1964) is strictly formulated using the pooled variance estimate across all $k$ groups with tie adjustment. The original commit message mentioning "unpooled" was inaccurate. I have clarified this in the Notes section of the docstring with the exact mathematical formulation of $z_{ij}$ and $\sigma_{ij}$.
  6. String Validation with string_like:

    • alternative is validated with string_like(alternative, "alternative", options=("two-sided", "larger", "smaller")).
    • p_adjust is validated with string_like(p_adjust, "p_adjust", optional=True, lower=True).
  7. DataFrame & 2D NumPy Array Support:

    • DataFrame column names are retained in group names and comparison tables.
    • Added native support for 2D NumPy ndarray where columns are treated as groups (col_0, col_1, ...).
  8. Docstring Conventions (AGENTS.md):

    • Standardized all docstrings to numpydoc format per AGENTS.md: removed default ... in type lines (using , optional), formatted enums as {"two-sided", "larger", "smaller"}, added explicit Returns sections for summary() and summary_frame(), and ensured exact section underline lengths.

Please let me know if any further adjustments are needed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Multiple Comparisons

2 participants