Stats chisquared contingency - CyrilB1531/lodestar GitHub Wiki
Home › Stats › Hypothesis tests
ChiSquared.Contingency
Tests a contingency table for independence of its two factors.
public static ChiSquaredContingencyResult Contingency(double[][] table, Continuity continuity = Continuity.Applied)
Parameters — table is the observed counts, row-major and rectangular, at least one row and
one column; one row or one column leaves no degree of freedom, a statistic of 0 and a p-value of
1 — unless a total is zero, which answers NaN first, as below. continuity says whether to apply Yates's correction; it is defined for 2×2 tables
only, so asking for it on any other shape changes nothing — the same rule
scipy.stats.chi2_contingency follows with correction=True.
Returns — ChiSquaredContingencyResult: the statistic, the p-value, the degrees of freedom
(rows - 1) * (columns - 1), and the table independence would have produced.
Exceptions — ArgumentException when table is empty, ragged, or holds a negative, infinite
or NaN count. A zero row or column total makes an expectation zero, which the statistic divides
by: both numbers are NaN (decision 0010). Unlike every other family in this package, a NaN or
an infinite cell here is refused rather than propagated: a contingency table's cells are counts,
not measurements, and the expected-frequency table divides by their marginals. Finite cells whose marginals
overflow answer NaN for both in a table of two rows and two columns or more, where scipy answers
(nan, nan) or, when another expectation underflows to zero, raises. See the
Python equivalence table's nan_policy row. ArgumentOutOfRangeException when an option is outside its enumeration.
Example — a 2×2 preference table, with Yates's correction applied by default.
using Lodestar.Stats;
double[][] table =
[
[30.0, 20.0],
[15.0, 35.0],
];
ChiSquaredContingencyResult result = ChiSquared.Contingency(table);
double statistic = Math.Round(result.Statistic, 4); // => 7.9192
int dof = result.DegreesOfFreedom; // => 1
double expected00 = result.ExpectedFrequencies[0][0]; // => 22.5
Remarks — Yates only ever touches a 2×2 table. Continuity.Applied moves each cell half a
unit toward its expectation before squaring it, and only when the table is exactly two rows by
two columns; on any other shape continuity is accepted and does nothing, matching scipy rather
than throwing on a parameter that would otherwise be silently ignored. Passing
Continuity.None on this same table gives a larger statistic, 9.0909, and a smaller p-value —
the correction always pulls the statistic down, which is why it is the more conservative default.
Applies to — net10.0, netstandard2.0.
See also — ChiSquared.GoodnessOfFit,
FisherExact.Test for the exact alternative at any sample size,
ChiSquaredContingencyResult, Continuity, the
Python equivalence table.