@numero-uno-jpn/rstats 0.15.2 → 0.16.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 +280 -0
- package/README.ja.md +40 -33
- package/README.md +36 -28
- package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
- package/dist/chunks/chunk-5UQCRBAG.js +2 -0
- package/dist/chunks/chunk-6CSTWA5E.js +2 -0
- package/dist/chunks/chunk-72Y3HZID.js +2 -0
- package/dist/chunks/chunk-BG2KLEHM.js +2 -0
- package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
- package/dist/chunks/chunk-FLJNSXSW.js +2 -0
- package/dist/chunks/chunk-GM53LWSR.js +2 -0
- package/dist/chunks/chunk-JBCA56ZS.js +3 -0
- package/dist/chunks/chunk-K3RJAD2T.js +2 -0
- package/dist/chunks/chunk-KAZRWIB5.js +2 -0
- package/dist/chunks/chunk-KBVVIMXX.js +3 -0
- package/dist/chunks/chunk-N3SIFCZX.js +2 -0
- package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
- package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
- package/dist/chunks/chunk-SYWOBOTR.js +2 -0
- package/dist/chunks/chunk-URIO5LY5.js +2 -0
- package/dist/chunks/chunk-VTUGG2SV.js +2 -0
- package/dist/chunks/chunk-W26LRYOJ.js +2 -0
- package/dist/chunks/chunk-XHETEYVC.js +2 -0
- package/dist/chunks/{chunk-PWVQVJTP.js → chunk-YRZWONZB.js} +1 -1
- package/dist/chunks/chunk-ZGABZMWX.js +2 -0
- package/dist/data/grouping.js +20 -5
- package/dist/descriptive/basic.js +90 -8
- package/dist/descriptive/cov.js +12 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +56 -18
- package/dist/descriptive/factanal.js +16 -7
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +71 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +72 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +68 -9
- package/dist/descriptive/pivot.d.ts +21 -9
- package/dist/descriptive/pivot.js +161 -35
- package/dist/descriptive/quantile.js +2 -1
- package/dist/descriptive/rank.js +4 -1
- package/dist/descriptive/table.d.ts +3 -2
- package/dist/descriptive/table.js +24 -9
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +19 -2
- package/dist/distributions/beta.js +35 -5
- package/dist/distributions/binomial.js +37 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +87 -8
- package/dist/distributions/chisq.js +7 -3
- package/dist/distributions/exponential.js +11 -1
- package/dist/distributions/f.js +73 -22
- package/dist/distributions/gamma.js +61 -6
- package/dist/distributions/geometric.js +53 -14
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +93 -6
- package/dist/distributions/invgamma.js +6 -1
- package/dist/distributions/kumaraswamy.js +22 -4
- package/dist/distributions/laplace.js +31 -7
- package/dist/distributions/logistic.js +11 -2
- package/dist/distributions/lognormal.js +20 -3
- package/dist/distributions/multinomial.js +54 -11
- package/dist/distributions/nbeta.js +128 -35
- package/dist/distributions/nchisq.js +85 -14
- package/dist/distributions/negbinomial.js +100 -18
- package/dist/distributions/normal.js +35 -5
- package/dist/distributions/nt.d.ts +28 -3
- package/dist/distributions/nt.js +536 -35
- package/dist/distributions/pareto.js +9 -1
- package/dist/distributions/poisson.js +28 -3
- package/dist/distributions/signrank.js +7 -4
- package/dist/distributions/summary.js +450 -60
- package/dist/distributions/t.js +55 -3
- package/dist/distributions/triangular.js +45 -13
- package/dist/distributions/tukey.js +21 -2
- package/dist/distributions/uniform.js +2 -0
- package/dist/distributions/weibull.js +33 -3
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +155 -26
- package/dist/distributions.js +2 -2
- package/dist/htest/agreement.d.ts +3 -2
- package/dist/htest/agreement.js +76 -14
- package/dist/htest/ansariTest.d.ts +6 -1
- package/dist/htest/ansariTest.js +75 -8
- package/dist/htest/aov.d.ts +1 -1
- package/dist/htest/aov.js +48 -34
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +41 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +7 -5
- package/dist/htest/chisqTest.d.ts +2 -1
- package/dist/htest/chisqTest.js +130 -43
- package/dist/htest/cor.d.ts +2 -1
- package/dist/htest/cor.js +17 -19
- 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/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +2 -0
- package/dist/htest/effectSize.js +91 -29
- package/dist/htest/fisherTest.d.ts +2 -2
- package/dist/htest/fisherTest.js +36 -18
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +3 -1
- package/dist/htest/ksTest.js +23 -2
- package/dist/htest/leveneTest.js +19 -3
- package/dist/htest/mantelhaenTest.js +125 -25
- package/dist/htest/mcnemarTest.js +32 -11
- package/dist/htest/multipleComparisons.d.ts +8 -1
- package/dist/htest/multipleComparisons.js +44 -21
- package/dist/htest/normalityTests.js +44 -10
- package/dist/htest/onewayTest.js +96 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +38 -6
- package/dist/htest/pairwise.d.ts +1 -1
- package/dist/htest/pairwise.js +17 -15
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +111 -59
- package/dist/htest/polycor.js +27 -7
- package/dist/htest/power.d.ts +11 -1
- package/dist/htest/power.js +112 -8
- package/dist/htest/propTest.js +21 -4
- package/dist/htest/pwr.js +121 -24
- package/dist/htest/rankTests.js +29 -5
- package/dist/htest/tTest.js +44 -21
- package/dist/htest/trendTests.d.ts +7 -3
- package/dist/htest/trendTests.js +114 -20
- package/dist/htest/types.d.ts +5 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +45 -14
- package/dist/htest/wilcoxTest.js +114 -21
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +23 -1
- package/dist/internal/ddexp.js +86 -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.d.ts +5 -0
- package/dist/internal/invert.js +25 -7
- package/dist/internal/noncentral.d.ts +7 -0
- package/dist/internal/noncentral.js +9 -0
- package/dist/internal/poissonMixture.js +29 -6
- 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/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +51 -7
- package/dist/linalg/chol.js +4 -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 +71 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +109 -15
- package/dist/linalg/kappa.js +58 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +35 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/ops.js +60 -13
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +91 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +147 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +29 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +124 -25
- package/dist/models/aovEz.js +140 -30
- package/dist/models/aovStrata.js +55 -22
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +83 -32
- package/dist/models/coxph.js +148 -66
- 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 +35 -5
- package/dist/models/glm.js +398 -55
- package/dist/models/glmAnova.js +84 -13
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +115 -27
- package/dist/models/glmFamily.d.ts +10 -0
- package/dist/models/glmFamily.js +244 -40
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +235 -36
- package/dist/models/lmer.d.ts +20 -1
- package/dist/models/lmer.js +109 -27
- package/dist/models/lmerAnova.js +37 -4
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +9 -2
- package/dist/models/lmerTest.js +64 -19
- package/dist/models/mauchly.d.ts +4 -1
- package/dist/models/mauchly.js +34 -13
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +8 -2
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +40 -15
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +6 -1
- package/dist/models/survival.js +67 -27
- 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 +64 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +103 -16
- package/dist/numerics/interp.d.ts +8 -2
- package/dist/numerics/interp.js +352 -50
- package/dist/numerics/ode.js +55 -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 +80 -8
- package/dist/random/beta.js +53 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +33 -5
- package/dist/random/extra.js +42 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +36 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +26 -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/sample.d.ts +12 -2
- package/dist/random/sample.js +57 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +168 -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 +11 -1
- package/dist/special/choose.js +17 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +15 -2
- package/dist/special/igam.js +33 -6
- package/dist/special/incbet.js +100 -10
- package/dist/special/incbetLargeA.js +7 -2
- package/dist/special/incbetPrefactor.d.ts +5 -0
- package/dist/special/incbetPrefactor.js +14 -3
- 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 +179 -33
- package/dist/special/log1pmx.js +4 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -11
- package/llms.txt +12 -6
- package/package.json +1 -1
- package/dist/chunks/chunk-2CUKVVRO.js +0 -2
- package/dist/chunks/chunk-3WQCKGKP.js +0 -2
- package/dist/chunks/chunk-4Z2XDWKV.js +0 -2
- package/dist/chunks/chunk-AJBLCNZ7.js +0 -3
- package/dist/chunks/chunk-D4F7GQAY.js +0 -2
- package/dist/chunks/chunk-EBQMGCQZ.js +0 -2
- package/dist/chunks/chunk-HBMHR5SS.js +0 -2
- package/dist/chunks/chunk-IBPWRQIF.js +0 -2
- package/dist/chunks/chunk-JLAH3X77.js +0 -2
- package/dist/chunks/chunk-LG74QY5U.js +0 -2
- package/dist/chunks/chunk-PEYGUK32.js +0 -2
- package/dist/chunks/chunk-Q4PGYESP.js +0 -2
- package/dist/chunks/chunk-RCAL4VHM.js +0 -3
- package/dist/chunks/chunk-SREPSVTT.js +0 -2
- package/dist/chunks/chunk-UFT662QZ.js +0 -2
- package/dist/chunks/chunk-VWJ74UHC.js +0 -2
- package/dist/chunks/chunk-XNPU54NH.js +0 -2
- package/dist/chunks/chunk-XPLDEK6D.js +0 -2
- package/dist/chunks/chunk-YGT4P7EU.js +0 -2
- package/dist/chunks/chunk-YVREYVI2.js +0 -2
package/dist/htest/agreement.js
CHANGED
|
@@ -10,8 +10,10 @@ import { cor, cov } from "../descriptive/cov.js";
|
|
|
10
10
|
import { pf1, qf1 } from "../distributions/f.js";
|
|
11
11
|
import { pnorm } from "../distributions/normal.js";
|
|
12
12
|
import { numberLevels } from "../internal/levels.js";
|
|
13
|
-
import { mean, sum, variance } from "../internal/summary.js";
|
|
13
|
+
import { mean, satterthwaiteDf, scaleToUnit, sum, variance } from "../internal/summary.js";
|
|
14
14
|
import { solve } from "../linalg/solve.js";
|
|
15
|
+
import { qr, qrResid } from "../linalg/qr.js";
|
|
16
|
+
import { ddAdd, ddDivNum, ddMul, ddSub } from "../special/dd.js";
|
|
15
17
|
import { formatR } from "./core/simulate.js";
|
|
16
18
|
import { matchChoice } from "./power.js";
|
|
17
19
|
import { checkConfLevelOpen } from "./types.js";
|
|
@@ -25,6 +27,8 @@ function columnsOf(x, what) {
|
|
|
25
27
|
function requireComplete(x, what) {
|
|
26
28
|
if (x.some((r) => r.some(Number.isNaN)))
|
|
27
29
|
throw new RangeError(`'${what}' contains missing values`);
|
|
30
|
+
if (x.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
31
|
+
throw new RangeError(`'${what}' contains infinite values`);
|
|
28
32
|
}
|
|
29
33
|
/** Two-sided normal p-value 2 Φ(−|z|) */
|
|
30
34
|
const twoSidedP = (z) => 2 * pnorm(-Math.abs(z));
|
|
@@ -37,7 +41,8 @@ const twoSidedP = (z) => 2 * pnorm(-Math.abs(z));
|
|
|
37
41
|
* the one under the null hypothesis; the p-value is computed as 2 Φ(−|z|), so small p-values are more accurate than
|
|
38
42
|
* irr's.
|
|
39
43
|
*
|
|
40
|
-
* @param ratings - An n × 2 matrix (array of rows): the ratings of the two raters for each subject
|
|
44
|
+
* @param ratings - An n × 2 matrix (array of rows): the ratings of the two raters for each subject, with at least 2
|
|
45
|
+
* complete rows.
|
|
41
46
|
* @param options - See {@link Kappa2Options}.
|
|
42
47
|
*
|
|
43
48
|
* @example
|
|
@@ -53,6 +58,11 @@ export function kappa2(ratings, options = {}) {
|
|
|
53
58
|
throw new TypeError("'ratings' must be a matrix with two columns");
|
|
54
59
|
const rows = ratings.filter((r) => !r.some(Number.isNaN));
|
|
55
60
|
const n = rows.length;
|
|
61
|
+
if (n === 0)
|
|
62
|
+
throw new RangeError("no complete rating pairs");
|
|
63
|
+
// the variance of kappa is 0 / 0 with one subject (irr returns z and p NaN)
|
|
64
|
+
if (n < 2)
|
|
65
|
+
throw new RangeError("at least 2 complete rating pairs are needed");
|
|
56
66
|
const first = rows.map((r) => formatR(r[0]));
|
|
57
67
|
const second = rows.map((r) => formatR(r[1]));
|
|
58
68
|
// the levels of both raters together, sorted as strings (by code point, as in R's C locale)
|
|
@@ -104,6 +114,8 @@ export function kappamFleiss(ratings, options = {}) {
|
|
|
104
114
|
requireComplete(ratings, "ratings");
|
|
105
115
|
const n = ratings.length;
|
|
106
116
|
const m = cols.length;
|
|
117
|
+
if (n < 2 || m < 2)
|
|
118
|
+
throw new RangeError("at least 2 subjects and 2 raters are needed");
|
|
107
119
|
// (the categories as R's factor() makes them: numbers with the same 15-digit text are one category)
|
|
108
120
|
const flat = ratings.flat();
|
|
109
121
|
const levelOf = numberLevels(flat);
|
|
@@ -162,19 +174,32 @@ export function icc(ratings, options = {}) {
|
|
|
162
174
|
const r0 = options.r0 ?? 0;
|
|
163
175
|
const confLevel = options.confLevel ?? 0.95;
|
|
164
176
|
checkConfLevelOpen(confLevel);
|
|
165
|
-
|
|
177
|
+
columnsOf(ratings, "ratings");
|
|
166
178
|
requireComplete(ratings, "ratings");
|
|
167
|
-
|
|
179
|
+
// the ratings scaled by one power of 2 (exact), so that the mean squares stay in range; the ICC, F and bounds do
|
|
180
|
+
// not depend on the units
|
|
181
|
+
const rows = scaleToUnit(ratings).groups;
|
|
182
|
+
const cols = columnsOf(rows, "ratings");
|
|
183
|
+
const n = rows.length;
|
|
168
184
|
const k = cols.length;
|
|
185
|
+
if (n < 2 || k < 2)
|
|
186
|
+
throw new RangeError("at least 2 subjects and 2 raters are needed");
|
|
187
|
+
if (!(r0 >= -1 && r0 < 1))
|
|
188
|
+
throw new RangeError("'r0' must be in [-1, 1)");
|
|
169
189
|
const alpha = 1 - confLevel;
|
|
170
190
|
// mean squares from sample variances
|
|
171
|
-
const msr = variance(
|
|
191
|
+
const msr = variance(rows.map((r) => mean(r))) * k;
|
|
172
192
|
const msc = variance(cols.map((c) => mean(c))) * n;
|
|
173
|
-
const msw = mean(
|
|
174
|
-
const ssTotal = variance(
|
|
175
|
-
|
|
193
|
+
const msw = mean(rows.map((r) => variance(r)));
|
|
194
|
+
const ssTotal = variance(rows.flat()) * (n * k - 1);
|
|
195
|
+
// the residual sum of squares by subtraction; where it cancels to below 2^-20 of the total (or to 0 or less) it
|
|
196
|
+
// is formed directly from the residuals in double-double (#392: subject and rater effects of 1e8 with an
|
|
197
|
+
// interaction of 1 gave mse 0, ICC 1 and F Infinity)
|
|
198
|
+
const ssE = ssTotal - msr * (n - 1) - msc * (k - 1);
|
|
199
|
+
const mse = ssE > 2 ** -20 * ssTotal ? ssE / ((n - 1) * (k - 1)) : residualSumOfSquares(rows) / ((n - 1) * (k - 1));
|
|
176
200
|
const upper = (F, d1, d2) => pf1(F, d1, d2, false, false);
|
|
177
|
-
|
|
201
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
|
|
202
|
+
const q = (d1, d2) => alpha / 2 < 1e-8 ? qf1(alpha / 2, d1, d2, false, false) : qf1(1 - alpha / 2, d1, d2, true, false);
|
|
178
203
|
const df1 = n - 1;
|
|
179
204
|
if (model === "oneway" || type === "consistency") {
|
|
180
205
|
const ms = model === "oneway" ? msw : mse;
|
|
@@ -190,7 +215,7 @@ export function icc(ratings, options = {}) {
|
|
|
190
215
|
// two-way agreement: Satterthwaite's degrees of freedom v for the combination a MSc + b MSe
|
|
191
216
|
const scale = unit === "single" ? k : 1;
|
|
192
217
|
const coefficients = (r) => [(scale * r) / (n * (1 - r)), 1 + (scale * r * (n - 1)) / (n * (1 - r))];
|
|
193
|
-
const dfOf = (a, b) => (a * msc
|
|
218
|
+
const dfOf = (a, b) => satterthwaiteDf([a * msc, b * mse], [k - 1, (n - 1) * (k - 1)]);
|
|
194
219
|
const value = unit === "single" ? (msr - mse) / (msr + (k - 1) * mse + (k / n) * (msc - mse)) : (msr - mse) / (msr + (msc - mse) / n);
|
|
195
220
|
const [a0, b0] = coefficients(r0);
|
|
196
221
|
const Fvalue = msr / (a0 * msc + b0 * mse);
|
|
@@ -220,7 +245,7 @@ function rawAlphaOf(C, keep) {
|
|
|
220
245
|
* and alpha with each item dropped. Equivalent to `psych::alpha()` in R. It gives the `total` row and
|
|
221
246
|
* `alpha.drop$raw_alpha` of `alpha(x)` with its defaults (no missing values, no reversed items).
|
|
222
247
|
*
|
|
223
|
-
* @param x - An n × k matrix (array of rows): k items observed on n subjects.
|
|
248
|
+
* @param x - An n × k matrix (array of rows): k ≥ 2 items observed on n ≥ 2 subjects.
|
|
224
249
|
*
|
|
225
250
|
* @example
|
|
226
251
|
* ```ts
|
|
@@ -234,12 +259,34 @@ export function cronbachAlpha(x) {
|
|
|
234
259
|
requireComplete(x, "x");
|
|
235
260
|
if (k < 2)
|
|
236
261
|
throw new RangeError("'x' needs at least two items");
|
|
237
|
-
|
|
262
|
+
// the sample covariances divide by n - 1
|
|
263
|
+
if (x.length < 2)
|
|
264
|
+
throw new RangeError("'x' needs at least two subjects");
|
|
265
|
+
// the covariances of the data scaled by one power of 2 (exact): raw alpha is a ratio of them
|
|
266
|
+
const C = cov(scaleToUnit(x).groups);
|
|
238
267
|
const R = cor(x);
|
|
239
268
|
const items = Array.from({ length: k }, (_, i) => i);
|
|
240
269
|
const sumR = sum(R.flat());
|
|
241
|
-
|
|
242
|
-
|
|
270
|
+
let smc;
|
|
271
|
+
try {
|
|
272
|
+
const Rinv = solve(R);
|
|
273
|
+
smc = items.map((i) => 1 - 1 / Rinv[i][i]);
|
|
274
|
+
}
|
|
275
|
+
catch (e) {
|
|
276
|
+
if (!R.flat().every(Number.isFinite))
|
|
277
|
+
throw e;
|
|
278
|
+
// A singular correlation matrix (a repeated item, an item that is the sum of others, or at least as many items as
|
|
279
|
+
// subjects): the SMC of item i is still the R^2 of lm(x_i ~ x_-i), here with R's QR (limited pivoting, tol 1e-7) on
|
|
280
|
+
// the data scaled by one power of 2. [[1, 1], [2, 2], [3, 3]] threw "exactly singular" (issue #468); psych's
|
|
281
|
+
// pseudo-inverse gives such items an SMC of 0 (G6 0.5), the R^2 is 1 (G6 1)
|
|
282
|
+
const xs = scaleToUnit(x).groups;
|
|
283
|
+
smc = items.map((i) => {
|
|
284
|
+
const y = xs.map((r) => r[i]);
|
|
285
|
+
const res = qrResid(qr(xs.map((r) => [1, ...r.filter((_, j) => j !== i)])), y);
|
|
286
|
+
const m = mean(y);
|
|
287
|
+
return 1 - sum(res.map((v) => v * v)) / sum(y.map((v) => (v - m) ** 2));
|
|
288
|
+
});
|
|
289
|
+
}
|
|
243
290
|
return {
|
|
244
291
|
rawAlpha: rawAlphaOf(C, items),
|
|
245
292
|
stdAlpha: ((1 - k / sumR) * k) / (k - 1),
|
|
@@ -287,3 +334,18 @@ export function partialR(x, i, j) {
|
|
|
287
334
|
}
|
|
288
335
|
return P[0][1] / Math.sqrt(P[0][0] * P[1][1]);
|
|
289
336
|
}
|
|
337
|
+
/** The residual sum of squares of the two-way layout, sum (x - row mean - column mean + grand mean)^2, in double-double */
|
|
338
|
+
function residualSumOfSquares(rows) {
|
|
339
|
+
const n = rows.length;
|
|
340
|
+
const k = rows[0].length;
|
|
341
|
+
const sumDD = (v) => v.reduce((a, x) => ddAdd(a, [x, 0]), [0, 0]);
|
|
342
|
+
const rm = rows.map((r) => ddDivNum(sumDD(r), k));
|
|
343
|
+
const cm = rows[0].map((_, j) => ddDivNum(sumDD(rows.map((r) => r[j])), n));
|
|
344
|
+
const gm = ddDivNum(sumDD(rows.flat()), n * k);
|
|
345
|
+
let ss = [0, 0];
|
|
346
|
+
rows.forEach((r, i) => r.forEach((x, j) => {
|
|
347
|
+
const e = ddAdd(ddSub(ddSub([x, 0], rm[i]), cm[j]), gm);
|
|
348
|
+
ss = ddAdd(ss, ddMul(e, e));
|
|
349
|
+
}));
|
|
350
|
+
return ss[0] + ss[1];
|
|
351
|
+
}
|
|
@@ -8,7 +8,12 @@ import { type Alternative, type HTest, type Sample } from "./types.js";
|
|
|
8
8
|
export interface AnsariTestOptions {
|
|
9
9
|
/** Alternative hypothesis (unambiguous abbreviations accepted). Default `"two.sided"`. */
|
|
10
10
|
alternative?: Alternative | "two" | "l" | "g";
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Exact p-value. Default: exact when both samples have fewer than 50 values and there are no ties. The exact
|
|
13
|
+
* distribution keeps 2 (m + 1) (floor((m + n + 1)^2 / 4) + 1) doubles and makes m + n passes over half of them;
|
|
14
|
+
* beyond 2^24 doubles or 2^32 steps (m = n = 203, or m = 1 and n = 2047) it is a RangeError (R computes it however
|
|
15
|
+
* large).
|
|
16
|
+
*/
|
|
12
17
|
exact?: boolean;
|
|
13
18
|
/** Compute a confidence interval for the ratio of scales and its estimate (R's `conf.int`). Default `false`. */
|
|
14
19
|
confInt?: boolean;
|
package/dist/htest/ansariTest.js
CHANGED
|
@@ -17,11 +17,12 @@
|
|
|
17
17
|
// values and of the negative values. The candidate sets, evaluation points, search range, tolerance and the cases
|
|
18
18
|
// returned as NaN (R's NA) follow R's documented and observed behaviour.
|
|
19
19
|
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
20
|
-
import { rank } from "../internal/summary.js";
|
|
20
|
+
import { ldexp, rank } from "../internal/summary.js";
|
|
21
21
|
import { uniroot } from "../internal/uniroot.js";
|
|
22
|
-
import { pansariExact, qansariR } from "./core/ansari.js";
|
|
22
|
+
import { checkAnsariExactSize, pansariExact, qansariR } from "./core/ansari.js";
|
|
23
23
|
import { twoGroupData } from "./testFormula.js";
|
|
24
24
|
import { checkConfLevelOpen, matchAlternative } from "./types.js";
|
|
25
|
+
import { maxOf, minOf } from "../internal/extremes.js";
|
|
25
26
|
export function ansariTest(x, y, options = {}) {
|
|
26
27
|
if (typeof x === "string") {
|
|
27
28
|
const d = twoGroupData(x, y);
|
|
@@ -51,6 +52,8 @@ export function ansariTest(x, y, options = {}) {
|
|
|
51
52
|
let pValue;
|
|
52
53
|
let ci;
|
|
53
54
|
if (exact && !ties) {
|
|
55
|
+
// (the exact distribution grows like m (m + n)^3: a RangeError before it is built when too large, #308)
|
|
56
|
+
checkAnsariExactSize(m, n);
|
|
54
57
|
const upperFrom = (q) => pansariExact(q - 1, m, n, false); // P(AB >= q)
|
|
55
58
|
const lowerTo = (q) => pansariExact(q, m, n, true); // P(AB <= q)
|
|
56
59
|
if (alternative === "two.sided") {
|
|
@@ -109,13 +112,68 @@ export function ansariTest(x, y, options = {}) {
|
|
|
109
112
|
function scaledStatistic(xs, ys, s) {
|
|
110
113
|
const m = xs.length;
|
|
111
114
|
const N = m + ys.length;
|
|
112
|
-
const
|
|
115
|
+
const q = xs.map((v) => v / s);
|
|
116
|
+
// x / s can overflow to Infinity or fall below the normal range (to 0) for a finite s, tying distinct observations
|
|
117
|
+
// (R's ansari.test does the same): only there rank by a comparison of x / s that keeps the order (#507)
|
|
118
|
+
const lossy = s > 0 && s < Infinity && q.some((v, i) => Number.isFinite(xs[i]) && (!Number.isFinite(v) || (xs[i] !== 0 && Math.abs(v) < MIN_NORMAL)));
|
|
119
|
+
const r = lossy ? orderedRanks(xs.map((v) => key(v, s)).concat(ys.map((v) => key(v, 1)))) : rankNaNLast(q.concat(ys));
|
|
113
120
|
const a = r.map((v) => Math.min(v, N - v + 1));
|
|
114
121
|
let ab = 0;
|
|
115
122
|
for (let i = 0; i < m; i++)
|
|
116
123
|
ab += a[i];
|
|
117
124
|
return { ab, a, ties: new Set(r).size < N };
|
|
118
125
|
}
|
|
126
|
+
const MIN_NORMAL = 2 ** -1022;
|
|
127
|
+
function key(v, d) {
|
|
128
|
+
if (v === 0)
|
|
129
|
+
return [0, 0, 0];
|
|
130
|
+
const sign = v > 0 ? 1 : -1;
|
|
131
|
+
if (!Number.isFinite(v))
|
|
132
|
+
return [sign, Infinity, 1];
|
|
133
|
+
const [ev, mv] = split(Math.abs(v));
|
|
134
|
+
const [ed, md] = split(d);
|
|
135
|
+
let m = mv / md;
|
|
136
|
+
let e = ev - ed;
|
|
137
|
+
if (m < 1) {
|
|
138
|
+
m *= 2;
|
|
139
|
+
e -= 1;
|
|
140
|
+
}
|
|
141
|
+
return [sign, e, m];
|
|
142
|
+
}
|
|
143
|
+
/** [e, m] with a = m 2^e, m in [1, 2), for a finite positive a */
|
|
144
|
+
function split(a) {
|
|
145
|
+
let e = Math.floor(Math.log2(a));
|
|
146
|
+
let m = ldexp(a, -e);
|
|
147
|
+
if (m >= 2) {
|
|
148
|
+
m /= 2;
|
|
149
|
+
e += 1;
|
|
150
|
+
}
|
|
151
|
+
else if (m < 1) {
|
|
152
|
+
m *= 2;
|
|
153
|
+
e -= 1;
|
|
154
|
+
}
|
|
155
|
+
return [e, m];
|
|
156
|
+
}
|
|
157
|
+
function compareKeys(a, b) {
|
|
158
|
+
if (a[0] !== b[0])
|
|
159
|
+
return a[0] - b[0];
|
|
160
|
+
const c = a[1] !== b[1] ? a[1] - b[1] : a[2] - b[2];
|
|
161
|
+
return a[0] * c;
|
|
162
|
+
}
|
|
163
|
+
/** Average ranks of the keys */
|
|
164
|
+
function orderedRanks(keys) {
|
|
165
|
+
const idx = keys.map((_, i) => i).sort((i, j) => compareKeys(keys[i], keys[j]));
|
|
166
|
+
const r = new Array(keys.length);
|
|
167
|
+
for (let lo = 0; lo < idx.length;) {
|
|
168
|
+
let hi = lo + 1;
|
|
169
|
+
while (hi < idx.length && compareKeys(keys[idx[lo]], keys[idx[hi]]) === 0)
|
|
170
|
+
hi++;
|
|
171
|
+
for (let k = lo; k < hi; k++)
|
|
172
|
+
r[idx[k]] = (lo + 1 + hi) / 2;
|
|
173
|
+
lo = hi;
|
|
174
|
+
}
|
|
175
|
+
return r;
|
|
176
|
+
}
|
|
119
177
|
/** Average ranks with NaN (0 / 0 at s = 0) ranked last in order of appearance, as R's rank(na.last = TRUE) */
|
|
120
178
|
function rankNaNLast(v) {
|
|
121
179
|
const keep = v.filter((e) => !Number.isNaN(e));
|
|
@@ -184,10 +242,14 @@ function exactInterval(xs, ys, alternative, confLevel) {
|
|
|
184
242
|
else
|
|
185
243
|
above = Math.min(above, sigma[k]);
|
|
186
244
|
});
|
|
187
|
-
|
|
245
|
+
// the midpoint as R's mean(c(u, l)); where the sum of two finite candidates overflows, from the halves (exact for
|
|
246
|
+
// them) (#209)
|
|
247
|
+
let estimate = below === -Infinity || above === Infinity ? NaN : (above + below) / 2;
|
|
248
|
+
if (estimate === Infinity)
|
|
249
|
+
estimate = above / 2 + below / 2;
|
|
188
250
|
return { confInt, estimate };
|
|
189
251
|
}
|
|
190
|
-
/** Normal-approximation interval and estimate (undefined when the search range is not finite) */
|
|
252
|
+
/** Normal-approximation interval and estimate (undefined when the search range is not finite, NaN when it is empty) */
|
|
191
253
|
function normalInterval(xs, ys, alternative, confLevel) {
|
|
192
254
|
const m = xs.length;
|
|
193
255
|
const n = ys.length;
|
|
@@ -217,14 +279,19 @@ function normalInterval(xs, ys, alternative, confLevel) {
|
|
|
217
279
|
const range = (xp, yp) => {
|
|
218
280
|
if (xp.length === 0 || yp.length === 0)
|
|
219
281
|
return;
|
|
220
|
-
ends.push(
|
|
282
|
+
ends.push(minOf(xp) / maxOf(yp), maxOf(xp) / minOf(yp));
|
|
221
283
|
};
|
|
222
284
|
range(xs.filter((v) => v > 0), ys.filter((v) => v > 0));
|
|
223
285
|
range(xs.filter((v) => v <= 0), ys.filter((v) => v < 0));
|
|
224
286
|
if (ends.some((v) => !Number.isFinite(v)))
|
|
225
287
|
return undefined;
|
|
226
|
-
|
|
227
|
-
|
|
288
|
+
// no positive ratio puts the samples across each other (all x positive and all y negative, or the reverse): the
|
|
289
|
+
// limits and the estimate cannot be formed, as in the exact path (R stops with "invalid 'xmin' value" after its
|
|
290
|
+
// "samples differ in location ... returning NA" warning) (#506)
|
|
291
|
+
if (ends.length === 0)
|
|
292
|
+
return { confInt: shapeInterval(alternative, 1 - confLevel, () => [NaN, NaN]), estimate: NaN };
|
|
293
|
+
const lo = minOf(ends);
|
|
294
|
+
const hi = maxOf(ends);
|
|
228
295
|
const root = (zq) => uniroot((s) => z(s, zq), lo, hi, { tol: 1e-4 });
|
|
229
296
|
const limits = (alpha) => {
|
|
230
297
|
const zLow = qnorm(alpha / 2);
|
package/dist/htest/aov.d.ts
CHANGED
|
@@ -59,7 +59,7 @@ export declare function aov(formula: string, data: DataFrame, options?: LmFormul
|
|
|
59
59
|
* @category Multiple comparisons
|
|
60
60
|
*/
|
|
61
61
|
export interface TukeyHSDOptions {
|
|
62
|
-
/** Family-wise confidence level. Default `0.95`. */
|
|
62
|
+
/** Family-wise confidence level in [0, 1] (a RangeError otherwise). Default `0.95`. */
|
|
63
63
|
confLevel?: number;
|
|
64
64
|
}
|
|
65
65
|
/**
|
package/dist/htest/aov.js
CHANGED
|
@@ -12,32 +12,13 @@
|
|
|
12
12
|
import { pf1 } from "../distributions/f.js";
|
|
13
13
|
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
14
14
|
import { ptukey, qtukey } from "../distributions/tukey.js";
|
|
15
|
-
import { meanDD } from "../internal/summary.js";
|
|
16
|
-
import { ddAdd, ddMul, ddSub } from "../special/dd.js";
|
|
15
|
+
import { groupMoments, ldexp, meanDD, scaleToUnit } from "../internal/summary.js";
|
|
17
16
|
import { parseFormula, splitErrorTerms } from "../models/formula.js";
|
|
18
17
|
import { aovStrataFit } from "../models/aovStrata.js";
|
|
19
18
|
import { lmFormulaFit } from "../models/lm.js";
|
|
20
19
|
import { design } from "../models/modelMatrix.js";
|
|
21
20
|
import { labelledGroups, toGroups } from "./groups.js";
|
|
22
|
-
import { matchAlternative } from "./types.js";
|
|
23
|
-
function sums(groups) {
|
|
24
|
-
const all = groups.flat();
|
|
25
|
-
const m = meanDD(all);
|
|
26
|
-
let ssb = [0, 0];
|
|
27
|
-
let ssw = [0, 0];
|
|
28
|
-
const means = [];
|
|
29
|
-
for (const g of groups) {
|
|
30
|
-
const mi = meanDD(g);
|
|
31
|
-
means.push(mi[0]);
|
|
32
|
-
const d = ddSub(mi, m);
|
|
33
|
-
ssb = ddAdd(ssb, ddMul(ddMul(d, d), [g.length, 0]));
|
|
34
|
-
for (const v of g) {
|
|
35
|
-
const e = ddSub([v, 0], mi);
|
|
36
|
-
ssw = ddAdd(ssw, ddMul(e, e));
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return { ssb: ssb[0], ssw: ssw[0], means };
|
|
40
|
-
}
|
|
21
|
+
import { checkConfLevel, matchAlternative } from "./types.js";
|
|
41
22
|
export function aov(x, g, options = {}) {
|
|
42
23
|
if (typeof x === "string")
|
|
43
24
|
return aovFormula(x, g, options);
|
|
@@ -59,16 +40,18 @@ function aovOneway(x, g) {
|
|
|
59
40
|
if (k < 2)
|
|
60
41
|
throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
|
|
61
42
|
const N = groups.reduce((a, s) => a + s.length, 0);
|
|
62
|
-
|
|
43
|
+
// sums of squares of the data scaled by 2^-k (groupMoments): F from them, the sums of squares scaled back
|
|
44
|
+
const { ssBetween: ssb, ssWithin: ssw, k: e } = groupMoments(groups);
|
|
63
45
|
const df1 = k - 1;
|
|
64
46
|
const df2 = N - k;
|
|
65
47
|
const msb = ssb / df1;
|
|
66
48
|
const msw = ssw / df2;
|
|
67
49
|
const fValue = msb / msw;
|
|
50
|
+
const back = (v) => ldexp(v, 2 * e);
|
|
68
51
|
return {
|
|
69
52
|
df: [df1, df2],
|
|
70
|
-
sumSq: [ssb, ssw],
|
|
71
|
-
meanSq: [msb, msw],
|
|
53
|
+
sumSq: [back(ssb), back(ssw)],
|
|
54
|
+
meanSq: [back(msb), back(msw)],
|
|
72
55
|
fValue,
|
|
73
56
|
pValue: df2 > 0 ? pf1(fValue, df1, df2, false, false) : NaN,
|
|
74
57
|
};
|
|
@@ -104,9 +87,19 @@ export function TukeyHSD(x, g, options = {}) {
|
|
|
104
87
|
if (k < 2)
|
|
105
88
|
throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
|
|
106
89
|
const confLevel = options.confLevel ?? 0.95;
|
|
90
|
+
// R accepts 0 and 1 (limits diff and ±Inf) but returns NaN limits outside [0, 1]: that is rejected
|
|
91
|
+
checkConfLevel(confLevel);
|
|
107
92
|
const N = groups.reduce((a, s) => a + s.length, 0);
|
|
108
93
|
const df = N - k;
|
|
109
|
-
|
|
94
|
+
// No residual variance without residual degrees of freedom (one value per group): the limits and p-values were NaN
|
|
95
|
+
// (R's too). The message is tukeyTest's (#315)
|
|
96
|
+
if (df === 0)
|
|
97
|
+
throw new RangeError("no residual degrees of freedom");
|
|
98
|
+
// ptukey and qtukey (R's too) are defined from 2 df: with 1 the limits and p-values were NaN (#315)
|
|
99
|
+
if (df < 2)
|
|
100
|
+
throw new RangeError("the studentized range needs at least 2 residual degrees of freedom");
|
|
101
|
+
// means and MSE of the data scaled by 2^-e (groupMoments): the differences and limits are scaled back
|
|
102
|
+
const { ssWithin: ssw, mean: means, k: e } = groupMoments(groups);
|
|
110
103
|
const mse = ssw / df;
|
|
111
104
|
const q = qtukey(confLevel, k, df);
|
|
112
105
|
const out = { names: [], i: [], j: [], diff: [], lwr: [], upr: [], pAdj: [] };
|
|
@@ -117,9 +110,9 @@ export function TukeyHSD(x, g, options = {}) {
|
|
|
117
110
|
out.names.push(`${names[a]}-${names[b]}`);
|
|
118
111
|
out.i.push(a + 1);
|
|
119
112
|
out.j.push(b + 1);
|
|
120
|
-
out.diff.push(diff);
|
|
121
|
-
out.lwr.push(diff - q * se);
|
|
122
|
-
out.upr.push(diff + q * se);
|
|
113
|
+
out.diff.push(ldexp(diff, e));
|
|
114
|
+
out.lwr.push(ldexp(diff - q * se, e));
|
|
115
|
+
out.upr.push(ldexp(diff + q * se, e));
|
|
123
116
|
out.pAdj.push(ptukey(Math.abs(diff) / se, k, df, { lowerTail: false }));
|
|
124
117
|
}
|
|
125
118
|
}
|
|
@@ -150,6 +143,10 @@ export function zTest(x, y, options = {}) {
|
|
|
150
143
|
if (sigmaX === undefined || (ys !== undefined && sigmaY === undefined)) {
|
|
151
144
|
throw new RangeError("sigmaX and sigmaY are both required for two samples");
|
|
152
145
|
}
|
|
146
|
+
for (const sd of [sigmaX, sigmaY]) {
|
|
147
|
+
if (sd !== undefined && !(sd > 0 && sd < Infinity))
|
|
148
|
+
throw new RangeError("sigmaX and sigmaY must be positive finite numbers");
|
|
149
|
+
}
|
|
153
150
|
if (Number.isNaN(mu))
|
|
154
151
|
throw new RangeError("mu must be a number");
|
|
155
152
|
const alternative = matchAlternative(options.alternative);
|
|
@@ -162,11 +159,16 @@ export function zTest(x, y, options = {}) {
|
|
|
162
159
|
throw new RangeError("x needs at least 3 non-missing values");
|
|
163
160
|
if (yv !== undefined && yv.length < 3)
|
|
164
161
|
throw new RangeError("y needs at least 3 non-missing values");
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const
|
|
162
|
+
// the data, the known standard deviations and mu scaled by one power of 2 (exact), so that the squared standard
|
|
163
|
+
// deviations stay in range; the estimates and interval are scaled back
|
|
164
|
+
const sc = scaleToUnit([xs, yv ?? [], [sigmaX, sigmaY ?? 0]]);
|
|
165
|
+
const k = sc.k;
|
|
166
|
+
const [xS, yS, [sxS, syS]] = sc.groups;
|
|
167
|
+
const meanX = meanDD(xS)[0];
|
|
168
|
+
const meanY = yv === undefined ? NaN : meanDD(yS)[0];
|
|
169
|
+
const se = yv === undefined ? sxS / Math.sqrt(xs.length) : Math.sqrt(sxS ** 2 / xs.length + syS ** 2 / yv.length);
|
|
168
170
|
const target = yv === undefined ? meanX : meanX - meanY;
|
|
169
|
-
const z = (target - mu) / se;
|
|
171
|
+
const z = (target - ldexp(mu, -k)) / se;
|
|
170
172
|
let pValue;
|
|
171
173
|
let confInt;
|
|
172
174
|
if (alternative === "less") {
|
|
@@ -179,10 +181,22 @@ export function zTest(x, y, options = {}) {
|
|
|
179
181
|
}
|
|
180
182
|
else {
|
|
181
183
|
pValue = 2 * pnorm(-Math.abs(z));
|
|
182
|
-
|
|
184
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
|
|
185
|
+
const a2 = (1 - confLevel) / 2;
|
|
186
|
+
const half = (a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - (1 - confLevel) / 2)) * se;
|
|
183
187
|
confInt = [target - half, target + half];
|
|
184
188
|
}
|
|
189
|
+
confInt = [ldexp(confInt[0], k), ldexp(confInt[1], k)];
|
|
185
190
|
const twoSample = yv !== undefined;
|
|
191
|
+
// The reported means. Where the common scale, set by sigma, divides a nonzero value below the normal range (#192: x
|
|
192
|
+
// around 1e-308 with sigma 1e308 gave the mean 0), the mean of that sample in its own scale instead, but never scaled
|
|
193
|
+
// up: small data are averaged as they are, so that a subnormal mean is rounded once. Elsewhere the same bits
|
|
194
|
+
const reported = (v, vS) => {
|
|
195
|
+
if (!(k > 0 && v.some((t, j) => t !== 0 && Math.abs(vS[j]) < 2 ** -1022)))
|
|
196
|
+
return ldexp(meanDD(vS)[0], k);
|
|
197
|
+
const own = Math.max(scaleToUnit([v]).k, 0);
|
|
198
|
+
return ldexp(meanDD(own === 0 ? v : v.map((t) => ldexp(t, -own)))[0], own);
|
|
199
|
+
};
|
|
186
200
|
return {
|
|
187
201
|
method: twoSample ? "Two-sample z-Test" : "One-sample z-Test",
|
|
188
202
|
alternative,
|
|
@@ -191,7 +205,7 @@ export function zTest(x, y, options = {}) {
|
|
|
191
205
|
pValue,
|
|
192
206
|
confInt,
|
|
193
207
|
confLevel,
|
|
194
|
-
estimate: twoSample ? [
|
|
208
|
+
estimate: twoSample ? [reported(xs, xS), reported(yv, yS)] : reported(xs, xS),
|
|
195
209
|
estimateNames: twoSample ? ["mean of x", "mean of y"] : "mean of x",
|
|
196
210
|
nullValue: mu,
|
|
197
211
|
nullValueName: twoSample ? "difference in means" : "mean",
|
|
@@ -44,3 +44,8 @@ export interface BinomTestResult extends HTest {
|
|
|
44
44
|
* @category Hypothesis tests
|
|
45
45
|
*/
|
|
46
46
|
export declare function binomTest(x: number | readonly [number, number], n?: number | BinomTestOptions, options?: BinomTestOptions): BinomTestResult;
|
|
47
|
+
/**
|
|
48
|
+
* The exact binomial test of xs successes in ns trials, without the check of ns > 0 (poissonTest compares two counts
|
|
49
|
+
* of 0 as R does: p-value 1, interval [0, 1])
|
|
50
|
+
*/
|
|
51
|
+
export declare function binomTestCounts(xs: number, ns: number, options?: BinomTestOptions): BinomTestResult;
|
package/dist/htest/binomTest.js
CHANGED
|
@@ -8,16 +8,29 @@
|
|
|
8
8
|
// quantiles.
|
|
9
9
|
import { dbinom1, pbinom1 } from "../distributions/binomial.js";
|
|
10
10
|
import { qbeta1 } from "../distributions/beta.js";
|
|
11
|
-
import {
|
|
11
|
+
import { firstTrue, lastTrue } from "../internal/discrete.js";
|
|
12
|
+
import { twoSum } from "../special/dd.js";
|
|
13
|
+
import { checkConfLevelOpen, isCount, matchAlternative } from "./types.js";
|
|
12
14
|
/** Relative slack when comparing outcome probabilities with the observed one */
|
|
13
15
|
const SLACK = 1 + 1e-7;
|
|
14
|
-
|
|
15
|
-
|
|
16
|
+
/**
|
|
17
|
+
* P[X >= x] under Binomial(n, p). Where x - 1 or n - (x - 1) is not exact (beyond 2^53), P[X > x] + dbinom(x):
|
|
18
|
+
* pbinom(x - 1, upper) took a rounded x - 1 or n - (x - 1) (x = 2^53, n = 2^54, p = 1/2 gave 0.5, true
|
|
19
|
+
* 0.5000000029724; issue #324)
|
|
20
|
+
*/
|
|
21
|
+
function atLeast(x, n, p) {
|
|
22
|
+
const xm = x - 1;
|
|
23
|
+
if (x === 0 || (x - xm === 1 && twoSum(n, -xm)[1] === 0))
|
|
24
|
+
return pbinom1(xm, n, p, false, false);
|
|
25
|
+
return pbinom1(x, n, p, false, false) + dbinom1(x, n, p, false);
|
|
16
26
|
}
|
|
17
27
|
/**
|
|
18
28
|
* Two-sided p-value: the total probability of the outcomes no more likely than x (within the relative slack). The
|
|
19
|
-
* observed side is one tail of the distribution function; on the opposite side the qualifying outcomes are
|
|
20
|
-
*
|
|
29
|
+
* observed side is one tail of the distribution function; on the opposite side the qualifying outcomes are the most
|
|
30
|
+
* extreme ones there, so their mass is again a tail probability. The density decreases from ceil(np) upwards and
|
|
31
|
+
* increases up to floor(np) (the ratio f(i + 1) / f(i) = (n - i) p / ((i + 1)(1 - p)) is below 1 exactly for
|
|
32
|
+
* i > (n + 1) p - 1), so the boundary of the qualifying outcomes is found by search in O(log n) evaluations instead of
|
|
33
|
+
* testing each of the outcomes on that side (which took seconds for n around 1e8).
|
|
21
34
|
*/
|
|
22
35
|
function twoSidedP(x, n, p) {
|
|
23
36
|
if (p === 0)
|
|
@@ -28,19 +41,17 @@ function twoSidedP(x, n, p) {
|
|
|
28
41
|
if (x === mean)
|
|
29
42
|
return 1;
|
|
30
43
|
const cut = dbinom1(x, n, p, false) * SLACK;
|
|
31
|
-
|
|
44
|
+
const qualifies = (i) => dbinom1(i, n, p, false) <= cut;
|
|
32
45
|
if (x < mean) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const other = count === 0 ? 0 : pbinom1(n - count, n, p, false, false);
|
|
46
|
+
// the first qualifying outcome above the mean; those from it to n qualify
|
|
47
|
+
const j = firstTrue(qualifies, Math.ceil(mean), n);
|
|
48
|
+
const other = j > n ? 0 : atLeast(j, n, p);
|
|
37
49
|
return Math.min(1, pbinom1(x, n, p, true, false) + other);
|
|
38
50
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
return Math.min(1, pbinom1(x - 1, n, p, false, false) + other);
|
|
51
|
+
// the last qualifying outcome below the mean; those from 0 to it qualify
|
|
52
|
+
const j = lastTrue(qualifies, 0, Math.floor(mean));
|
|
53
|
+
const other = j < 0 ? 0 : pbinom1(j, n, p, true, false);
|
|
54
|
+
return Math.min(1, atLeast(x, n, p) + other);
|
|
44
55
|
}
|
|
45
56
|
/**
|
|
46
57
|
* Exact test of a simple null hypothesis about the probability of success in Bernoulli trials. Equivalent to R's
|
|
@@ -70,6 +81,10 @@ export function binomTest(x, n, options = {}) {
|
|
|
70
81
|
throw new RangeError("'x' must be nonnegative and integer");
|
|
71
82
|
xs = Math.round(x[0]);
|
|
72
83
|
ns = Math.round(x[0]) + Math.round(x[1]);
|
|
84
|
+
// no trials: neither the estimate nor the test is defined (R returns a p-value of 1), as for binomTest(0, 0)
|
|
85
|
+
// no trials, or a total that overflows (binomTest([1e308, 1e308]) gave NaN; a scalar n = Infinity is rejected too)
|
|
86
|
+
if (ns === 0 || ns === Infinity)
|
|
87
|
+
throw new RangeError("'n' must be a positive integer >= 'x'");
|
|
73
88
|
}
|
|
74
89
|
else {
|
|
75
90
|
if (typeof n !== "number")
|
|
@@ -81,6 +96,13 @@ export function binomTest(x, n, options = {}) {
|
|
|
81
96
|
throw new RangeError("'n' must be a positive integer >= 'x'");
|
|
82
97
|
ns = Math.round(n);
|
|
83
98
|
}
|
|
99
|
+
return binomTestCounts(xs, ns, options);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The exact binomial test of xs successes in ns trials, without the check of ns > 0 (poissonTest compares two counts
|
|
103
|
+
* of 0 as R does: p-value 1, interval [0, 1])
|
|
104
|
+
*/
|
|
105
|
+
export function binomTestCounts(xs, ns, options = {}) {
|
|
84
106
|
const p = options.p ?? 0.5;
|
|
85
107
|
if (!(p >= 0 && p <= 1))
|
|
86
108
|
throw new RangeError("'p' must be a single number between 0 and 1");
|
|
@@ -91,11 +113,13 @@ export function binomTest(x, n, options = {}) {
|
|
|
91
113
|
if (alternative === "less")
|
|
92
114
|
pValue = pbinom1(xs, ns, p, true, false);
|
|
93
115
|
else if (alternative === "greater")
|
|
94
|
-
pValue =
|
|
116
|
+
pValue = atLeast(xs, ns, p);
|
|
95
117
|
else
|
|
96
118
|
pValue = twoSidedP(xs, ns, p);
|
|
97
119
|
const lower = (alpha) => (xs === 0 ? 0 : qbeta1(alpha, xs, ns - xs + 1, true, false));
|
|
98
|
-
|
|
120
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits, and is 1 below 1.1e-16, which gave
|
|
121
|
+
// the limit 1 at confLevel = 0.9999999999999999)
|
|
122
|
+
const upper = (alpha) => xs === ns ? 1 : alpha < 1e-8 ? qbeta1(alpha, xs + 1, ns - xs, false, false) : qbeta1(1 - alpha, xs + 1, ns - xs, true, false);
|
|
99
123
|
let confInt;
|
|
100
124
|
if (alternative === "less")
|
|
101
125
|
confInt = [0, upper(1 - confLevel)];
|
|
@@ -17,9 +17,10 @@ export interface BrunnerMunzelTestOptions {
|
|
|
17
17
|
* Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
|
|
18
18
|
* variances or shapes. Equivalent to `lawstat::brunner.munzel.test()` in R. `NaN` values are dropped.
|
|
19
19
|
*
|
|
20
|
-
* `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]).
|
|
21
|
-
* sample
|
|
22
|
-
* statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
|
|
20
|
+
* `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). Each
|
|
21
|
+
* sample needs at least 2 values (lawstat returns NaN for a sample of one). When the variance estimates are 0 (for
|
|
22
|
+
* example completely separated samples), the statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
|
|
23
|
+
* lawstat.
|
|
23
24
|
*
|
|
24
25
|
* @example
|
|
25
26
|
* ```ts
|
|
@@ -18,9 +18,10 @@ import { checkConfLevel, matchAlternative } from "./types.js";
|
|
|
18
18
|
* Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
|
|
19
19
|
* variances or shapes. Equivalent to `lawstat::brunner.munzel.test()` in R. `NaN` values are dropped.
|
|
20
20
|
*
|
|
21
|
-
* `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]).
|
|
22
|
-
* sample
|
|
23
|
-
* statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
|
|
21
|
+
* `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). Each
|
|
22
|
+
* sample needs at least 2 values (lawstat returns NaN for a sample of one). When the variance estimates are 0 (for
|
|
23
|
+
* example completely separated samples), the statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
|
|
24
|
+
* lawstat.
|
|
24
25
|
*
|
|
25
26
|
* @example
|
|
26
27
|
* ```ts
|
|
@@ -37,9 +38,10 @@ export function brunnerMunzelTest(x, y, options = {}) {
|
|
|
37
38
|
const ys = Array.from(y).filter((v) => !Number.isNaN(v));
|
|
38
39
|
const n1 = xs.length;
|
|
39
40
|
const n2 = ys.length;
|
|
40
|
-
|
|
41
|
+
// S_i^2 divides by n_i - 1 (lawstat returns NaN for a sample of one)
|
|
42
|
+
if (n1 < 2)
|
|
41
43
|
throw new RangeError("not enough 'x' observations");
|
|
42
|
-
if (n2 <
|
|
44
|
+
if (n2 < 2)
|
|
43
45
|
throw new RangeError("not enough 'y' observations");
|
|
44
46
|
const alternative = matchAlternative(options.alternative);
|
|
45
47
|
const confLevel = options.confLevel ?? 0.95;
|
|
@@ -36,7 +36,8 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
|
|
|
36
36
|
/**
|
|
37
37
|
* Standardized residuals `(O - E) / sqrt(V)`, where `V` is
|
|
38
38
|
* `E (1 - row proportion) (1 - column proportion)` for a contingency table and
|
|
39
|
-
* `n p (1 - p)` for goodness of fit.
|
|
39
|
+
* `n p (1 - p)` for goodness of fit. For a contingency table the complements are the other rows' and columns'
|
|
40
|
+
* sums over the total, and the residual and `V` are computed in double-double.
|
|
40
41
|
*/
|
|
41
42
|
stdres: number[] | number[][];
|
|
42
43
|
}
|