@numero-uno-jpn/rstats 0.15.3 → 0.17.0
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.
- package/CHANGELOG.md +294 -0
- package/README.ja.md +68 -35
- package/README.md +65 -30
- package/dist/chunks/chunk-2C33MXSW.js +3 -0
- package/dist/chunks/chunk-34S5SQY6.js +2 -0
- package/dist/chunks/chunk-4WE3OO62.js +2 -0
- package/dist/chunks/chunk-5AYHCITP.js +2 -0
- package/dist/chunks/chunk-6JJQL6HL.js +2 -0
- package/dist/chunks/chunk-C7V2FH6L.js +3 -0
- package/dist/chunks/chunk-CZI7KUO3.js +2 -0
- package/dist/chunks/chunk-DXI5N2ET.js +2 -0
- package/dist/chunks/chunk-FY3FVOBM.js +2 -0
- package/dist/chunks/chunk-H3WVPZDL.js +2 -0
- package/dist/chunks/chunk-LHUIJQHY.js +2 -0
- package/dist/chunks/chunk-LV3W2F7N.js +2 -0
- package/dist/chunks/chunk-M4ITG7YR.js +2 -0
- package/dist/chunks/chunk-NSYZTS26.js +2 -0
- package/dist/chunks/chunk-ONY5CISH.js +2 -0
- package/dist/chunks/chunk-RFE7MVP7.js +2 -0
- package/dist/chunks/chunk-SE7V2KLO.js +2 -0
- package/dist/chunks/chunk-THIGHOKK.js +2 -0
- package/dist/chunks/chunk-TNMJPQPV.js +2 -0
- package/dist/chunks/chunk-WM7VFXTV.js +2 -0
- package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
- package/dist/chunks/chunk-XLSFJTTK.js +2 -0
- package/dist/chunks/chunk-Z37NELOS.js +2 -0
- package/dist/chunks/chunk-ZFQWB222.js +2 -0
- package/dist/data/grouping.js +26 -7
- package/dist/descriptive/basic.js +110 -8
- package/dist/descriptive/cov.js +23 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +69 -23
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +26 -9
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +77 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +86 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +74 -10
- package/dist/descriptive/pivot.d.ts +25 -10
- package/dist/descriptive/pivot.js +182 -42
- package/dist/descriptive/quantile.js +10 -1
- package/dist/descriptive/rank.js +8 -1
- package/dist/descriptive/table.d.ts +23 -3
- package/dist/descriptive/table.js +36 -21
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +27 -2
- package/dist/distributions/beta.js +33 -4
- package/dist/distributions/binomial.js +46 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +21 -4
- package/dist/distributions/chisq.js +16 -3
- package/dist/distributions/exponential.js +14 -0
- package/dist/distributions/f.js +41 -17
- package/dist/distributions/gamma.js +35 -3
- package/dist/distributions/geometric.js +58 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +101 -6
- package/dist/distributions/invgamma.js +10 -1
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +36 -6
- package/dist/distributions/logistic.js +13 -1
- package/dist/distributions/lognormal.js +16 -2
- package/dist/distributions/multinomial.js +58 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +102 -17
- package/dist/distributions/normal.js +17 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +12 -1
- package/dist/distributions/poisson.js +37 -3
- package/dist/distributions/signrank.js +16 -4
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +481 -61
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +19 -5
- package/dist/distributions/tukey.js +11 -2
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +18 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +164 -26
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +3 -1
- package/dist/entries/descriptive.js +1 -1
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +2 -0
- package/dist/entries/linalg.d.ts +3 -1
- package/dist/entries/mixed.d.ts +3 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/numerics.d.ts +2 -1
- package/dist/entries/tests.d.ts +8 -5
- package/dist/entries/tests.js +3 -1
- package/dist/htest/agreement.d.ts +16 -2
- package/dist/htest/agreement.js +122 -21
- package/dist/htest/ansariTest.d.ts +8 -2
- package/dist/htest/ansariTest.js +116 -18
- package/dist/htest/aov.d.ts +29 -23
- package/dist/htest/aov.js +90 -47
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +47 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +12 -5
- package/dist/htest/chisqTest.d.ts +5 -2
- package/dist/htest/chisqTest.js +151 -46
- package/dist/htest/cor.d.ts +9 -2
- package/dist/htest/cor.js +57 -26
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +5 -0
- package/dist/htest/effectSize.js +117 -35
- package/dist/htest/fisherTest.d.ts +4 -3
- package/dist/htest/fisherTest.js +88 -24
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +7 -1
- package/dist/htest/ksTest.js +36 -6
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +28 -6
- package/dist/htest/mantelhaenTest.js +132 -25
- package/dist/htest/mcnemarTest.js +40 -11
- package/dist/htest/multipleComparisons.d.ts +24 -26
- package/dist/htest/multipleComparisons.js +70 -64
- package/dist/htest/normalityTests.js +54 -14
- package/dist/htest/onewayTest.js +106 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +42 -6
- package/dist/htest/pairwise.d.ts +3 -1
- package/dist/htest/pairwise.js +46 -21
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +117 -59
- package/dist/htest/polycor.js +47 -17
- package/dist/htest/power.d.ts +15 -1
- package/dist/htest/power.js +128 -10
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +44 -6
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +159 -39
- package/dist/htest/rankTests.js +36 -6
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +53 -21
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +28 -4
- package/dist/htest/trendTests.js +124 -35
- package/dist/htest/types.d.ts +7 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +52 -14
- package/dist/htest/wilcoxTest.js +164 -29
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +15 -1
- package/dist/internal/ddexp.js +59 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.js +15 -2
- package/dist/internal/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +58 -7
- package/dist/linalg/chol.js +10 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +75 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +113 -15
- package/dist/linalg/kappa.js +64 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +40 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +74 -26
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +105 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +156 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +33 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +32 -2
- package/dist/models/anovaSequential.js +170 -28
- package/dist/models/aovEz.js +154 -39
- package/dist/models/aovStrata.js +68 -24
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +78 -33
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +166 -69
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +57 -7
- package/dist/models/glm.js +427 -74
- package/dist/models/glmAnova.js +90 -14
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +121 -29
- package/dist/models/glmFamily.d.ts +11 -6
- package/dist/models/glmFamily.js +247 -62
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +246 -37
- package/dist/models/lmer.d.ts +31 -7
- package/dist/models/lmer.js +129 -42
- package/dist/models/lmerAnova.d.ts +3 -3
- package/dist/models/lmerAnova.js +47 -9
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +13 -6
- package/dist/models/lmerTest.js +82 -29
- package/dist/models/mauchly.d.ts +6 -1
- package/dist/models/mauchly.js +41 -15
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +10 -4
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +47 -17
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +12 -1
- package/dist/models/survival.js +75 -28
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +72 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +111 -16
- package/dist/numerics/interp.d.ts +40 -9
- package/dist/numerics/interp.js +375 -55
- package/dist/numerics/ode.js +59 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +97 -10
- package/dist/random/beta.js +58 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +50 -5
- package/dist/random/extra.js +55 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +47 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +31 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/rng.js +4 -0
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +63 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +175 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +4 -1
- package/dist/special/choose.js +24 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +11 -2
- package/dist/special/incbet.js +30 -4
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +117 -20
- package/dist/special/log1pmx.js +4 -0
- package/dist/special/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -11
- package/llms.txt +15 -6
- package/package.json +19 -10
- package/dist/chunks/chunk-3THFTB36.js +0 -2
- package/dist/chunks/chunk-3TSWYE5L.js +0 -2
- package/dist/chunks/chunk-3WPU6LGK.js +0 -2
- package/dist/chunks/chunk-5ITR67MB.js +0 -2
- package/dist/chunks/chunk-5NRFU6F6.js +0 -2
- package/dist/chunks/chunk-E2LCSVQV.js +0 -2
- package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
- package/dist/chunks/chunk-FKAKALOZ.js +0 -2
- package/dist/chunks/chunk-HD73UKPT.js +0 -2
- package/dist/chunks/chunk-IUULP3LE.js +0 -2
- package/dist/chunks/chunk-JQG3YQOC.js +0 -2
- package/dist/chunks/chunk-KT66SB7R.js +0 -2
- package/dist/chunks/chunk-MAUAOQG3.js +0 -2
- package/dist/chunks/chunk-MDYE7QP2.js +0 -2
- package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
- package/dist/chunks/chunk-PMJI5QO6.js +0 -3
- package/dist/chunks/chunk-UF7KOTHF.js +0 -3
- package/dist/chunks/chunk-UOE57JGT.js +0 -2
- package/dist/chunks/chunk-USPEBXSR.js +0 -2
- package/dist/chunks/chunk-VLUL2HFW.js +0 -3
- package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
package/dist/htest/rankTests.js
CHANGED
|
@@ -19,10 +19,14 @@
|
|
|
19
19
|
import { pf1 } from "../distributions/f.js";
|
|
20
20
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
21
21
|
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
22
|
-
import { rank, tieCounts, variance } from "../internal/summary.js";
|
|
22
|
+
import { rank, scaleToUnit, tieCounts, variance } from "../internal/summary.js";
|
|
23
23
|
import { completeRows, median, toGroups } from "./groups.js";
|
|
24
24
|
import { blockData, kSampleData, twoGroupData } from "./testFormula.js";
|
|
25
25
|
import { matchAlternative } from "./types.js";
|
|
26
|
+
import { maxOf, minOf } from "../internal/extremes.js";
|
|
27
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
28
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
29
|
+
const MOOD_TEST_KEYS = ["alternative"];
|
|
26
30
|
function chisqResult(method, name, statistic, df) {
|
|
27
31
|
return {
|
|
28
32
|
method,
|
|
@@ -31,6 +35,7 @@ function chisqResult(method, name, statistic, df) {
|
|
|
31
35
|
parameter: df,
|
|
32
36
|
parameterName: "df",
|
|
33
37
|
pValue: pgamma1(statistic, df / 2, 2, false, false),
|
|
38
|
+
warnings: [],
|
|
34
39
|
};
|
|
35
40
|
}
|
|
36
41
|
function sumTies(x) {
|
|
@@ -102,18 +107,29 @@ export function friedmanTest(y, data) {
|
|
|
102
107
|
* @category Hypothesis tests
|
|
103
108
|
*/
|
|
104
109
|
export function cochranQTest(y) {
|
|
110
|
+
if (y.some((r) => r.some((v) => !Number.isNaN(v) && v !== 0 && v !== 1)))
|
|
111
|
+
throw new RangeError("the responses must be 0 or 1 (or NaN)");
|
|
105
112
|
return { ...friedmanTest(y), method: "Cochran's Q test", statisticName: "Q" };
|
|
106
113
|
}
|
|
107
114
|
export function quadeTest(y, data) {
|
|
108
115
|
if (typeof y === "string")
|
|
109
116
|
return quadeTest(blockData(y, data));
|
|
110
117
|
const rows = completeRows(y);
|
|
111
|
-
//
|
|
112
|
-
|
|
118
|
+
// b is the number of complete blocks, those the statistic is computed from. R's quade.test (4.5.2) counts the
|
|
119
|
+
// blocks dropped for a missing value as well (in B = sum S_j^2 / b, in (b - 1) B / (A - B) and in the degrees of
|
|
120
|
+
// freedom), so that its result for data with an incomplete block differs from that for the same data without the
|
|
121
|
+
// block (F 10 against 25 in docs/differences-from-r.md); here the two agree
|
|
122
|
+
const b = rows.length;
|
|
113
123
|
const k = y[0]?.length ?? 0;
|
|
114
124
|
if (rows.length < 2 || k < 2)
|
|
115
125
|
throw new RangeError("'y' must have at least two complete rows and two columns");
|
|
116
|
-
|
|
126
|
+
let ranges = rows.map((r) => maxOf(r) - minOf(r));
|
|
127
|
+
// ranges of finite data that overflow (-1e308 to 1e308 and -9e307 to 9e307 both gave Infinity, tied; R too): the data
|
|
128
|
+
// divided by a common power of 2 first, which keeps their order
|
|
129
|
+
if (ranges.some((v) => v === Infinity) && rows.every((r) => r.every(Number.isFinite))) {
|
|
130
|
+
ranges = scaleToUnit(rows).groups.map((r) => maxOf(r) - minOf(r));
|
|
131
|
+
}
|
|
132
|
+
const q = rank(ranges);
|
|
117
133
|
const colS = new Array(k).fill(0);
|
|
118
134
|
let A = 0;
|
|
119
135
|
rows.forEach((row, i) => {
|
|
@@ -153,6 +169,7 @@ export function quadeTest(y, data) {
|
|
|
153
169
|
parameter,
|
|
154
170
|
parameterName: ["num df", "denom df"],
|
|
155
171
|
pValue,
|
|
172
|
+
warnings: [],
|
|
156
173
|
};
|
|
157
174
|
}
|
|
158
175
|
export function flignerTest(x, g) {
|
|
@@ -164,10 +181,20 @@ export function flignerTest(x, g) {
|
|
|
164
181
|
const k = groups.length;
|
|
165
182
|
if (k < 2)
|
|
166
183
|
throw new RangeError("all observations are in the same group");
|
|
167
|
-
const
|
|
184
|
+
const deviations = (gs) => gs.flatMap((grp) => {
|
|
168
185
|
const m = median(grp);
|
|
169
186
|
return grp.map((v) => Math.abs(v - m));
|
|
170
187
|
});
|
|
188
|
+
let centred = deviations(groups);
|
|
189
|
+
// a group whose median is infinite (half its values infinite, or both infinities) has deviations Inf - Inf: no
|
|
190
|
+
// order, so no ranks (#329). An infinite value about a finite median ranks last, as in R
|
|
191
|
+
if (centred.some(Number.isNaN))
|
|
192
|
+
throw new RangeError("a group has an infinite median: its deviations are undefined");
|
|
193
|
+
// deviations of finite data that overflow (1e308 from medians of -1e308 and -9e307 both gave Infinity, tied; R too):
|
|
194
|
+
// all groups divided by one common power of 2 first, which keeps the order of the deviations across groups
|
|
195
|
+
if (centred.some((v) => v === Infinity) && groups.every((grp) => grp.every(Number.isFinite))) {
|
|
196
|
+
centred = deviations(scaleToUnit(groups).groups);
|
|
197
|
+
}
|
|
171
198
|
const n = centred.length;
|
|
172
199
|
const r = rank(centred);
|
|
173
200
|
const a = r.map((v) => qnorm((1 + v / (n + 1)) / 2));
|
|
@@ -189,6 +216,7 @@ export function flignerTest(x, g) {
|
|
|
189
216
|
return chisqResult("Fligner-Killeen test of homogeneity of variances", "Fligner-Killeen:med chi-squared", stat, k - 1);
|
|
190
217
|
}
|
|
191
218
|
export function moodTest(x, y, options = {}) {
|
|
219
|
+
checkOptions(options, MOOD_TEST_KEYS, "moodTest"); // generated: option-keys.mjs
|
|
192
220
|
if (typeof x === "string") {
|
|
193
221
|
const d = twoGroupData(x, y);
|
|
194
222
|
return moodTest(d.x, d.y, options);
|
|
@@ -202,6 +230,8 @@ export function moodTest(x, y, options = {}) {
|
|
|
202
230
|
const N = m + n;
|
|
203
231
|
if (N < 3)
|
|
204
232
|
throw new RangeError("not enough observations");
|
|
233
|
+
if (m === 0 || n === 0)
|
|
234
|
+
throw new RangeError("not enough observations in each sample");
|
|
205
235
|
const z = xs.concat(ys);
|
|
206
236
|
// positions in sorted order; tied values share the mean of the scores of their positions
|
|
207
237
|
const order = Array.from({ length: N }, (_, i) => i).sort((p, q) => z[p] - z[q]);
|
|
@@ -237,5 +267,5 @@ export function moodTest(x, y, options = {}) {
|
|
|
237
267
|
: alternative === "greater"
|
|
238
268
|
? pnorm(zstat, { lowerTail: false })
|
|
239
269
|
: 2 * pnorm(-Math.abs(zstat));
|
|
240
|
-
return { method: "Mood two-sample test of scale", alternative, statistic: zstat, statisticName: "Z", pValue };
|
|
270
|
+
return { method: "Mood two-sample test of scale", alternative, statistic: zstat, statisticName: "Z", pValue, warnings: [] };
|
|
241
271
|
}
|
package/dist/htest/tTest.d.ts
CHANGED
|
@@ -38,6 +38,8 @@ export interface TTestResult extends HTest {
|
|
|
38
38
|
nullValue: number;
|
|
39
39
|
/** Standard error of the mean (or difference), R's `stderr`. */
|
|
40
40
|
stdErr: number;
|
|
41
|
+
/** Alias of `stdErr`: the same value. */
|
|
42
|
+
stdError: number;
|
|
41
43
|
}
|
|
42
44
|
/**
|
|
43
45
|
* Student's t-test. Equivalent to R's `t.test()`.
|
package/dist/htest/tTest.js
CHANGED
|
@@ -4,12 +4,20 @@
|
|
|
4
4
|
// (equal_var = False is Welch) and ttest_rel (scipy/stats/_stats_py.py; SciPy commit a087e61,
|
|
5
5
|
// BSD-3-Clause, see THIRD_PARTY_NOTICES.md). Defaults, confidence intervals and result names follow R's output.
|
|
6
6
|
// - Welch is the default (scipy's default is equal variance)
|
|
7
|
-
// - If the standard error is below 10 eps times the absolute mean, the data are treated as constant and an error is raised (as in R)
|
|
7
|
+
// - If the standard error is below 10 eps times the absolute mean, the data are treated as constant and an error is raised (as in R),
|
|
8
|
+
// and also if it is 0 (R lets through samples of zeros with NaN results; #314)
|
|
8
9
|
import { pt1, qt1 } from "../distributions/t.js";
|
|
9
|
-
import { completePairs, dropNaN, mean, variance } from "../internal/summary.js";
|
|
10
|
+
import { completePairs, dropNaN, ldexp, mean, pairedDifferences, satterthwaiteDfSe, scaleToUnit, variance } from "../internal/summary.js";
|
|
10
11
|
import { twoSampleData } from "./testFormula.js";
|
|
11
12
|
import { checkConfLevel, matchAlternative } from "./types.js";
|
|
13
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
14
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
15
|
+
import { isOptionsObject } from "../internal/optionalArgs.js";
|
|
16
|
+
const T_TEST_KEYS = ["alternative", "mu", "paired", "varEqual", "confLevel"];
|
|
12
17
|
export function tTest(x, y, options = {}) {
|
|
18
|
+
if (typeof x !== "string" && isOptionsObject(y))
|
|
19
|
+
checkOptions(y, T_TEST_KEYS, "tTest"); // generated: option-keys.mjs
|
|
20
|
+
checkOptions(options, T_TEST_KEYS, "tTest"); // generated: option-keys.mjs
|
|
13
21
|
if (typeof x === "string")
|
|
14
22
|
return tTestFormula(x, y, options);
|
|
15
23
|
// Also accept the form tTest(x, { mu: 1 })
|
|
@@ -28,18 +36,23 @@ export function tTest(x, y, options = {}) {
|
|
|
28
36
|
checkConfLevel(confLevel);
|
|
29
37
|
if (paired && ys === undefined)
|
|
30
38
|
throw new TypeError("y is required when paired is true");
|
|
31
|
-
|
|
32
|
-
|
|
39
|
+
// Work on the data scaled by 2^-k (exact; paired values before their differences are taken), so that neither the
|
|
40
|
+
// differences nor the variances and their squares leave the range. mu goes with them; the estimates, standard
|
|
41
|
+
// error and interval are scaled back at the end
|
|
42
|
+
let xs;
|
|
43
|
+
let yv;
|
|
44
|
+
let k;
|
|
33
45
|
if (paired) {
|
|
34
|
-
const [a, b] = completePairs(
|
|
35
|
-
|
|
36
|
-
yv = undefined;
|
|
46
|
+
const [a, b] = completePairs(Array.from(x), Array.from(ys));
|
|
47
|
+
({ d: xs, k } = pairedDifferences(a, b));
|
|
37
48
|
}
|
|
38
49
|
else {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
50
|
+
const scaled = scaleToUnit(ys === undefined ? [dropNaN(Array.from(x))] : [dropNaN(Array.from(x)), dropNaN(Array.from(ys))]);
|
|
51
|
+
k = scaled.k;
|
|
52
|
+
xs = scaled.groups[0];
|
|
53
|
+
yv = scaled.groups[1];
|
|
42
54
|
}
|
|
55
|
+
const muS = ldexp(mu, -k);
|
|
43
56
|
let tstat;
|
|
44
57
|
let df;
|
|
45
58
|
let stdErr;
|
|
@@ -57,9 +70,10 @@ export function tTest(x, y, options = {}) {
|
|
|
57
70
|
if (yv === undefined) {
|
|
58
71
|
df = nx - 1;
|
|
59
72
|
stdErr = Math.sqrt(vx / nx);
|
|
60
|
-
|
|
73
|
+
// A standard error of 0 is constant data also when the mean is 0 (R's test 0 < 0 lets [0, 0] through to NaN; #314)
|
|
74
|
+
if (stdErr === 0 || stdErr < 10 * Number.EPSILON * Math.abs(mx))
|
|
61
75
|
throw new Error("data are essentially constant");
|
|
62
|
-
tstat = (mx -
|
|
76
|
+
tstat = (mx - muS) / stdErr;
|
|
63
77
|
method = paired ? "Paired t-test" : "One Sample t-test";
|
|
64
78
|
estimate = mx;
|
|
65
79
|
estimateNames = paired ? "mean difference" : "mean of x";
|
|
@@ -91,31 +105,47 @@ export function tTest(x, y, options = {}) {
|
|
|
91
105
|
else {
|
|
92
106
|
const sx = vx / nx;
|
|
93
107
|
const sy = vy / ny;
|
|
94
|
-
|
|
95
|
-
|
|
108
|
+
// as R, the standard error from the two standard errors (sqrt of the scaled variances is exact: the scale is
|
|
109
|
+
// 2^-2k)
|
|
110
|
+
stdErr = Math.sqrt(Math.sqrt(sx) ** 2 + Math.sqrt(sy) ** 2);
|
|
111
|
+
df = satterthwaiteDfSe([sx, sy], [nx - 1, ny - 1]);
|
|
96
112
|
}
|
|
97
|
-
if (stdErr < 10 * Number.EPSILON * Math.max(Math.abs(mx), Math.abs(my))) {
|
|
113
|
+
if (stdErr === 0 || stdErr < 10 * Number.EPSILON * Math.max(Math.abs(mx), Math.abs(my))) {
|
|
98
114
|
throw new Error("data are essentially constant");
|
|
99
115
|
}
|
|
100
|
-
tstat = (mx - my -
|
|
116
|
+
tstat = (mx - my - muS) / stdErr;
|
|
101
117
|
}
|
|
118
|
+
// The ends are R's mu + (t ± q) stdErr (the same bits as R where its parts are). That cancels where mu or t stdErr is
|
|
119
|
+
// far larger than the interval itself (R's t.test(1:4, mu = 1e6) is 1.4e-10 off, mu = -1e300 gives [0, 0]; an
|
|
120
|
+
// infinite mu NaN): where either exceeds 16 times abs(estimate) + q stdErr, or the end is not finite, the end is the
|
|
121
|
+
// estimate -+ q stdErr instead (revision of review 3). (A standard error of 0 is an error above)
|
|
122
|
+
const centre = typeof estimate === "number" ? estimate : estimate[0] - estimate[1];
|
|
123
|
+
const end = (q, sign) => {
|
|
124
|
+
const r = muS + (tstat + sign * q) * stdErr;
|
|
125
|
+
if (Number.isFinite(r) && Math.max(Math.abs(muS), Math.abs(tstat * stdErr)) <= 16 * (Math.abs(centre) + q * stdErr))
|
|
126
|
+
return r;
|
|
127
|
+
return centre + sign * q * stdErr;
|
|
128
|
+
};
|
|
102
129
|
let pValue;
|
|
103
130
|
let confInt;
|
|
104
131
|
if (alternative === "less") {
|
|
105
132
|
pValue = pt1(tstat, df, true, false);
|
|
106
|
-
confInt = [-Infinity,
|
|
133
|
+
confInt = [-Infinity, end(qt1(confLevel, df, true, false), 1)];
|
|
107
134
|
}
|
|
108
135
|
else if (alternative === "greater") {
|
|
109
136
|
pValue = pt1(tstat, df, false, false);
|
|
110
|
-
confInt = [
|
|
137
|
+
confInt = [end(qt1(confLevel, df, true, false), -1), Infinity];
|
|
111
138
|
}
|
|
112
139
|
else {
|
|
113
140
|
pValue = 2 * pt1(-Math.abs(tstat), df, true, false);
|
|
114
141
|
const alpha = 1 - confLevel;
|
|
115
|
-
|
|
116
|
-
|
|
142
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
|
|
143
|
+
const c = alpha / 2 < 1e-8 ? qt1(alpha / 2, df, false, false) : qt1(1 - alpha / 2, df, true, false);
|
|
144
|
+
confInt = [end(c, -1), end(c, 1)];
|
|
117
145
|
}
|
|
118
|
-
confInt = [
|
|
146
|
+
confInt = [ldexp(confInt[0], k), ldexp(confInt[1], k)];
|
|
147
|
+
estimate = typeof estimate === "number" ? ldexp(estimate, k) : estimate.map((v) => ldexp(v, k));
|
|
148
|
+
stdErr = ldexp(stdErr, k);
|
|
119
149
|
return {
|
|
120
150
|
method,
|
|
121
151
|
alternative,
|
|
@@ -131,6 +161,8 @@ export function tTest(x, y, options = {}) {
|
|
|
131
161
|
nullValue: mu,
|
|
132
162
|
nullValueName,
|
|
133
163
|
stdErr,
|
|
164
|
+
stdError: stdErr,
|
|
165
|
+
warnings: [],
|
|
134
166
|
};
|
|
135
167
|
}
|
|
136
168
|
/** t.test from a formula: the default form on the data the formula selects, with the estimates named after the levels */
|
|
@@ -54,19 +54,19 @@ export function twoSampleData(formula, data, oneSample) {
|
|
|
54
54
|
if (pair !== null) {
|
|
55
55
|
const { terms, rhsVariables } = plainTerms(`~${sides.rhs}`, data);
|
|
56
56
|
if (!oneSample || !interceptOnly(terms, rhsVariables))
|
|
57
|
-
throw new
|
|
57
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
58
58
|
const frame = modelFrame(data, [pair[1], pair[2]]);
|
|
59
59
|
return { kind: "paired", x: numericValues(frame.variables[0], pair[1]), y: numericValues(frame.variables[1], pair[2]) };
|
|
60
60
|
}
|
|
61
61
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
62
62
|
if (terms.response < 0)
|
|
63
|
-
throw new
|
|
63
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
64
64
|
const response = terms.variables[0];
|
|
65
65
|
if (oneSample && interceptOnly(terms, rhsVariables)) {
|
|
66
66
|
return { kind: "one", x: numericValues(modelFrame(data, [response]).variables[0], response) };
|
|
67
67
|
}
|
|
68
68
|
if (rhsVariables.length !== 1 || terms.terms.length !== 1)
|
|
69
|
-
throw new
|
|
69
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
70
70
|
const frame = modelFrame(data, [response, rhsVariables[0]], { dropUnusedLevels: true });
|
|
71
71
|
const values = numericValues(frame.variables[0], response);
|
|
72
72
|
const group = groupFactor(frame.variables[1]);
|
|
@@ -83,16 +83,16 @@ export function twoSampleData(formula, data, oneSample) {
|
|
|
83
83
|
export function twoGroupData(formula, data) {
|
|
84
84
|
const d = twoSampleData(formula, data, false);
|
|
85
85
|
if (d.kind !== "two")
|
|
86
|
-
throw new
|
|
86
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
87
87
|
return d;
|
|
88
88
|
}
|
|
89
89
|
/** The response and group of a formula `y ~ g` with one variable on the right (kruskal.test, fligner.test, bartlett.test) */
|
|
90
90
|
export function kSampleData(formula, data) {
|
|
91
91
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
92
92
|
if (terms.response < 0)
|
|
93
|
-
throw new
|
|
93
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
94
94
|
if (rhsVariables.length !== 1)
|
|
95
|
-
throw new
|
|
95
|
+
throw new TypeError("'formula' should be of the form response ~ group");
|
|
96
96
|
const response = terms.variables[0];
|
|
97
97
|
const frame = modelFrame(data, [response, rhsVariables[0]], { dropUnusedLevels: true });
|
|
98
98
|
return { values: numericValues(frame.variables[0], response), group: groupFactor(frame.variables[1]) };
|
|
@@ -110,7 +110,7 @@ export function samplesByLevel(values, group) {
|
|
|
110
110
|
export function onewayData(formula, data) {
|
|
111
111
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
112
112
|
if (terms.response < 0 || rhsVariables.length === 0)
|
|
113
|
-
throw new
|
|
113
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
114
114
|
const response = terms.variables[0];
|
|
115
115
|
const frame = modelFrame(data, [response, ...rhsVariables], { dropUnusedLevels: true });
|
|
116
116
|
const factors = frame.variables.slice(1).map(groupFactor);
|
|
@@ -135,11 +135,11 @@ export function blockData(formula, data) {
|
|
|
135
135
|
const sides = splitTilde(formula);
|
|
136
136
|
const parts = sides?.rhs.split("|");
|
|
137
137
|
if (sides === undefined || sides.lhs === "" || parts.length !== 2)
|
|
138
|
-
throw new
|
|
138
|
+
throw new TypeError(INCORRECT_BLOCKS);
|
|
139
139
|
const one = (text) => {
|
|
140
140
|
const { terms, rhsVariables } = plainTerms(text, data);
|
|
141
141
|
if (rhsVariables.length !== 1 || terms.terms.length !== 1)
|
|
142
|
-
throw new
|
|
142
|
+
throw new TypeError(INCORRECT_BLOCKS);
|
|
143
143
|
return rhsVariables[0];
|
|
144
144
|
};
|
|
145
145
|
const { terms } = plainTerms(`${sides.lhs} ~ 1`, data);
|
|
@@ -166,9 +166,9 @@ export function blockData(formula, data) {
|
|
|
166
166
|
export function correlationData(formula, data) {
|
|
167
167
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
168
168
|
if (terms.response >= 0)
|
|
169
|
-
throw new
|
|
169
|
+
throw new TypeError("'formula' missing or invalid");
|
|
170
170
|
if (rhsVariables.length !== 2)
|
|
171
|
-
throw new
|
|
171
|
+
throw new TypeError("invalid formula");
|
|
172
172
|
const frame = modelFrame(data, rhsVariables);
|
|
173
173
|
return { x: numericValues(frame.variables[0], rhsVariables[0]), y: numericValues(frame.variables[1], rhsVariables[1]) };
|
|
174
174
|
}
|
|
@@ -10,11 +10,23 @@ export interface PropTrendTestResult extends Omit<HTest, "alternative"> {
|
|
|
10
10
|
parameter: number;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
13
|
+
* Options for {@link propTrendTest}.
|
|
14
|
+
*
|
|
15
|
+
* @category Hypothesis tests
|
|
16
|
+
*/
|
|
17
|
+
export interface PropTrendTestOptions {
|
|
18
|
+
/** Scores of the groups (as the third argument `score`). Default `1, 2, ..., k`. */
|
|
19
|
+
score?: Sample;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Chi-squared test for trend in proportions. Equivalent to R's `prop.trend.test(x, n, score)`. The scores are the
|
|
23
|
+
* third argument or the option `score` (giving both is a RangeError).
|
|
14
24
|
*
|
|
15
25
|
* @param x Numbers of events.
|
|
16
26
|
* @param n Numbers of trials.
|
|
17
|
-
* @param score Scores of the groups. Default `1, 2, ..., k`.
|
|
27
|
+
* @param score Scores of the groups. Default `1, 2, ..., k`. A group with a NaN score is left out of the regression
|
|
28
|
+
* (as R's `lm` omits it), but its counts stay in the pooled proportion and the weights, as in R. Other scores must
|
|
29
|
+
* be finite, with at least two distinct values. With no events or only events (all proportions 0, or all 1) the test is not defined (an error, as in R).
|
|
18
30
|
*
|
|
19
31
|
* @example
|
|
20
32
|
* ```ts
|
|
@@ -24,6 +36,16 @@ export interface PropTrendTestResult extends Omit<HTest, "alternative"> {
|
|
|
24
36
|
* @category Hypothesis tests
|
|
25
37
|
*/
|
|
26
38
|
export declare function propTrendTest(x: Sample, n: Sample, score?: Sample): PropTrendTestResult;
|
|
39
|
+
/**
|
|
40
|
+
* Chi-squared test for trend in proportions, with the scores in the options:
|
|
41
|
+
* `propTrendTest(x, n, { score: [0, 1, 2, 4] })`.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* propTrendTest([15, 10, 8, 4], [30, 30, 30, 30], { score: [1, 2, 3, 4] }).statistic; // 9.573428850537288
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare function propTrendTest(x: Sample, n: Sample, options: PropTrendTestOptions): PropTrendTestResult;
|
|
27
49
|
/**
|
|
28
50
|
* Alternative of {@link jonckheereTest}.
|
|
29
51
|
*
|
|
@@ -40,7 +62,9 @@ export interface JonckheereTestOptions {
|
|
|
40
62
|
alternative?: JonckheereAlternative | (string & {});
|
|
41
63
|
/**
|
|
42
64
|
* The exact p-value (`"DescTools"` only). Default: exact when there are no ties and at most 100 observations. With
|
|
43
|
-
* ties the normal approximation is used anyway, with a warning.
|
|
65
|
+
* ties the normal approximation is used anyway, with a warning. The exact distribution is the convolution of the
|
|
66
|
+
* Mann-Whitney distributions; where it would have more than 2^24 values or take more than 2^32 multiply-adds
|
|
67
|
+
* (three groups of 215, about 8 s), `exact: true` is a RangeError (R computes it however long it takes).
|
|
44
68
|
*/
|
|
45
69
|
exact?: boolean;
|
|
46
70
|
/** `"DescTools"` (default: `JonckheereTerpstraTest`) or `"clinfun"` (`jonckheere.test`). */
|
|
@@ -63,7 +87,7 @@ export interface JonckheereTestResult extends Omit<HTest, "alternative"> {
|
|
|
63
87
|
* Jonckheere-Terpstra test of equal distributions against ordered alternatives. Equivalent to
|
|
64
88
|
* `DescTools::JonckheereTerpstraTest()` in R. Computes `JonckheereTerpstraTest(x, g, alternative, exact)` (with `g`
|
|
65
89
|
* an ordered factor) or, with `variant: "clinfun"`, clinfun's `jonckheere.test(x, g, alternative)` (whose
|
|
66
|
-
* two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped.
|
|
90
|
+
* two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped (with `variant: "clinfun"`, also those with an infinite value, as clinfun does).
|
|
67
91
|
*
|
|
68
92
|
* @param x The values.
|
|
69
93
|
* @param g Group labels, parallel to `x`, in the order of the alternative.
|
package/dist/htest/trendTests.js
CHANGED
|
@@ -12,44 +12,73 @@
|
|
|
12
12
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
13
13
|
import { pnorm } from "../distributions/normal.js";
|
|
14
14
|
import { dwilcox1 } from "../distributions/wilcox.js";
|
|
15
|
+
import { optionalArgs } from "../internal/optionalArgs.js";
|
|
15
16
|
import { levelText, numberLevels } from "../internal/levels.js";
|
|
17
|
+
import { ldexp, scaleToUnit, squareOver } from "../internal/summary.js";
|
|
16
18
|
import { compareCodePoints } from "../models/modelFrame.js";
|
|
17
19
|
import { matchChoice } from "./power.js";
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
* propTrendTest([15, 10, 8, 4], [30, 30, 30, 30]).statistic; // 9.573428850537288
|
|
28
|
-
* ```
|
|
29
|
-
*
|
|
30
|
-
* @category Hypothesis tests
|
|
31
|
-
*/
|
|
32
|
-
export function propTrendTest(x, n, score) {
|
|
20
|
+
import { reported } from "../internal/warnings.js";
|
|
21
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
22
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
23
|
+
import { optionsIn } from "../internal/optionalArgs.js";
|
|
24
|
+
const PROP_TREND_TEST_KEYS = ["score"];
|
|
25
|
+
const JONCKHEERE_TEST_KEYS = ["alternative", "exact", "variant", "levels"];
|
|
26
|
+
export function propTrendTest(x, n, ...args) {
|
|
27
|
+
checkOptions(optionsIn(args), PROP_TREND_TEST_KEYS, "propTrendTest"); // generated: option-keys.mjs
|
|
28
|
+
const { score } = optionalArgs(["score"], args);
|
|
33
29
|
const xs = Array.from(x);
|
|
34
30
|
const ns = Array.from(n);
|
|
35
31
|
const k = xs.length;
|
|
36
32
|
const s = score === undefined ? xs.map((_, i) => i + 1) : Array.from(score);
|
|
37
33
|
if (ns.length !== k || s.length !== k)
|
|
38
34
|
throw new RangeError("'x', 'n' and 'score' must have the same length");
|
|
39
|
-
|
|
35
|
+
if (ns.some((v) => !(v > 0 && v < Infinity)))
|
|
36
|
+
throw new RangeError("elements of 'n' must be positive and finite");
|
|
37
|
+
if (xs.some((v, i) => !(v >= 0 && v <= ns[i])))
|
|
38
|
+
throw new RangeError("elements of 'x' must be between 0 and 'n'");
|
|
39
|
+
// With no events or only events the pooled proportion is 0 or 1, the weights n / (p (1 - p)) are infinite and every
|
|
40
|
+
// proportion is the same: no trend to test (R's lm: "NA/NaN/Inf in 'x'"; this returned NaN, #319)
|
|
41
|
+
if (xs.every((v) => v === 0) || xs.every((v, i) => v === ns[i])) {
|
|
42
|
+
throw new RangeError("all proportions are 0 or all are 1: the test for trend is not defined");
|
|
43
|
+
}
|
|
44
|
+
const sumN = ns.reduce((a, v) => a + v, 0);
|
|
45
|
+
const p = xs.reduce((a, v) => a + v, 0) / sumN;
|
|
40
46
|
const w = ns.map((v) => v / (p * (1 - p)));
|
|
41
47
|
const f = xs.map((v, i) => v / ns[i]);
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
48
|
+
// the weighted regression of f on the scores, over the groups with a score
|
|
49
|
+
const rows = s.flatMap((v, i) => (Number.isNaN(v) ? [] : [i]));
|
|
50
|
+
if (rows.length === 0)
|
|
51
|
+
throw new RangeError("no non-missing scores");
|
|
52
|
+
// An infinite score made the centred scores Inf - Inf and the statistic NaN (R's lm: "NA/NaN/Inf in 'x'"; #317)
|
|
53
|
+
if (rows.some((i) => !Number.isFinite(s[i])))
|
|
54
|
+
throw new RangeError("non-missing scores must be finite");
|
|
55
|
+
// One distinct score (all equal, or one group with a score) leaves no slope: sxx = sxy = 0 and the statistic 0 / 0
|
|
56
|
+
// (R's NA; NaN before, #318)
|
|
57
|
+
if (rows.every((i) => s[i] === s[rows[0]]))
|
|
58
|
+
throw new RangeError("at least 2 distinct non-missing scores are needed");
|
|
59
|
+
let sc = s;
|
|
60
|
+
let { sw, sxy, sxx } = trendRegression(w, f, sc, rows);
|
|
61
|
+
if (!(sxx >= 2 ** -1022 && sxx < Infinity && Math.abs(sxy) < Infinity)) {
|
|
62
|
+
// Scores far from 1 (0 and 1e200, or 0 and 2^-700): sxx overflowed or underflowed, and the statistic was 0 or
|
|
63
|
+
// Infinity. The statistic does not change when the scores are multiplied by a constant, so it is formed from the
|
|
64
|
+
// scores divided by a power of 2 that brings the largest into [1, 2) (#389). Otherwise the same bits as before
|
|
65
|
+
const scaled = scaleToUnit([rows.map((i) => s[i])]);
|
|
66
|
+
if (scaled.k !== 0) {
|
|
67
|
+
sc = s.slice();
|
|
68
|
+
rows.forEach((i, j) => (sc[i] = scaled.groups[0][j]));
|
|
69
|
+
({ sw, sxy, sxx } = trendRegression(w, f, sc, rows));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
let statistic = squareOver(sxy, sxx);
|
|
73
|
+
if (!(sumN < Infinity) || (p > 0 && p < 1 && !(sw < Infinity && Math.abs(sxy) < Infinity && sxx < Infinity))) {
|
|
74
|
+
// The totals or the weights overflow although the counts are finite: the pooled proportion from the counts
|
|
75
|
+
// scaled by 2^-k, and the regression with the weights n_i 2^-k (the common factor 1 / (p (1 - p)) cancels in the
|
|
76
|
+
// means), the statistic sxy^2 / sxx / (p (1 - p)) multiplied back by 2^k
|
|
77
|
+
const { groups: [xu, nu], k, } = scaleToUnit([xs, ns]);
|
|
78
|
+
const pu = xu.reduce((a, v) => a + v, 0) / nu.reduce((a, v) => a + v, 0);
|
|
79
|
+
const u = trendRegression(nu, f, sc, rows);
|
|
80
|
+
statistic = ldexp((u.sxy / pu) * (u.sxy / u.sxx / (1 - pu)), k);
|
|
81
|
+
}
|
|
53
82
|
return {
|
|
54
83
|
method: "Chi-squared Test for Trend in Proportions",
|
|
55
84
|
statistic,
|
|
@@ -57,16 +86,38 @@ export function propTrendTest(x, n, score) {
|
|
|
57
86
|
parameter: 1,
|
|
58
87
|
parameterName: "df",
|
|
59
88
|
pValue: pgamma1(statistic, 0.5, 2, false, false),
|
|
89
|
+
warnings: [],
|
|
60
90
|
};
|
|
61
91
|
}
|
|
92
|
+
/** Weighted sums of the regression of f on the scores s over the given rows: the total weight and the centred sums */
|
|
93
|
+
function trendRegression(w, f, s, rows) {
|
|
94
|
+
const sw = rows.reduce((a, i) => a + w[i], 0);
|
|
95
|
+
const sBar = rows.reduce((a, i) => a + w[i] * s[i], 0) / sw;
|
|
96
|
+
const fBar = rows.reduce((a, i) => a + w[i] * f[i], 0) / sw;
|
|
97
|
+
let sxy = 0;
|
|
98
|
+
let sxx = 0;
|
|
99
|
+
for (const i of rows) {
|
|
100
|
+
const ds = s[i] - sBar;
|
|
101
|
+
sxy += w[i] * ds * (f[i] - fBar);
|
|
102
|
+
sxx += w[i] * ds * ds;
|
|
103
|
+
}
|
|
104
|
+
return { sw, sxy, sxx };
|
|
105
|
+
}
|
|
106
|
+
/** Largest length (as #232's 2^24) and number of multiply-adds (three groups of 215: about 8 s) of the exact JT distribution (#321) */
|
|
107
|
+
const MAX_EXACT_LENGTH = 2 ** 24;
|
|
108
|
+
const MAX_EXACT_WORK = 2 ** 32;
|
|
62
109
|
const NOT_EXACT = "Sample size > 100 or data with ties \n p-value based on normal approximation. Specify nperm for permutation p-value";
|
|
63
110
|
const TIES = "Sample data with ties \n p-value based on normal approximation. Specify nperm for permutation p-value.";
|
|
64
|
-
/**
|
|
65
|
-
|
|
111
|
+
/**
|
|
112
|
+
* The groups in order: the labels sorted (numbers as numbers, strings by code point) or as `levels`. Pairs with a NaN
|
|
113
|
+
* are dropped, and with `finiteOnly` also those with an infinite value or numeric label
|
|
114
|
+
*/
|
|
115
|
+
function orderedGroups(x, g, levels, finiteOnly = false) {
|
|
66
116
|
const xs = Array.from(x);
|
|
67
117
|
if (xs.length !== g.length)
|
|
68
118
|
throw new RangeError("'x' and 'g' must have the same length");
|
|
69
|
-
const
|
|
119
|
+
const bad = (v) => typeof v === "number" && (finiteOnly ? !Number.isFinite(v) : Number.isNaN(v));
|
|
120
|
+
const keep = xs.flatMap((v, i) => (bad(v) || bad(g[i]) ? [] : [i]));
|
|
70
121
|
// numeric labels with the same 15-digit text are one level, as in R's factor() (only without given levels, which
|
|
71
122
|
// are matched by their text)
|
|
72
123
|
if (levels === undefined)
|
|
@@ -90,11 +141,28 @@ function orderedGroups(x, g, levels) {
|
|
|
90
141
|
}
|
|
91
142
|
return groups;
|
|
92
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* The null variance of JT under ties (Hollander & Wolfe): the variance of the permutation distribution given the
|
|
146
|
+
* group sizes n_i and the sizes t_j of the groups of tied values. The packages (clinfun, DescTools) use the variance
|
|
147
|
+
* without ties there, which is too large (review 59)
|
|
148
|
+
*/
|
|
149
|
+
function tiedVariance(groupSizes, all) {
|
|
150
|
+
const counts = new Map();
|
|
151
|
+
for (const v of all)
|
|
152
|
+
counts.set(v, (counts.get(v) ?? 0) + 1);
|
|
153
|
+
const t = [...counts.values()];
|
|
154
|
+
const N = all.length;
|
|
155
|
+
const s1 = (a, f) => a.reduce((acc, v) => acc + f(v), 0);
|
|
156
|
+
const first = (N * (N - 1) * (2 * N + 5) - s1(groupSizes, (v) => v * (v - 1) * (2 * v + 5)) - s1(t, (v) => v * (v - 1) * (2 * v + 5))) / 72;
|
|
157
|
+
const second = N < 3 ? 0 : (s1(groupSizes, (v) => v * (v - 1) * (v - 2)) * s1(t, (v) => v * (v - 1) * (v - 2))) / (36 * N * (N - 1) * (N - 2));
|
|
158
|
+
const third = (s1(groupSizes, (v) => v * (v - 1)) * s1(t, (v) => v * (v - 1))) / (8 * N * (N - 1));
|
|
159
|
+
return first + second + third;
|
|
160
|
+
}
|
|
93
161
|
/**
|
|
94
162
|
* Jonckheere-Terpstra test of equal distributions against ordered alternatives. Equivalent to
|
|
95
163
|
* `DescTools::JonckheereTerpstraTest()` in R. Computes `JonckheereTerpstraTest(x, g, alternative, exact)` (with `g`
|
|
96
164
|
* an ordered factor) or, with `variant: "clinfun"`, clinfun's `jonckheere.test(x, g, alternative)` (whose
|
|
97
|
-
* two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped.
|
|
165
|
+
* two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped (with `variant: "clinfun"`, also those with an infinite value, as clinfun does).
|
|
98
166
|
*
|
|
99
167
|
* @param x The values.
|
|
100
168
|
* @param g Group labels, parallel to `x`, in the order of the alternative.
|
|
@@ -107,13 +175,18 @@ function orderedGroups(x, g, levels) {
|
|
|
107
175
|
* @category Hypothesis tests
|
|
108
176
|
*/
|
|
109
177
|
export function jonckheereTest(x, g, options = {}) {
|
|
178
|
+
checkOptions(options, JONCKHEERE_TEST_KEYS, "jonckheereTest"); // generated: option-keys.mjs
|
|
110
179
|
const alternative = matchChoice(options.alternative, ["two.sided", "increasing", "decreasing"]);
|
|
111
180
|
const variant = options.variant ?? "DescTools";
|
|
112
181
|
if (variant !== "DescTools" && variant !== "clinfun")
|
|
113
182
|
throw new RangeError(`invalid variant "${String(variant)}"`);
|
|
114
183
|
if (variant === "clinfun" && options.exact !== undefined)
|
|
115
184
|
throw new TypeError("clinfun's jonckheere.test has no option 'exact'");
|
|
116
|
-
|
|
185
|
+
// clinfun keeps only the pairs where both values are finite
|
|
186
|
+
const groups = orderedGroups(x, g, options.levels, variant === "clinfun");
|
|
187
|
+
// with fewer than 2 nonempty groups there is no pair to compare (the packages' errors)
|
|
188
|
+
if (groups.filter((gi) => gi.length > 0).length < 2)
|
|
189
|
+
throw new RangeError(variant === "clinfun" ? "only one group has non-missing data" : "all observations are in the same group");
|
|
117
190
|
const all = groups.flat();
|
|
118
191
|
const nTotal = all.length;
|
|
119
192
|
const ties = new Set(all).size < nTotal;
|
|
@@ -144,6 +217,18 @@ export function jonckheereTest(x, g, options = {}) {
|
|
|
144
217
|
let lower;
|
|
145
218
|
let upper;
|
|
146
219
|
if (exact) {
|
|
220
|
+
// the length of the convolution and its multiply-adds, checked before anything is built (#321)
|
|
221
|
+
let len = 1;
|
|
222
|
+
let work = 0;
|
|
223
|
+
for (const [ni, mi] of sizes) {
|
|
224
|
+
if (ni === 0 || mi === 0)
|
|
225
|
+
continue;
|
|
226
|
+
work += len * (ni * mi + 1);
|
|
227
|
+
len += ni * mi;
|
|
228
|
+
}
|
|
229
|
+
if (len > MAX_EXACT_LENGTH || work > MAX_EXACT_WORK) {
|
|
230
|
+
throw new RangeError(`the exact distribution of JT has ${len} values and needs ${work} steps, too many: use exact: false`);
|
|
231
|
+
}
|
|
147
232
|
// the convolution of the Mann-Whitney distributions
|
|
148
233
|
let dist = [1];
|
|
149
234
|
for (const [ni, mi] of sizes) {
|
|
@@ -165,12 +250,16 @@ export function jonckheereTest(x, g, options = {}) {
|
|
|
165
250
|
}
|
|
166
251
|
else {
|
|
167
252
|
const mean = sizes.reduce((a, [ni, mi]) => a + ni * mi, 0) / 2;
|
|
168
|
-
const variance = sizes.reduce((a, [ni, mi]) => a + (ni * mi * (ni + mi + 1)) / 12, 0);
|
|
253
|
+
const variance = ties ? tiedVariance(groups.map((gi) => gi.length), all) : sizes.reduce((a, [ni, mi]) => a + (ni * mi * (ni + mi + 1)) / 12, 0);
|
|
169
254
|
const z = (jt - mean) / Math.sqrt(variance);
|
|
170
255
|
lower = pnorm(z);
|
|
171
256
|
upper = 1 - lower;
|
|
257
|
+
// 1 - pnorm loses the small upper tail (0 beyond z ~ 8.3); below 1e-8 take it directly,
|
|
258
|
+
// elsewhere the packages' expression (the same bits) (#280)
|
|
259
|
+
if (upper < 1e-8)
|
|
260
|
+
upper = pnorm(z, { lowerTail: false });
|
|
172
261
|
}
|
|
173
262
|
const cap = variant === "clinfun" ? 0.5 : 1;
|
|
174
|
-
const pValue = alternative === "increasing" ? upper : alternative === "decreasing" ? lower : 2 * Math.min(upper, lower, cap);
|
|
175
|
-
return { method: "Jonckheere-Terpstra test", alternative, statistic: jt, statisticName: "JT", pValue, warnings };
|
|
263
|
+
const pValue = alternative === "increasing" ? upper : alternative === "decreasing" ? lower : Math.min(1, 2 * Math.min(upper, lower, cap)); // (DescTools can exceed 1)
|
|
264
|
+
return reported("jonckheereTest", { method: "Jonckheere-Terpstra test", alternative, statistic: jt, statisticName: "JT", pValue, warnings });
|
|
176
265
|
}
|
package/dist/htest/types.d.ts
CHANGED
|
@@ -54,10 +54,17 @@ export interface HTest {
|
|
|
54
54
|
nullValue?: number;
|
|
55
55
|
/** Name of `nullValue` (R's `names(null.value)`), e.g. `"difference in means"`. */
|
|
56
56
|
nullValueName?: string;
|
|
57
|
+
/** R's warnings, each once, in R's order (an empty array when there are none). */
|
|
58
|
+
warnings: string[];
|
|
57
59
|
}
|
|
58
60
|
/** Like R's match.arg, abbreviations ("two", "l", "g") are also accepted */
|
|
59
61
|
export declare function matchAlternative(a: string | undefined): Alternative;
|
|
60
62
|
/** Validate the confidence level (R's t.test also accepts exactly 0 and 1; with 1 the interval is ±Inf) */
|
|
61
63
|
export declare function checkConfLevel(level: number): void;
|
|
64
|
+
/**
|
|
65
|
+
* Whether v is a nonnegative count. The slack is absolute: a count is an integer whatever its size, so a relative
|
|
66
|
+
* slack would accept 1e8 + 0.25 and silently round it
|
|
67
|
+
*/
|
|
68
|
+
export declare function isCount(v: number): boolean;
|
|
62
69
|
/** Validate the confidence level strictly inside (0, 1), as most of R's tests require */
|
|
63
70
|
export declare function checkConfLevelOpen(level: number): void;
|