@numero-uno-jpn/rstats 0.16.0 → 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 +128 -0
- package/README.ja.md +44 -18
- package/README.md +45 -18
- package/dist/chunks/chunk-2C33MXSW.js +3 -0
- package/dist/chunks/chunk-34S5SQY6.js +2 -0
- package/dist/chunks/{chunk-URIO5LY5.js → chunk-4WE3OO62.js} +2 -2
- 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-QNNL7AZ3.js → chunk-H3WVPZDL.js} +2 -2
- 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-FLJNSXSW.js → chunk-NSYZTS26.js} +2 -2
- package/dist/chunks/chunk-ONY5CISH.js +2 -0
- package/dist/chunks/chunk-RFE7MVP7.js +2 -0
- package/dist/chunks/{chunk-W26LRYOJ.js → chunk-SE7V2KLO.js} +1 -1
- 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-5UQCRBAG.js → chunk-Z37NELOS.js} +1 -1
- package/dist/chunks/chunk-ZFQWB222.js +2 -0
- package/dist/data/grouping.js +6 -2
- package/dist/descriptive/basic.js +20 -0
- package/dist/descriptive/cov.js +11 -0
- package/dist/descriptive/dataFrames.js +13 -5
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +10 -2
- package/dist/descriptive/hist.js +6 -0
- package/dist/descriptive/moments.js +14 -0
- package/dist/descriptive/omega.js +8 -3
- package/dist/descriptive/pivot.d.ts +4 -1
- package/dist/descriptive/pivot.js +27 -13
- package/dist/descriptive/quantile.js +8 -0
- package/dist/descriptive/rank.js +4 -0
- package/dist/descriptive/table.d.ts +20 -1
- package/dist/descriptive/table.js +14 -14
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +8 -0
- package/dist/distributions/beta.js +9 -0
- package/dist/distributions/binomial.js +9 -0
- package/dist/distributions/cauchy.js +9 -0
- package/dist/distributions/chisq.js +9 -0
- package/dist/distributions/exponential.js +9 -0
- package/dist/distributions/f.js +9 -0
- package/dist/distributions/gamma.js +8 -0
- package/dist/distributions/geometric.js +9 -0
- package/dist/distributions/hypergeometric.js +8 -0
- package/dist/distributions/invgamma.js +8 -0
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +9 -0
- package/dist/distributions/logistic.js +9 -0
- package/dist/distributions/lognormal.js +8 -0
- package/dist/distributions/multinomial.js +4 -0
- package/dist/distributions/negbinomial.js +8 -0
- package/dist/distributions/normal.js +8 -0
- package/dist/distributions/pareto.js +8 -0
- package/dist/distributions/poisson.js +9 -0
- package/dist/distributions/signrank.js +9 -0
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +31 -1
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +9 -0
- package/dist/distributions/tukey.js +6 -0
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +8 -0
- package/dist/distributions/wilcox.js +9 -0
- 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 +13 -0
- package/dist/htest/agreement.js +46 -7
- package/dist/htest/ansariTest.d.ts +2 -1
- package/dist/htest/ansariTest.js +43 -12
- package/dist/htest/aov.d.ts +28 -22
- package/dist/htest/aov.js +42 -13
- package/dist/htest/binomTest.js +6 -0
- package/dist/htest/brunnerMunzelTest.js +5 -0
- package/dist/htest/chisqTest.d.ts +3 -1
- package/dist/htest/chisqTest.js +21 -3
- package/dist/htest/cor.d.ts +7 -1
- package/dist/htest/cor.js +40 -7
- package/dist/htest/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/effectSize.d.ts +3 -0
- package/dist/htest/effectSize.js +28 -8
- package/dist/htest/fisherTest.d.ts +2 -1
- package/dist/htest/fisherTest.js +52 -6
- package/dist/htest/ksTest.d.ts +4 -0
- package/dist/htest/ksTest.js +13 -4
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +9 -3
- package/dist/htest/mantelhaenTest.js +7 -0
- package/dist/htest/mcnemarTest.js +8 -0
- package/dist/htest/multipleComparisons.d.ts +16 -25
- package/dist/htest/multipleComparisons.js +26 -43
- package/dist/htest/normalityTests.js +10 -4
- package/dist/htest/onewayTest.js +10 -0
- package/dist/htest/pAdjust.js +4 -0
- package/dist/htest/pairwise.d.ts +2 -0
- package/dist/htest/pairwise.js +29 -6
- package/dist/htest/poissonTest.js +6 -0
- package/dist/htest/polycor.js +20 -10
- package/dist/htest/power.d.ts +4 -0
- package/dist/htest/power.js +16 -2
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +23 -2
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +38 -15
- package/dist/htest/rankTests.js +7 -1
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +9 -0
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +21 -1
- package/dist/htest/trendTests.js +13 -18
- package/dist/htest/types.d.ts +2 -0
- package/dist/htest/varTest.js +7 -0
- package/dist/htest/wilcoxTest.js +51 -9
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- package/dist/internal/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- package/dist/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.js +7 -0
- package/dist/linalg/chol.js +6 -0
- package/dist/linalg/eigen.js +4 -0
- package/dist/linalg/expm.js +4 -0
- package/dist/linalg/kappa.js +6 -0
- package/dist/linalg/lu.js +5 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +14 -13
- package/dist/linalg/qr.js +14 -0
- package/dist/linalg/solve.js +9 -0
- package/dist/linalg/svd.js +6 -2
- 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 +50 -7
- package/dist/models/aovEz.js +16 -11
- package/dist/models/aovStrata.js +15 -4
- package/dist/models/carAnova.js +11 -17
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +21 -6
- package/dist/models/glm.d.ts +22 -2
- package/dist/models/glm.js +32 -22
- package/dist/models/glmAnova.js +8 -3
- package/dist/models/glmConfint.js +6 -2
- package/dist/models/glmFamily.d.ts +1 -6
- package/dist/models/glmFamily.js +3 -22
- package/dist/models/lm.js +13 -3
- package/dist/models/lmer.d.ts +11 -6
- package/dist/models/lmer.js +20 -15
- package/dist/models/lmerAnova.d.ts +3 -3
- package/dist/models/lmerAnova.js +10 -5
- package/dist/models/lmerTest.d.ts +4 -4
- package/dist/models/lmerTest.js +19 -11
- package/dist/models/mauchly.d.ts +2 -0
- package/dist/models/mauchly.js +7 -2
- package/dist/models/modelFrame.js +2 -2
- package/dist/models/modelMatrix.js +7 -2
- package/dist/models/survival.d.ts +6 -0
- package/dist/models/survival.js +9 -2
- package/dist/numerics/deriv.js +8 -0
- package/dist/numerics/integrate.js +8 -0
- package/dist/numerics/interp.d.ts +32 -7
- package/dist/numerics/interp.js +27 -9
- package/dist/numerics/ode.js +4 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/optim.js +17 -2
- package/dist/random/beta.js +5 -0
- package/dist/random/continuous.js +17 -0
- package/dist/random/extra.js +13 -0
- package/dist/random/gamma.js +11 -0
- package/dist/random/poisson.js +5 -0
- package/dist/random/rng.js +4 -0
- package/dist/random/sample.js +6 -0
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.js +7 -0
- package/dist/special/choose.js +7 -0
- package/dist/special/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -11
- package/llms.txt +5 -2
- package/package.json +19 -10
- package/dist/chunks/chunk-2D2IQWUQ.js +0 -2
- package/dist/chunks/chunk-6CSTWA5E.js +0 -2
- package/dist/chunks/chunk-72Y3HZID.js +0 -2
- package/dist/chunks/chunk-BG2KLEHM.js +0 -2
- package/dist/chunks/chunk-CMEKBNHQ.js +0 -2
- package/dist/chunks/chunk-GM53LWSR.js +0 -2
- package/dist/chunks/chunk-JBCA56ZS.js +0 -3
- package/dist/chunks/chunk-K3RJAD2T.js +0 -2
- package/dist/chunks/chunk-KAZRWIB5.js +0 -2
- package/dist/chunks/chunk-KBVVIMXX.js +0 -3
- package/dist/chunks/chunk-N3SIFCZX.js +0 -2
- package/dist/chunks/chunk-SC6CV4Z3.js +0 -2
- package/dist/chunks/chunk-SYWOBOTR.js +0 -2
- package/dist/chunks/chunk-VTUGG2SV.js +0 -2
- package/dist/chunks/chunk-XHETEYVC.js +0 -2
- package/dist/chunks/chunk-YRZWONZB.js +0 -3
- package/dist/chunks/chunk-ZGABZMWX.js +0 -2
|
@@ -78,7 +78,9 @@ export type Factor = readonly (string | null | undefined)[];
|
|
|
78
78
|
* Given two factor vectors (arrays of labels of the same length), tests independence in their contingency table, as
|
|
79
79
|
* R's `chisq.test(x, y)`; pairs with a missing label are dropped and the levels are sorted by code point.
|
|
80
80
|
*
|
|
81
|
-
* R
|
|
81
|
+
* As R, `warnings` has "Chi-squared approximation may be incorrect" where an expected count is below 5 (unless the
|
|
82
|
+
* p-value is simulated), and "cannot compute simulated p-value with zero marginals" where `simulatePValue` is asked for
|
|
83
|
+
* a table with a zero row or column sum (the ordinary test is done).
|
|
82
84
|
*
|
|
83
85
|
* @param x Counts, or a contingency table as an array of rows (or a factor, with `y`).
|
|
84
86
|
* @param options See {@link ChisqTestOptions}.
|
package/dist/htest/chisqTest.js
CHANGED
|
@@ -15,7 +15,10 @@
|
|
|
15
15
|
// observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) one at a time (the uniforms of
|
|
16
16
|
// R's sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
|
|
17
17
|
// (src/random/r2dtable.ts). The statistic is then the uncorrected one, and the parameter is NaN (R's NA). Tables
|
|
18
|
-
// with a zero margin are not simulated (ordinary test), as in R
|
|
18
|
+
// with a zero margin are not simulated (ordinary test), as in R, with R's warning "cannot compute simulated p-value
|
|
19
|
+
// with zero marginals"
|
|
20
|
+
// - R's warning "Chi-squared approximation may be incorrect" where an expected count is below 5 and the p-value is
|
|
21
|
+
// not simulated
|
|
19
22
|
// - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
|
|
20
23
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
21
24
|
import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
|
|
@@ -24,6 +27,11 @@ import { ldexp, productOver, squareOver } from "../internal/summary.js";
|
|
|
24
27
|
import { compareCodePoints } from "../models/modelFrame.js";
|
|
25
28
|
import { ddAdd, ddDiv, ddMul, ddSub } from "../special/dd.js";
|
|
26
29
|
import { simulatedMethod } from "./core/simulate.js";
|
|
30
|
+
import { reported } from "../internal/warnings.js";
|
|
31
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
32
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
33
|
+
import { isOptionsObject } from "../internal/optionalArgs.js";
|
|
34
|
+
const CHISQ_TEST_KEYS = ["correct", "p", "rescaleP", "simulatePValue", "B"];
|
|
27
35
|
/** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
|
|
28
36
|
function ddSum(x) {
|
|
29
37
|
let s = [0, 0];
|
|
@@ -35,10 +43,15 @@ function ddSum(x) {
|
|
|
35
43
|
return Number.isFinite(plain) ? s[0] : plain;
|
|
36
44
|
}
|
|
37
45
|
export function chisqTest(x, yOrOptions, maybeOptions) {
|
|
46
|
+
if (isOptionsObject(yOrOptions))
|
|
47
|
+
checkOptions(yOrOptions, CHISQ_TEST_KEYS, "chisqTest"); // generated: option-keys.mjs
|
|
48
|
+
checkOptions(maybeOptions, CHISQ_TEST_KEYS, "chisqTest"); // generated: option-keys.mjs
|
|
38
49
|
if (Array.isArray(yOrOptions))
|
|
39
|
-
return chisqFactors(x, yOrOptions, maybeOptions ?? {});
|
|
40
|
-
return chisqCounts(x, yOrOptions ?? {});
|
|
50
|
+
return reported("chisqTest", chisqFactors(x, yOrOptions, maybeOptions ?? {}));
|
|
51
|
+
return reported("chisqTest", chisqCounts(x, yOrOptions ?? {}));
|
|
41
52
|
}
|
|
53
|
+
/** R's warning where an expected count is below 5 and the p-value is not simulated */
|
|
54
|
+
const APPROXIMATION = "Chi-squared approximation may be incorrect";
|
|
42
55
|
function chisqFactors(x, y, options) {
|
|
43
56
|
if (x.length !== y.length)
|
|
44
57
|
throw new RangeError("'x' and 'y' must have the same length");
|
|
@@ -181,6 +194,7 @@ function goodnessOfFit(x, options) {
|
|
|
181
194
|
expected: E,
|
|
182
195
|
residuals: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Es[i]), s / 2)),
|
|
183
196
|
stdres: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Vs[i]), s / 2)),
|
|
197
|
+
warnings: Number.isFinite(df) && E.some((e) => e < 5) ? [APPROXIMATION] : [],
|
|
184
198
|
};
|
|
185
199
|
}
|
|
186
200
|
/**
|
|
@@ -253,6 +267,9 @@ function contingency(x, options) {
|
|
|
253
267
|
let pValue;
|
|
254
268
|
const simulate = (options.simulatePValue ?? false) && sr.every((v) => v > 0) && sc.every((v) => v > 0);
|
|
255
269
|
const yates = !simulate && correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
|
|
270
|
+
const warnings = [];
|
|
271
|
+
if ((options.simulatePValue ?? false) && !simulate)
|
|
272
|
+
warnings.push("cannot compute simulated p-value with zero marginals");
|
|
256
273
|
if (simulate) {
|
|
257
274
|
// counts are integers for the simulation: the simulated tables have integer margins, and fractional observed
|
|
258
275
|
// counts would be compared with them (R truncates the margins and runs it)
|
|
@@ -283,6 +300,7 @@ function contingency(x, options) {
|
|
|
283
300
|
expected: E,
|
|
284
301
|
residuals: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j]))),
|
|
285
302
|
stdres: contingencyStdres(x, n, sr, sc, E, diff),
|
|
303
|
+
warnings: Number.isFinite(df) && E.some((r) => r.some((e) => e < 5)) ? [...warnings, APPROXIMATION] : warnings,
|
|
286
304
|
};
|
|
287
305
|
}
|
|
288
306
|
/**
|
package/dist/htest/cor.d.ts
CHANGED
|
@@ -8,7 +8,8 @@ import { type Alternative, type HTest, type Sample } from "./types.js";
|
|
|
8
8
|
*/
|
|
9
9
|
export type CorMethod = "pearson" | "kendall" | "spearman";
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
11
|
+
* The base of {@link CorTestOptions}: the options {@link corTest} shares with the coefficient. The options of the
|
|
12
|
+
* exported `cor` (descriptive statistics) are {@link CovOptions}.
|
|
12
13
|
*
|
|
13
14
|
* @category Hypothesis tests
|
|
14
15
|
*/
|
|
@@ -92,6 +93,11 @@ export declare function kendall(x: readonly number[], y: readonly number[]): Ken
|
|
|
92
93
|
* arithmetic, so results can differ from R's when r is very close to ±1, where R's own
|
|
93
94
|
* value is less accurate.
|
|
94
95
|
*
|
|
96
|
+
* As R, `warnings` has "the standard deviation is zero" where x or y is constant (the correlation is `NaN`), and
|
|
97
|
+
* "Cannot compute exact p-value with ties" where Kendall's or Spearman's exact p-value is asked for or the default
|
|
98
|
+
* but there are ties (the approximation is used), and "NaNs produced" where Spearman's t approximation has 2 pairs
|
|
99
|
+
* (0 degrees of freedom: the p-value is `NaN`).
|
|
100
|
+
*
|
|
95
101
|
* @param x First sample.
|
|
96
102
|
* @param y Second sample, of the same length as `x`.
|
|
97
103
|
* @param options See {@link CorTestOptions}.
|
package/dist/htest/cor.js
CHANGED
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
// replaces rho with (rho + 6 / (n^3 - n)) / (1 + 6 / (n^3 - n)) (regardless of sign or alternative; R's behaviour)
|
|
20
20
|
// - When the correlation is undefined (constant data), the statistic, p-value, estimate and interval are NaN. Kendall's
|
|
21
21
|
// statistic is then always named "T"
|
|
22
|
+
// - R's warnings: "the standard deviation is zero" where the correlation is NaN because x or y is constant (R's cor;
|
|
23
|
+
// for Pearson finite values, as R, whose sd of an infinite constant is NaN), and "Cannot compute exact p-value with
|
|
24
|
+
// ties" where the exact p-value is asked for or the default (Kendall n < 50; Spearman always, as R's exact = TRUE)
|
|
25
|
+
// but there are ties, and "NaNs produced" of R's pt with 0 degrees of freedom (Spearman's t approximation, n = 2)
|
|
22
26
|
// - confLevel is validated only for Pearson. The interval is only reported with 4 or more pairs
|
|
23
27
|
// More accurate than R: the correlation coefficient, 1 - r^2 and the continuity-corrected rho are computed in double-double.
|
|
24
28
|
// R's cor is off by about 1e-10 for data with a large mean (1e8 + small spread), and does not give 1 even for perfect correlation (1 - 2 ulp).
|
|
@@ -28,7 +32,11 @@ import { pnorm, qnorm } from "../distributions/normal.js";
|
|
|
28
32
|
import { ddAdd, ddDiv, ddMul, ddSub, twoProd, twoSum } from "../special/dd.js";
|
|
29
33
|
import { centered, completePairs, rank, tieCounts } from "../internal/summary.js";
|
|
30
34
|
import { correlationData } from "./testFormula.js";
|
|
35
|
+
import { reported } from "../internal/warnings.js";
|
|
31
36
|
import { checkConfLevel, matchAlternative } from "./types.js";
|
|
37
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
38
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
39
|
+
const COR_TEST_KEYS = ["alternative", "exact", "confLevel", "continuity", "method"];
|
|
32
40
|
const METHODS = ["pearson", "kendall", "spearman"];
|
|
33
41
|
function matchMethod(m) {
|
|
34
42
|
if (m === undefined)
|
|
@@ -275,6 +283,7 @@ function spearmanTail(n, q, lower) {
|
|
|
275
283
|
return spearmanEdgeworth(n, q, false);
|
|
276
284
|
}
|
|
277
285
|
export function corTest(x, y, options = {}) {
|
|
286
|
+
checkOptions(options, COR_TEST_KEYS, "corTest"); // generated: option-keys.mjs
|
|
278
287
|
if (typeof x === "string") {
|
|
279
288
|
const d = correlationData(x, y);
|
|
280
289
|
return corTest(d.x, d.y, options);
|
|
@@ -310,6 +319,7 @@ function corTestSamples(x, y, options) {
|
|
|
310
319
|
estimateNames: "cor",
|
|
311
320
|
nullValue: 0,
|
|
312
321
|
nullValueName: "correlation",
|
|
322
|
+
warnings: Number.isNaN(r[0]) && (finiteConstant(xs) || finiteConstant(ys)) ? [SD_ZERO] : [],
|
|
313
323
|
};
|
|
314
324
|
if (n > 3) {
|
|
315
325
|
const z = atanhDD(r);
|
|
@@ -331,7 +341,7 @@ function corTestSamples(x, y, options) {
|
|
|
331
341
|
result.confInt = ci;
|
|
332
342
|
result.confLevel = confLevel;
|
|
333
343
|
}
|
|
334
|
-
return result;
|
|
344
|
+
return reported("corTest", result);
|
|
335
345
|
}
|
|
336
346
|
if (n < 2)
|
|
337
347
|
throw new Error("not enough finite observations");
|
|
@@ -344,9 +354,11 @@ function corTestSamples(x, y, options) {
|
|
|
344
354
|
estimateNames: "tau",
|
|
345
355
|
nullValue: 0,
|
|
346
356
|
nullValueName: "tau",
|
|
357
|
+
warnings: [],
|
|
347
358
|
};
|
|
359
|
+
// tau is NaN only where x or y is constant (n >= 2)
|
|
348
360
|
if (Number.isNaN(k.tau))
|
|
349
|
-
return { ...base, statistic: NaN, statisticName: "T", pValue: NaN };
|
|
361
|
+
return reported("corTest", { ...base, statistic: NaN, statisticName: "T", pValue: NaN, warnings: [SD_ZERO] });
|
|
350
362
|
const exact = options.exact ?? n < 50;
|
|
351
363
|
if (exact && !k.ties) {
|
|
352
364
|
// the two runs of kendallCdf below take n (q + 1) + n (total - q + 1) steps, about n^3 / 2: limited to n <= 1290
|
|
@@ -360,7 +372,7 @@ function corTestSamples(x, y, options) {
|
|
|
360
372
|
const lowerP = kendallCdf(n, q);
|
|
361
373
|
const upperP = kendallCdf(n, total - q);
|
|
362
374
|
const p = alternative === "less" ? lowerP : alternative === "greater" ? upperP : Math.min(1, 2 * Math.min(lowerP, upperP));
|
|
363
|
-
return { ...base, statistic: q, statisticName: "T", pValue: p };
|
|
375
|
+
return reported("corTest", { ...base, statistic: q, statisticName: "T", pValue: p });
|
|
364
376
|
}
|
|
365
377
|
// Normal approximation (tie-corrected variance)
|
|
366
378
|
const v = (f, ts) => ts.reduce((a, t) => a + f(t), 0);
|
|
@@ -374,7 +386,9 @@ function corTestSamples(x, y, options) {
|
|
|
374
386
|
(v(a2, k.tx) * v(a2, k.ty)) / (2 * n * (n - 1));
|
|
375
387
|
const s = continuity ? Math.sign(k.s) * (Math.abs(k.s) - 1) : k.s;
|
|
376
388
|
const z = s / Math.sqrt(varS);
|
|
377
|
-
|
|
389
|
+
if (exact)
|
|
390
|
+
base.warnings = [TIES];
|
|
391
|
+
return reported("corTest", { ...base, statistic: z, statisticName: "z", pValue: pFromZ(z, alternative) });
|
|
378
392
|
}
|
|
379
393
|
// spearman
|
|
380
394
|
const rx = rank(xs);
|
|
@@ -391,10 +405,15 @@ function corTestSamples(x, y, options) {
|
|
|
391
405
|
estimateNames: "rho",
|
|
392
406
|
nullValue: 0,
|
|
393
407
|
nullValueName: "rho",
|
|
408
|
+
warnings: [],
|
|
394
409
|
};
|
|
410
|
+
// rho is NaN only where the ranks of x or y are constant (n >= 2)
|
|
395
411
|
if (Number.isNaN(rho[0]))
|
|
396
|
-
return { ...base, pValue: NaN };
|
|
412
|
+
return reported("corTest", { ...base, pValue: NaN, warnings: [SD_ZERO] });
|
|
397
413
|
const ties = tieCounts(xs).length > 0 || tieCounts(ys).length > 0;
|
|
414
|
+
// R's exact is TRUE by default for Spearman, whatever n (above 1290 its pspearman takes the t approximation)
|
|
415
|
+
if (ties && (options.exact ?? true))
|
|
416
|
+
base.warnings = [TIES];
|
|
398
417
|
const exact = options.exact ?? n <= 1290;
|
|
399
418
|
if (exact && !ties && n <= 1290) {
|
|
400
419
|
const q = Math.round(S);
|
|
@@ -402,7 +421,7 @@ function corTestSamples(x, y, options) {
|
|
|
402
421
|
const upperP = spearmanTail(n, q, false);
|
|
403
422
|
// Smaller S means positive correlation
|
|
404
423
|
const p = alternative === "greater" ? lowerP : alternative === "less" ? upperP : Math.min(1, 2 * Math.min(lowerP, upperP));
|
|
405
|
-
return { ...base, pValue: p };
|
|
424
|
+
return reported("corTest", { ...base, pValue: p });
|
|
406
425
|
}
|
|
407
426
|
// t approximation. The continuity-corrected rho is also in double-double (1 - rho^2 cancels when rho is near ±1)
|
|
408
427
|
let r = rho;
|
|
@@ -413,5 +432,19 @@ function corTestSamples(x, y, options) {
|
|
|
413
432
|
r = [Math.sign(r[0]), 0];
|
|
414
433
|
}
|
|
415
434
|
const t = tFromR(r, n - 2);
|
|
416
|
-
|
|
435
|
+
// n = 2: R's pt with 0 degrees of freedom gives NaN with its warning (R's rho of the two ranks is ±(1 - 2^-52), so
|
|
436
|
+
// its t is finite)
|
|
437
|
+
if (n === 2)
|
|
438
|
+
base.warnings = [...base.warnings, NANS];
|
|
439
|
+
return reported("corTest", { ...base, pValue: pFromT(t, n - 2, alternative) });
|
|
440
|
+
}
|
|
441
|
+
/** R's warning of cor where x or y is constant */
|
|
442
|
+
const SD_ZERO = "the standard deviation is zero";
|
|
443
|
+
/** R's warning of pt where the p-value is NaN (Spearman's t approximation with n = 2) */
|
|
444
|
+
const NANS = "NaNs produced";
|
|
445
|
+
/** R's warning where the exact p-value cannot be used because of ties */
|
|
446
|
+
const TIES = "Cannot compute exact p-value with ties";
|
|
447
|
+
/** Whether all values are equal and finite */
|
|
448
|
+
function finiteConstant(v) {
|
|
449
|
+
return Number.isFinite(v[0]) && v.every((a) => a === v[0]);
|
|
417
450
|
}
|
|
@@ -2,3 +2,9 @@
|
|
|
2
2
|
export declare function simulatedMethod(B: number): string;
|
|
3
3
|
/** A number as R's as.character prints it (15 significant digits, fixed or scientific, whichever is narrower) */
|
|
4
4
|
export declare function formatR(v: number): string;
|
|
5
|
+
/**
|
|
6
|
+
* A number as R's format() prints it with `digits` significant digits (default 7, R's option): the fewest significant
|
|
7
|
+
* digits, at most `digits`, that show the number rounded to `digits`, in fixed notation unless the scientific one is
|
|
8
|
+
* narrower (R's scipen = 0)
|
|
9
|
+
*/
|
|
10
|
+
export declare function formatDigits(v: number, digits?: number): string;
|
|
@@ -14,3 +14,23 @@ export function formatR(v) {
|
|
|
14
14
|
const fixed = String(Number(v.toPrecision(15)));
|
|
15
15
|
return fixed.length <= sciStr.length ? fixed : sciStr;
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* A number as R's format() prints it with `digits` significant digits (default 7, R's option): the fewest significant
|
|
19
|
+
* digits, at most `digits`, that show the number rounded to `digits`, in fixed notation unless the scientific one is
|
|
20
|
+
* narrower (R's scipen = 0)
|
|
21
|
+
*/
|
|
22
|
+
export function formatDigits(v, digits = 7) {
|
|
23
|
+
if (!Number.isFinite(v))
|
|
24
|
+
return Number.isNaN(v) ? "NaN" : v > 0 ? "Inf" : "-Inf";
|
|
25
|
+
if (v === 0)
|
|
26
|
+
return "0";
|
|
27
|
+
const [mant, exp] = v.toExponential(digits - 1).split("e");
|
|
28
|
+
const m = mant.includes(".") ? mant.replace(/0+$/, "").replace(/\.$/, "") : mant;
|
|
29
|
+
const e = Number(exp);
|
|
30
|
+
const sig = m.replace(/^-/, "").replace(".", "").length;
|
|
31
|
+
const sciStr = `${m}e${e < 0 ? "-" : "+"}${String(Math.abs(e)).padStart(2, "0")}`;
|
|
32
|
+
// digits right of the point in fixed notation
|
|
33
|
+
const right = Math.max(0, sig - 1 - e);
|
|
34
|
+
const fixedWidth = (v < 0 ? 1 : 0) + (e >= 0 ? e + 1 : 1) + (right > 0 ? right + 1 : 0);
|
|
35
|
+
return fixedWidth > sciStr.length ? sciStr : v.toFixed(right);
|
|
36
|
+
}
|
|
@@ -48,6 +48,9 @@ export declare function hedgesJ(df: number): number;
|
|
|
48
48
|
* samples, or of one sample against `mu`, with a confidence interval from the noncentral t distribution.
|
|
49
49
|
* Equivalent to `effectsize::cohens_d()` in R.
|
|
50
50
|
*
|
|
51
|
+
* As effectsize, `warnings` has "'y' is numeric but has only 2 unique values. ..." where `y` has exactly 2 distinct
|
|
52
|
+
* values (a grouping variable is given as two samples here) and "Missing values detected. NAs dropped." for `NaN`.
|
|
53
|
+
*
|
|
51
54
|
* @example
|
|
52
55
|
* ```ts
|
|
53
56
|
* cohensD([5.1, 4.9, 6.2, 5.8], [4.1, 4.5, 3.9, 5.0]).value; // 2.049693834034246
|
package/dist/htest/effectSize.js
CHANGED
|
@@ -14,12 +14,22 @@ import { scaledTables } from "../models/scaledTables.js";
|
|
|
14
14
|
import { unirootCore as uniroot } from "../numerics/integrate.js";
|
|
15
15
|
import { lgammaDiff } from "../special/lgammaDiff.js";
|
|
16
16
|
import { matchChoice } from "./power.js";
|
|
17
|
+
import { reported, unreported } from "../internal/warnings.js";
|
|
18
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
19
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
20
|
+
const COHENS_D_KEYS = ["pooledSd", "mu", "paired", "ci", "alternative", "adjust"];
|
|
21
|
+
const HEDGES_G_KEYS = ["pooledSd", "mu", "paired", "ci", "alternative"];
|
|
22
|
+
const ETA_SQUARED_KEYS = ["generalized", "partial", "ci", "alternative"];
|
|
23
|
+
const OMEGA_SQUARED_KEYS = ["partial", "ci", "alternative"];
|
|
24
|
+
const EPSILON_SQUARED_KEYS = ["partial", "ci", "alternative"];
|
|
17
25
|
/** The confidence level of an interval, null for none: as effectsize, strictly between 0 and 1 */
|
|
18
26
|
function checkCi(ci) {
|
|
19
27
|
if (ci !== null && !(ci > 0 && ci < 1))
|
|
20
28
|
throw new RangeError("ci must be a single numeric value between (0, 1)");
|
|
21
29
|
}
|
|
22
30
|
const NA_WARNING = "Missing values detected. NAs dropped.";
|
|
31
|
+
/** effectsize's warning where y has exactly 2 distinct values (not counting NA), as a grouping variable would */
|
|
32
|
+
const TWO_VALUES_WARNING = "'y' is numeric but has only 2 unique values.\n If this is a grouping variable, convert it to a factor.";
|
|
23
33
|
/** Brent's method run until the bracket is as narrow as doubles allow */
|
|
24
34
|
const EXACT = { tol: 0, maxiter: 5000 };
|
|
25
35
|
/** Hedges' correction J(df) = Γ(df/2) / (sqrt(df/2) Γ((df − 1)/2)) (exported for the tests) */
|
|
@@ -47,6 +57,8 @@ function standardizedDifference(x, y, options, adjust) {
|
|
|
47
57
|
const xs = Array.from(x);
|
|
48
58
|
const ys = y === undefined ? undefined : Array.from(y);
|
|
49
59
|
const warnings = [];
|
|
60
|
+
if (ys !== undefined && new Set(dropNaN(ys)).size === 2)
|
|
61
|
+
warnings.push(TWO_VALUES_WARNING);
|
|
50
62
|
if (xs.some(Number.isNaN) || (ys?.some(Number.isNaN) ?? false))
|
|
51
63
|
warnings.push(NA_WARNING);
|
|
52
64
|
// (an infinite value, or too few observations, ended in the root search of the interval: "lower < upper is not
|
|
@@ -123,6 +135,9 @@ function standardizedDifference(x, y, options, adjust) {
|
|
|
123
135
|
* samples, or of one sample against `mu`, with a confidence interval from the noncentral t distribution.
|
|
124
136
|
* Equivalent to `effectsize::cohens_d()` in R.
|
|
125
137
|
*
|
|
138
|
+
* As effectsize, `warnings` has "'y' is numeric but has only 2 unique values. ..." where `y` has exactly 2 distinct
|
|
139
|
+
* values (a grouping variable is given as two samples here) and "Missing values detected. NAs dropped." for `NaN`.
|
|
140
|
+
*
|
|
126
141
|
* @example
|
|
127
142
|
* ```ts
|
|
128
143
|
* cohensD([5.1, 4.9, 6.2, 5.8], [4.1, 4.5, 3.9, 5.0]).value; // 2.049693834034246
|
|
@@ -131,7 +146,8 @@ function standardizedDifference(x, y, options, adjust) {
|
|
|
131
146
|
* @category Effect sizes and power
|
|
132
147
|
*/
|
|
133
148
|
export function cohensD(x, y, options = {}) {
|
|
134
|
-
|
|
149
|
+
checkOptions(options, COHENS_D_KEYS, "cohensD"); // generated: option-keys.mjs
|
|
150
|
+
return reported("cohensD", standardizedDifference(x, y, options, options.adjust ?? false));
|
|
135
151
|
}
|
|
136
152
|
/**
|
|
137
153
|
* Hedges' g: Cohen's d and its interval multiplied by the small-sample correction J(df). Equivalent to
|
|
@@ -145,7 +161,8 @@ export function cohensD(x, y, options = {}) {
|
|
|
145
161
|
* @category Effect sizes and power
|
|
146
162
|
*/
|
|
147
163
|
export function hedgesG(x, y, options = {}) {
|
|
148
|
-
|
|
164
|
+
checkOptions(options, HEDGES_G_KEYS, "hedgesG"); // generated: option-keys.mjs
|
|
165
|
+
return reported("hedgesG", standardizedDifference(x, y, options, true));
|
|
149
166
|
}
|
|
150
167
|
const isFit = (m) => Array.isArray(m.effects);
|
|
151
168
|
const isStrataFit = (m) => m.multistratum === true;
|
|
@@ -243,7 +260,7 @@ function observedTerms(gen, terms) {
|
|
|
243
260
|
const observed = Array.isArray(gen) ? gen : [];
|
|
244
261
|
const missing = observed.filter((o) => !terms.some((t) => word(o).test(t.name)));
|
|
245
262
|
if (missing.length > 0)
|
|
246
|
-
throw new
|
|
263
|
+
throw new RangeError(`Observed variable not in data: ${missing.join(", ")}`);
|
|
247
264
|
const isObserved = (name) => observed.some((o) => word(o).test(name));
|
|
248
265
|
return { isObserved, ssObserved: terms.reduce((a, t) => (isObserved(t.name) ? a + t.ss : a), 0) };
|
|
249
266
|
}
|
|
@@ -292,7 +309,7 @@ function anovaEffectSize(model, kind, options) {
|
|
|
292
309
|
throw new TypeError(NEEDS);
|
|
293
310
|
if (isStrataFit(model) || isStrataSummary(model) || isEz(model))
|
|
294
311
|
return strataEffectSize(model, kind, options);
|
|
295
|
-
const given = isFit(model) ? anova(model) : model;
|
|
312
|
+
const given = isFit(model) ? unreported(() => anova(model)) : model;
|
|
296
313
|
if (!Array.isArray(given.colNames) || !Array.isArray(given.table))
|
|
297
314
|
throw new TypeError(NEEDS);
|
|
298
315
|
// the sums of squares as fitted where the table has them (those returned can overflow: scaledTables.ts)
|
|
@@ -368,7 +385,7 @@ function strataEffectSize(model, kind, options) {
|
|
|
368
385
|
rows = s.order.map((term) => ({ term, stratum: s.strata.find((st) => st.terms.includes(term)) }));
|
|
369
386
|
}
|
|
370
387
|
else {
|
|
371
|
-
const summary = isStrataFit(model) ? aovSummary(model) : model;
|
|
388
|
+
const summary = isStrataFit(model) ? unreported(() => aovSummary(model)) : model;
|
|
372
389
|
const sc = scaledTables.get(summary);
|
|
373
390
|
({ strata, subject } = summaryStrata(Array.isArray(sc) ? { ...summary, strata: sc.map((t, i) => ({ ...summary.strata[i], ...t })) } : summary));
|
|
374
391
|
rows = strata.flatMap((stratum) => stratum.terms.map((term) => ({ term, stratum })));
|
|
@@ -446,7 +463,8 @@ function strataEffectSize(model, kind, options) {
|
|
|
446
463
|
* @category Effect sizes and power
|
|
447
464
|
*/
|
|
448
465
|
export function etaSquared(model, options = {}) {
|
|
449
|
-
|
|
466
|
+
checkOptions(options, ETA_SQUARED_KEYS, "etaSquared"); // generated: option-keys.mjs
|
|
467
|
+
return reported("etaSquared", anovaEffectSize(model, "Eta2", options), model);
|
|
450
468
|
}
|
|
451
469
|
/**
|
|
452
470
|
* Omega squared of the terms of an analysis-of-variance table, also of repeated-measures designs (see
|
|
@@ -461,7 +479,8 @@ export function etaSquared(model, options = {}) {
|
|
|
461
479
|
* @category Effect sizes and power
|
|
462
480
|
*/
|
|
463
481
|
export function omegaSquared(model, options = {}) {
|
|
464
|
-
|
|
482
|
+
checkOptions(options, OMEGA_SQUARED_KEYS, "omegaSquared"); // generated: option-keys.mjs
|
|
483
|
+
return reported("omegaSquared", anovaEffectSize(model, "Omega2", options), model);
|
|
465
484
|
}
|
|
466
485
|
/**
|
|
467
486
|
* Epsilon squared of the terms of an analysis-of-variance table, also of repeated-measures designs (see
|
|
@@ -476,5 +495,6 @@ export function omegaSquared(model, options = {}) {
|
|
|
476
495
|
* @category Effect sizes and power
|
|
477
496
|
*/
|
|
478
497
|
export function epsilonSquared(model, options = {}) {
|
|
479
|
-
|
|
498
|
+
checkOptions(options, EPSILON_SQUARED_KEYS, "epsilonSquared"); // generated: option-keys.mjs
|
|
499
|
+
return reported("epsilonSquared", anovaEffectSize(model, "Epsilon2", options), model);
|
|
480
500
|
}
|
|
@@ -43,7 +43,8 @@ export interface FisherTestResult extends Omit<HTest, "statistic" | "statisticNa
|
|
|
43
43
|
* reproducing R's numbers (including R's root-finding tolerance). The two-sided p-value
|
|
44
44
|
* sums the probabilities of tables no more likely than the observed one (relative
|
|
45
45
|
* tolerance `1e-7`, as in R). Non-integer counts are rounded to the nearest integer
|
|
46
|
-
* (ties to even),
|
|
46
|
+
* (ties to even), with R's warning ("'x' has been rounded to integer: Mean relative difference: 0.0625", the text of
|
|
47
|
+
* R's `all.equal` of the counts and the rounded counts; none where they differ by less than about 1.5e-8).
|
|
47
48
|
*
|
|
48
49
|
* With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
|
|
49
50
|
* observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
|
package/dist/htest/fisherTest.js
CHANGED
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
// values here are the roots (review 58)
|
|
14
14
|
// - The two-sided p-value is the sum of probabilities of tables whose probability is at most (1 + 1e-7) times the
|
|
15
15
|
// observed one (R's convention); for or = 0 or Inf the distribution is a point mass at the end of the support
|
|
16
|
-
// - Counts are made integer by rounding half to even
|
|
16
|
+
// - Counts are made integer by rounding half to even, with R's warning "'x' has been rounded to integer: " and the text
|
|
17
|
+
// of all.equal(original, rounded) (allEqualMessage)
|
|
17
18
|
// The same distribution and root conventions are used for the exact Mantel-Haenszel test (src/htest/core/mantelhaen.ts).
|
|
18
19
|
//
|
|
19
20
|
// rxc tables: the probabilities of tables with fixed margins (multivariate hypergeometric) are
|
|
@@ -38,9 +39,13 @@ import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.j
|
|
|
38
39
|
import { lfactorial } from "../special/choose.js";
|
|
39
40
|
import { logScaleRoot } from "../internal/uniroot.js";
|
|
40
41
|
import { ddAdd, ddLog, ddNeg, ddSub } from "../special/dd.js";
|
|
41
|
-
import { simulatedMethod } from "./core/simulate.js";
|
|
42
|
+
import { formatDigits, simulatedMethod } from "./core/simulate.js";
|
|
43
|
+
import { reported } from "../internal/warnings.js";
|
|
42
44
|
import { matchAlternative } from "./types.js";
|
|
43
45
|
import { maxOf, minOf } from "../internal/extremes.js";
|
|
46
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
47
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
48
|
+
const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulatePValue", "B"];
|
|
44
49
|
/**
|
|
45
50
|
* Fisher's exact test for count data. Equivalent to R's `fisher.test()`.
|
|
46
51
|
*
|
|
@@ -49,7 +54,8 @@ import { maxOf, minOf } from "../internal/extremes.js";
|
|
|
49
54
|
* reproducing R's numbers (including R's root-finding tolerance). The two-sided p-value
|
|
50
55
|
* sums the probabilities of tables no more likely than the observed one (relative
|
|
51
56
|
* tolerance `1e-7`, as in R). Non-integer counts are rounded to the nearest integer
|
|
52
|
-
* (ties to even),
|
|
57
|
+
* (ties to even), with R's warning ("'x' has been rounded to integer: Mean relative difference: 0.0625", the text of
|
|
58
|
+
* R's `all.equal` of the counts and the rounded counts; none where they differ by less than about 1.5e-8).
|
|
53
59
|
*
|
|
54
60
|
* With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
|
|
55
61
|
* observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
|
|
@@ -71,6 +77,7 @@ import { maxOf, minOf } from "../internal/extremes.js";
|
|
|
71
77
|
* @category Hypothesis tests
|
|
72
78
|
*/
|
|
73
79
|
export function fisherTest(x, options = {}) {
|
|
80
|
+
checkOptions(options, FISHER_TEST_KEYS, "fisherTest"); // generated: option-keys.mjs
|
|
74
81
|
const nr = x.length;
|
|
75
82
|
const nc = nr === 0 ? 0 : x[0].length;
|
|
76
83
|
if (x.some((r) => r.length !== nc))
|
|
@@ -87,9 +94,13 @@ export function fisherTest(x, options = {}) {
|
|
|
87
94
|
// as in R, counts beyond the largest integer (2^31 - 1) are rejected (the 2 x 2 support would also be huge)
|
|
88
95
|
if (t.flat().some((v) => v > 2147483647))
|
|
89
96
|
throw new RangeError("'x' has entries too large to be integer");
|
|
97
|
+
const warnings = [];
|
|
98
|
+
const rounding = allEqualMessage(raw, t);
|
|
99
|
+
if (rounding !== null)
|
|
100
|
+
warnings.push(`'x' has been rounded to integer: ${rounding}`);
|
|
90
101
|
const method = "Fisher's Exact Test for Count Data";
|
|
91
102
|
if (nr === 2 && nc === 2)
|
|
92
|
-
return fisher2x2(t, options, method);
|
|
103
|
+
return reported("fisherTest", { ...fisher2x2(t, options, method), warnings });
|
|
93
104
|
// For rxc, alternative etc. are not validated and are returned as given (as in R)
|
|
94
105
|
const alternative = (options.alternative ?? "two.sided");
|
|
95
106
|
if (options.simulatePValue ?? false) {
|
|
@@ -98,9 +109,43 @@ export function fisherTest(x, options = {}) {
|
|
|
98
109
|
// nothing (R's p = (1 + 0) / (0 + 1) = 1): an error too (#488)
|
|
99
110
|
if (!(Number.isInteger(B) && B >= 1 && B < 2 ** 31))
|
|
100
111
|
throw new RangeError("'B' must be a positive integer");
|
|
101
|
-
return { method: method + simulatedMethod(B), alternative, pValue: fisherSimulated(t, B) };
|
|
112
|
+
return reported("fisherTest", { method: method + simulatedMethod(B), alternative, pValue: fisherSimulated(t, B), warnings });
|
|
102
113
|
}
|
|
103
|
-
return { method, alternative, pValue: fisherRxC(t) };
|
|
114
|
+
return reported("fisherTest", { method, alternative, pValue: fisherRxC(t), warnings });
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The text of R's `all.equal(target, current)` for two numeric matrices of the same shape with no NA, or null where
|
|
118
|
+
* it is TRUE: "Mean relative difference: <format(err)>", the mean absolute difference over the entries that differ
|
|
119
|
+
* divided by the mean absolute target over them ("absolute" with no division where that mean is at most the
|
|
120
|
+
* tolerance sqrt(eps) or not finite), when it exceeds the tolerance. The entries are taken in R's (column) order.
|
|
121
|
+
*/
|
|
122
|
+
function allEqualMessage(target, current) {
|
|
123
|
+
const tolerance = Math.sqrt(Number.EPSILON);
|
|
124
|
+
const t = [];
|
|
125
|
+
const c = [];
|
|
126
|
+
for (let j = 0; j < target[0].length; j++) {
|
|
127
|
+
for (let i = 0; i < target.length; i++) {
|
|
128
|
+
if (target[i][j] !== current[i][j]) {
|
|
129
|
+
t.push(target[i][j]);
|
|
130
|
+
c.push(current[i][j]);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const n = t.length;
|
|
135
|
+
if (n === 0)
|
|
136
|
+
return null;
|
|
137
|
+
let scale = 0;
|
|
138
|
+
for (const v of t)
|
|
139
|
+
scale += Math.abs(v) / n;
|
|
140
|
+
let what = "relative";
|
|
141
|
+
if (!(Number.isFinite(scale) && scale > tolerance)) {
|
|
142
|
+
scale = 1;
|
|
143
|
+
what = "absolute";
|
|
144
|
+
}
|
|
145
|
+
let xy = 0;
|
|
146
|
+
for (let k = 0; k < n; k++)
|
|
147
|
+
xy += Math.abs(t[k] - c[k]) / (n * scale);
|
|
148
|
+
return Number.isNaN(xy) || xy > tolerance ? `Mean ${what} difference: ${formatDigits(xy)}` : null;
|
|
104
149
|
}
|
|
105
150
|
/** Monte Carlo p-value of an r x c table: tables with fixed margins drawn by Patefield's algorithm */
|
|
106
151
|
function fisherSimulated(t, B) {
|
|
@@ -297,6 +342,7 @@ function fisher2x2(t, options, method) {
|
|
|
297
342
|
estimateNames: "odds ratio",
|
|
298
343
|
nullValue: or,
|
|
299
344
|
nullValueName: "odds ratio",
|
|
345
|
+
warnings: [],
|
|
300
346
|
};
|
|
301
347
|
if (!(options.confInt ?? true))
|
|
302
348
|
return result;
|
package/dist/htest/ksTest.d.ts
CHANGED
|
@@ -35,6 +35,10 @@ export interface KsTestResult extends Omit<HTest, "alternative"> {
|
|
|
35
35
|
* Kolmogorov-Smirnov test. Equivalent to R's `ks.test()`. Takes a distribution function given as a function (for
|
|
36
36
|
* example `(q) => pnorm(q)`) or a second sample. `NaN` values are dropped.
|
|
37
37
|
*
|
|
38
|
+
* As R, `warnings` has "ties should not be present for the one-sample Kolmogorov-Smirnov test" for one sample with
|
|
39
|
+
* ties, and "p-value will be approximate in the presence of ties" for two samples with ties and `exact: false` (or
|
|
40
|
+
* m n >= 10000).
|
|
41
|
+
*
|
|
38
42
|
* @param x Sample.
|
|
39
43
|
* @param y A continuous distribution function, or a second sample.
|
|
40
44
|
* @param options See {@link KsTestOptions}.
|
package/dist/htest/ksTest.js
CHANGED
|
@@ -6,10 +6,16 @@
|
|
|
6
6
|
// Kolmogorov's limit and exp(-2 n D^2). Two samples: the largest differences of the empirical distribution functions,
|
|
7
7
|
// taken only where the pooled sorted values change; exact p-values (by default for m n < 10000, with or without ties)
|
|
8
8
|
// by counting lattice paths, asymptotic ones as for one sample with n replaced by m n / (m + n).
|
|
9
|
+
// R's warnings: "ties should not be present for the one-sample Kolmogorov-Smirnov test" for one sample with ties, and
|
|
10
|
+
// "p-value will be approximate in the presence of ties" for two samples with ties and the asymptotic p-value.
|
|
9
11
|
import { checkKolmogorovExactSize, pkolmogorovExact, pkolmogorovExactUpper, pkolmogorovLimit, pkolmogorovOneSidedUpper, } from "./core/kolmogorov.js";
|
|
10
12
|
import { psmirnovUpper } from "./core/smirnov.js";
|
|
11
13
|
import { twoGroupData } from "./testFormula.js";
|
|
12
14
|
import { matchAlternative } from "./types.js";
|
|
15
|
+
import { reported } from "../internal/warnings.js";
|
|
16
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
17
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
18
|
+
const KS_TEST_KEYS = ["alternative", "exact"];
|
|
13
19
|
function describe(alternative, oneSample) {
|
|
14
20
|
if (alternative === "two.sided")
|
|
15
21
|
return "two-sided";
|
|
@@ -17,6 +23,7 @@ function describe(alternative, oneSample) {
|
|
|
17
23
|
return `the CDF of x lies ${where} ${oneSample ? "the null hypothesis" : "that of y"}`;
|
|
18
24
|
}
|
|
19
25
|
export function ksTest(x, y, options = {}) {
|
|
26
|
+
checkOptions(options, KS_TEST_KEYS, "ksTest"); // generated: option-keys.mjs
|
|
20
27
|
if (typeof x === "string") {
|
|
21
28
|
const d = twoGroupData(x, y);
|
|
22
29
|
return ksTest(d.x, d.y, options);
|
|
@@ -68,14 +75,15 @@ export function ksTest(x, y, options = {}) {
|
|
|
68
75
|
else {
|
|
69
76
|
pValue = exact ? pkolmogorovOneSidedUpper(n, statistic) : Math.exp(-2 * n * statistic * statistic);
|
|
70
77
|
}
|
|
71
|
-
return {
|
|
78
|
+
return reported("ksTest", {
|
|
72
79
|
method: `${exact ? "Exact" : "Asymptotic"} one-sample Kolmogorov-Smirnov test`,
|
|
73
80
|
alternative: describe(alternative, true),
|
|
74
81
|
exact,
|
|
75
82
|
statistic,
|
|
76
83
|
statisticName,
|
|
77
84
|
pValue: Math.min(1, Math.max(0, pValue)),
|
|
78
|
-
|
|
85
|
+
warnings: ties ? ["ties should not be present for the one-sample Kolmogorov-Smirnov test"] : [],
|
|
86
|
+
});
|
|
79
87
|
}
|
|
80
88
|
const ys = Array.from(y).filter((v) => !Number.isNaN(v));
|
|
81
89
|
const m = ys.length;
|
|
@@ -113,12 +121,13 @@ export function ksTest(x, y, options = {}) {
|
|
|
113
121
|
? pkolmogorovLimit(Math.sqrt(en) * statistic, false)
|
|
114
122
|
: Math.exp(-2 * en * statistic * statistic);
|
|
115
123
|
}
|
|
116
|
-
return {
|
|
124
|
+
return reported("ksTest", {
|
|
117
125
|
method: `${exact ? "Exact" : "Asymptotic"} two-sample Kolmogorov-Smirnov test`,
|
|
118
126
|
alternative: describe(alternative, false),
|
|
119
127
|
exact,
|
|
120
128
|
statistic,
|
|
121
129
|
statisticName,
|
|
122
130
|
pValue: Math.min(1, Math.max(0, pValue)),
|
|
123
|
-
|
|
131
|
+
warnings: ties && !exact ? ["p-value will be approximate in the presence of ties"] : [],
|
|
132
|
+
});
|
|
124
133
|
}
|
|
@@ -21,6 +21,8 @@ export interface LeveneTestResult {
|
|
|
21
21
|
rowNames: string[];
|
|
22
22
|
/** One array per row; NaN where car prints nothing. */
|
|
23
23
|
table: number[][];
|
|
24
|
+
/** R's warnings, each once, in R's order (an empty array when there are none). */
|
|
25
|
+
warnings: string[];
|
|
24
26
|
}
|
|
25
27
|
/**
|
|
26
28
|
* Levene's test for homogeneity of variance across groups. Equivalent to `car::leveneTest()` in R. Computes
|
package/dist/htest/leveneTest.js
CHANGED
|
@@ -4,9 +4,13 @@
|
|
|
4
4
|
//
|
|
5
5
|
// Written for rStats.js from oracle/rm-tests-behaviour.md (no ported code; car's source was not read).
|
|
6
6
|
import { ldexp, mean, scaleToUnit } from "../internal/summary.js";
|
|
7
|
-
import {
|
|
8
|
-
import { labelledGroups, median } from "./groups.js";
|
|
7
|
+
import { onewayTable } from "./aov.js";
|
|
8
|
+
import { labelledGroups, median, toGroups } from "./groups.js";
|
|
9
9
|
import { matchChoice } from "./power.js";
|
|
10
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
11
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
12
|
+
const LEVENE_TEST_KEYS = ["center"];
|
|
13
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
10
14
|
const MIN_NORMAL = 2 ** -1022;
|
|
11
15
|
/**
|
|
12
16
|
* Levene's test for homogeneity of variance across groups. Equivalent to `car::leveneTest()` in R. Computes
|
|
@@ -25,6 +29,7 @@ const MIN_NORMAL = 2 ** -1022;
|
|
|
25
29
|
* @category Hypothesis tests
|
|
26
30
|
*/
|
|
27
31
|
export function leveneTest(y, g, options = {}) {
|
|
32
|
+
checkOptions(options, LEVENE_TEST_KEYS, "leveneTest"); // generated: option-keys.mjs
|
|
28
33
|
const center = matchChoice(options.center ?? "median", ["median", "mean"]);
|
|
29
34
|
const { groups } = labelledGroups(y, g);
|
|
30
35
|
if (groups.length < 2)
|
|
@@ -48,7 +53,7 @@ export function leveneTest(y, g, options = {}) {
|
|
|
48
53
|
const e = Number.isFinite(top) ? top : 0;
|
|
49
54
|
deviations = own.map((o) => o.d.map((v) => ldexp(v, o.k - e)));
|
|
50
55
|
}
|
|
51
|
-
const r =
|
|
56
|
+
const r = onewayTable(toGroups(deviations));
|
|
52
57
|
return {
|
|
53
58
|
colNames: ["Df", "F value", "Pr(>F)"],
|
|
54
59
|
rowNames: ["group", ""],
|
|
@@ -56,5 +61,6 @@ export function leveneTest(y, g, options = {}) {
|
|
|
56
61
|
[r.df[0], r.fValue, r.pValue],
|
|
57
62
|
[r.df[1], NaN, NaN],
|
|
58
63
|
],
|
|
64
|
+
warnings: [],
|
|
59
65
|
};
|
|
60
66
|
}
|