@numero-uno-jpn/rstats 0.5.0 → 0.7.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 +125 -0
- package/README.ja.md +36 -20
- package/README.md +34 -18
- package/THIRD_PARTY_NOTICES.md +25 -5
- package/dist/chunks/chunk-6R7YDHA2.js +2 -0
- package/dist/chunks/chunk-AFKYWGKN.js +2 -0
- package/dist/chunks/chunk-ANYGLFT4.js +2 -0
- package/dist/chunks/chunk-BI5RSUZ2.js +2 -0
- package/dist/chunks/chunk-J3SNI7KY.js +2 -0
- package/dist/chunks/chunk-JCZAB6C5.js +2 -0
- package/dist/chunks/chunk-MVG5LUZU.js +2 -0
- package/dist/chunks/chunk-PTPPP4TI.js +2 -0
- package/dist/chunks/chunk-QNQJA6KZ.js +2 -0
- package/dist/chunks/chunk-SXSJXDD3.js +2 -0
- package/dist/chunks/chunk-UIOAWLAN.js +2 -0
- package/dist/chunks/chunk-XYXHHF5L.js +2 -0
- package/dist/chunks/chunk-YKN6OGJL.js +2 -0
- package/dist/chunks/chunk-ZW52Z3GY.js +2 -0
- package/dist/chunks/chunk-ZYA4ISAT.js +2 -0
- package/dist/descriptive/basic.d.ts +73 -0
- package/dist/descriptive/basic.js +256 -0
- package/dist/descriptive/cov.d.ts +39 -0
- package/dist/descriptive/cov.js +105 -0
- package/dist/descriptive/hist.d.ts +64 -0
- package/dist/descriptive/hist.js +304 -0
- package/dist/descriptive/moments.d.ts +63 -0
- package/dist/descriptive/moments.js +158 -0
- package/dist/descriptive/quantile.d.ts +50 -0
- package/dist/descriptive/quantile.js +131 -0
- package/dist/descriptive/rank.d.ts +23 -0
- package/dist/descriptive/rank.js +72 -0
- package/dist/descriptive/table.d.ts +54 -0
- package/dist/descriptive/table.js +160 -0
- package/dist/descriptive.js +2 -0
- package/dist/distributions/arcsine.d.ts +24 -0
- package/dist/distributions/arcsine.js +73 -0
- package/dist/distributions/invgamma.d.ts +29 -0
- package/dist/distributions/invgamma.js +85 -0
- package/dist/distributions/kumaraswamy.d.ts +17 -0
- package/dist/distributions/kumaraswamy.js +96 -0
- package/dist/distributions/laplace.d.ts +23 -0
- package/dist/distributions/laplace.js +69 -0
- package/dist/distributions/multinomial.d.ts +24 -0
- package/dist/distributions/multinomial.js +70 -0
- package/dist/distributions/nbeta.js +28 -10
- package/dist/distributions/nchisq.js +20 -3
- package/dist/distributions/pareto.d.ts +23 -0
- package/dist/distributions/pareto.js +76 -0
- package/dist/distributions/summary.d.ts +25 -0
- package/dist/distributions/summary.js +289 -0
- package/dist/distributions/triangular.d.ts +25 -0
- package/dist/distributions/triangular.js +87 -0
- package/dist/distributions.js +2 -0
- package/dist/entries/descriptive.d.ts +7 -0
- package/dist/entries/descriptive.js +8 -0
- package/dist/entries/distributions.d.ts +42 -0
- package/dist/entries/distributions.js +42 -0
- package/dist/entries/linalg.d.ts +11 -0
- package/dist/entries/linalg.js +11 -0
- package/dist/entries/numerics.d.ts +8 -0
- package/dist/entries/numerics.js +6 -0
- package/dist/entries/special.d.ts +10 -0
- package/dist/entries/special.js +10 -0
- package/dist/entries/tests.d.ts +21 -0
- package/dist/entries/tests.js +20 -0
- package/dist/htest/ansariTest.d.ts +30 -0
- package/dist/htest/ansariTest.js +253 -0
- package/dist/htest/aov.d.ts +85 -0
- package/dist/htest/aov.js +178 -0
- package/dist/htest/binomTest.d.ts +36 -0
- package/dist/htest/binomTest.js +121 -0
- package/dist/htest/chisqTest.d.ts +34 -2
- package/dist/htest/chisqTest.js +140 -37
- package/dist/htest/cor.d.ts +14 -0
- package/dist/htest/cor.js +4 -3
- package/dist/htest/core/ansari.d.ts +25 -0
- package/dist/htest/core/ansari.js +186 -0
- package/dist/htest/core/kolmogorov.d.ts +26 -0
- package/dist/htest/core/kolmogorov.js +221 -0
- package/dist/htest/core/mantelhaen.d.ts +26 -0
- package/dist/htest/core/mantelhaen.js +145 -0
- package/dist/htest/core/shapiro.d.ts +24 -0
- package/dist/htest/core/shapiro.js +142 -0
- package/dist/htest/core/simulate.d.ts +2 -0
- package/dist/htest/core/simulate.js +16 -0
- package/dist/htest/core/smirnov.d.ts +20 -0
- package/dist/htest/core/smirnov.js +75 -0
- package/dist/htest/fisherTest.d.ts +12 -1
- package/dist/htest/fisherTest.js +187 -127
- package/dist/htest/groups.d.ts +20 -0
- package/dist/htest/groups.js +62 -0
- package/dist/htest/ksTest.d.ts +31 -0
- package/dist/htest/ksTest.js +106 -0
- package/dist/htest/mantelhaenTest.d.ts +26 -0
- package/dist/htest/mantelhaenTest.js +196 -0
- package/dist/htest/mcnemarTest.d.ts +26 -0
- package/dist/htest/mcnemarTest.js +99 -0
- package/dist/htest/onewayTest.d.ts +26 -0
- package/dist/htest/onewayTest.js +97 -0
- package/dist/htest/pairwise.d.ts +64 -0
- package/dist/htest/pairwise.js +152 -0
- package/dist/htest/poissonTest.d.ts +35 -0
- package/dist/htest/poissonTest.js +170 -0
- package/dist/htest/propTest.d.ts +37 -0
- package/dist/htest/propTest.js +164 -0
- package/dist/htest/rankTests.d.ts +52 -0
- package/dist/htest/rankTests.js +234 -0
- package/dist/htest/types.d.ts +2 -0
- package/dist/htest/types.js +6 -0
- package/dist/htest/varTest.d.ts +48 -0
- package/dist/htest/varTest.js +118 -0
- package/dist/htest/wilcoxTest.js +136 -174
- package/dist/index.d.ts +6 -50
- package/dist/index.js +8 -50
- package/dist/integrate/quadpack.d.ts +29 -0
- package/dist/integrate/quadpack.js +525 -0
- package/dist/internal/seq.d.ts +5 -0
- package/dist/internal/seq.js +14 -0
- package/dist/internal/uniroot.js +10 -71
- package/dist/linalg/lu.d.ts +45 -0
- package/dist/linalg/lu.js +88 -0
- package/dist/linalg/ops.d.ts +90 -0
- package/dist/linalg/ops.js +320 -0
- package/dist/linalg.js +2 -0
- package/dist/models/lm.d.ts +98 -0
- package/dist/models/lm.js +187 -0
- package/dist/numerics/deriv.d.ts +37 -0
- package/dist/numerics/deriv.js +150 -0
- package/dist/numerics/integrate.d.ts +91 -0
- package/dist/numerics/integrate.js +264 -0
- package/dist/numerics/interp.d.ts +103 -0
- package/dist/numerics/interp.js +581 -0
- package/dist/numerics/ode.d.ts +23 -0
- package/dist/numerics/ode.js +59 -0
- package/dist/numerics.js +2 -0
- package/dist/optim/localmin.d.ts +16 -0
- package/dist/optim/localmin.js +97 -0
- package/dist/random/beta.js +1 -1
- package/dist/random/binomial.js +1 -1
- package/dist/random/continuous.js +1 -1
- package/dist/random/extra.d.ts +33 -0
- package/dist/random/extra.js +62 -0
- package/dist/random/gamma.js +1 -1
- package/dist/random/hyper.js +1 -1
- package/dist/random/mt.js +0 -1
- package/dist/random/poisson.js +0 -1
- package/dist/random/r2dtable.d.ts +26 -0
- package/dist/random/r2dtable.js +153 -0
- package/dist/random/rank.js +1 -1
- package/dist/random/rng.js +1 -1
- package/dist/random/sample.js +1 -1
- package/dist/rstats.js +3 -2
- package/dist/special/besselIK.d.ts +38 -0
- package/dist/special/besselIK.js +315 -0
- package/dist/special/besselJY.d.ts +32 -0
- package/dist/special/besselJY.js +508 -0
- package/dist/special/besselSeries.d.ts +8 -0
- package/dist/special/besselSeries.js +24 -0
- package/dist/special/beta.js +22 -5
- package/dist/special/choose.d.ts +75 -0
- package/dist/special/choose.js +233 -0
- package/dist/special/erf.d.ts +28 -2
- package/dist/special/erf.js +37 -10
- package/dist/special/extra.d.ts +47 -0
- package/dist/special/extra.js +220 -0
- package/dist/special/igam.d.ts +4 -0
- package/dist/special/igam.js +57 -2
- package/dist/special/incbet.js +77 -22
- package/dist/special/lgammaDiff.d.ts +7 -0
- package/dist/special/lgammaDiff.js +16 -3
- package/dist/special/log1p.d.ts +53 -0
- package/dist/special/log1p.js +93 -0
- package/dist/special/psigamma.d.ts +48 -0
- package/dist/special/psigamma.js +318 -0
- package/dist/special/rCompatible.d.ts +8 -0
- package/dist/special/rCompatible.js +1 -0
- package/dist/special.js +2 -0
- package/dist/tests.js +3 -0
- package/package.json +26 -1
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type Alternative, type HTest } from "./types.js";
|
|
2
|
+
/** Options for {@link binomTest}. */
|
|
3
|
+
export interface BinomTestOptions {
|
|
4
|
+
/** Hypothesized probability of success. Default `0.5`. */
|
|
5
|
+
p?: number;
|
|
6
|
+
/** Alternative hypothesis (unambiguous abbreviations accepted). Default `"two.sided"`. */
|
|
7
|
+
alternative?: Alternative | "two" | "l" | "g";
|
|
8
|
+
/** Confidence level of the interval. Default `0.95`. */
|
|
9
|
+
confLevel?: number;
|
|
10
|
+
}
|
|
11
|
+
/** Result of {@link binomTest}. */
|
|
12
|
+
export interface BinomTestResult extends HTest {
|
|
13
|
+
/** Number of trials (`parameterName` is `"number of trials"`). */
|
|
14
|
+
parameter: number;
|
|
15
|
+
/** Clopper-Pearson interval for the probability of success. */
|
|
16
|
+
confInt: [number, number];
|
|
17
|
+
confLevel: number;
|
|
18
|
+
/** Observed proportion of successes. */
|
|
19
|
+
estimate: number;
|
|
20
|
+
nullValue: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Exact test of a simple null hypothesis about the probability of success in Bernoulli trials. Equivalent to R's
|
|
24
|
+
* `binom.test()`.
|
|
25
|
+
*
|
|
26
|
+
* @param x Number of successes, or `[successes, failures]`.
|
|
27
|
+
* @param n Number of trials (ignored when `x` has two elements; may then be omitted and the options passed in its
|
|
28
|
+
* place).
|
|
29
|
+
* @param options See {@link BinomTestOptions}.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* binomTest(682, 925, { p: 0.75 }).pValue; // 0.3824916
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export declare function binomTest(x: number | readonly [number, number], n?: number | BinomTestOptions, options?: BinomTestOptions): BinomTestResult;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Exact binomial test (R's binom.test).
|
|
2
|
+
//
|
|
3
|
+
// Written for rStats.js from the textbook construction and R's documented behaviour. The two-sided p-value adds the
|
|
4
|
+
// probabilities of all outcomes no more likely than the observed one, with a relative slack of 1e-7 on that
|
|
5
|
+
// comparison so that outcomes of equal probability are not split by rounding (R's convention). The observed side is
|
|
6
|
+
// taken as a tail of the distribution function and the opposite side as the tail made of the outcomes that pass the
|
|
7
|
+
// comparison (counted one by one). The confidence interval is Clopper and Pearson's (Biometrika 26, 1934), from beta
|
|
8
|
+
// quantiles.
|
|
9
|
+
import { dbinom1, pbinom1 } from "../distributions/binomial.js";
|
|
10
|
+
import { qbeta1 } from "../distributions/beta.js";
|
|
11
|
+
import { checkConfLevelOpen, matchAlternative } from "./types.js";
|
|
12
|
+
/** Relative slack when comparing outcome probabilities with the observed one */
|
|
13
|
+
const SLACK = 1 + 1e-7;
|
|
14
|
+
function isCount(v) {
|
|
15
|
+
return Number.isFinite(v) && v >= 0 && Math.abs(v - Math.round(v)) <= 1e-7 * Math.max(1, Math.abs(v));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* 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 counted,
|
|
20
|
+
* and as they are the most extreme ones there, their mass is again a tail probability.
|
|
21
|
+
*/
|
|
22
|
+
function twoSidedP(x, n, p) {
|
|
23
|
+
if (p === 0)
|
|
24
|
+
return x === 0 ? 1 : 0;
|
|
25
|
+
if (p === 1)
|
|
26
|
+
return x === n ? 1 : 0;
|
|
27
|
+
const mean = n * p;
|
|
28
|
+
if (x === mean)
|
|
29
|
+
return 1;
|
|
30
|
+
const cut = dbinom1(x, n, p, false) * SLACK;
|
|
31
|
+
let count = 0;
|
|
32
|
+
if (x < mean) {
|
|
33
|
+
for (let i = Math.ceil(mean); i <= n; i++)
|
|
34
|
+
if (dbinom1(i, n, p, false) <= cut)
|
|
35
|
+
count++;
|
|
36
|
+
const other = count === 0 ? 0 : pbinom1(n - count, n, p, false, false);
|
|
37
|
+
return Math.min(1, pbinom1(x, n, p, true, false) + other);
|
|
38
|
+
}
|
|
39
|
+
for (let i = 0; i <= Math.floor(mean); i++)
|
|
40
|
+
if (dbinom1(i, n, p, false) <= cut)
|
|
41
|
+
count++;
|
|
42
|
+
const other = count === 0 ? 0 : pbinom1(count - 1, n, p, true, false);
|
|
43
|
+
return Math.min(1, pbinom1(x - 1, n, p, false, false) + other);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Exact test of a simple null hypothesis about the probability of success in Bernoulli trials. Equivalent to R's
|
|
47
|
+
* `binom.test()`.
|
|
48
|
+
*
|
|
49
|
+
* @param x Number of successes, or `[successes, failures]`.
|
|
50
|
+
* @param n Number of trials (ignored when `x` has two elements; may then be omitted and the options passed in its
|
|
51
|
+
* place).
|
|
52
|
+
* @param options See {@link BinomTestOptions}.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* binomTest(682, 925, { p: 0.75 }).pValue; // 0.3824916
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export function binomTest(x, n, options = {}) {
|
|
60
|
+
let xs;
|
|
61
|
+
let ns;
|
|
62
|
+
if (typeof x !== "number") {
|
|
63
|
+
if (x.length !== 2)
|
|
64
|
+
throw new RangeError("incorrect length of 'x'");
|
|
65
|
+
if (n !== undefined && typeof n !== "number")
|
|
66
|
+
options = n;
|
|
67
|
+
if (!isCount(x[0]) || !isCount(x[1]))
|
|
68
|
+
throw new RangeError("'x' must be nonnegative and integer");
|
|
69
|
+
xs = Math.round(x[0]);
|
|
70
|
+
ns = Math.round(x[0]) + Math.round(x[1]);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
if (typeof n !== "number")
|
|
74
|
+
throw new TypeError("'n' is required when 'x' is a single number");
|
|
75
|
+
if (!isCount(x))
|
|
76
|
+
throw new RangeError("'x' must be nonnegative and integer");
|
|
77
|
+
xs = Math.round(x);
|
|
78
|
+
if (!(isCount(n) && Math.round(n) >= xs && n > 0))
|
|
79
|
+
throw new RangeError("'n' must be a positive integer >= 'x'");
|
|
80
|
+
ns = Math.round(n);
|
|
81
|
+
}
|
|
82
|
+
const p = options.p ?? 0.5;
|
|
83
|
+
if (!(p >= 0 && p <= 1))
|
|
84
|
+
throw new RangeError("'p' must be a single number between 0 and 1");
|
|
85
|
+
const alternative = matchAlternative(options.alternative);
|
|
86
|
+
const confLevel = options.confLevel ?? 0.95;
|
|
87
|
+
checkConfLevelOpen(confLevel);
|
|
88
|
+
let pValue;
|
|
89
|
+
if (alternative === "less")
|
|
90
|
+
pValue = pbinom1(xs, ns, p, true, false);
|
|
91
|
+
else if (alternative === "greater")
|
|
92
|
+
pValue = pbinom1(xs - 1, ns, p, false, false);
|
|
93
|
+
else
|
|
94
|
+
pValue = twoSidedP(xs, ns, p);
|
|
95
|
+
const lower = (alpha) => (xs === 0 ? 0 : qbeta1(alpha, xs, ns - xs + 1, true, false));
|
|
96
|
+
const upper = (alpha) => (xs === ns ? 1 : qbeta1(1 - alpha, xs + 1, ns - xs, true, false));
|
|
97
|
+
let confInt;
|
|
98
|
+
if (alternative === "less")
|
|
99
|
+
confInt = [0, upper(1 - confLevel)];
|
|
100
|
+
else if (alternative === "greater")
|
|
101
|
+
confInt = [lower(1 - confLevel), 1];
|
|
102
|
+
else {
|
|
103
|
+
const alpha = (1 - confLevel) / 2;
|
|
104
|
+
confInt = [lower(alpha), upper(alpha)];
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
method: "Exact binomial test",
|
|
108
|
+
alternative,
|
|
109
|
+
statistic: xs,
|
|
110
|
+
statisticName: "number of successes",
|
|
111
|
+
parameter: ns,
|
|
112
|
+
parameterName: "number of trials",
|
|
113
|
+
pValue,
|
|
114
|
+
confInt,
|
|
115
|
+
confLevel,
|
|
116
|
+
estimate: xs / ns,
|
|
117
|
+
estimateNames: "probability of success",
|
|
118
|
+
nullValue: p,
|
|
119
|
+
nullValueName: "probability of success",
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -7,6 +7,13 @@ export interface ChisqTestOptions {
|
|
|
7
7
|
p?: readonly number[];
|
|
8
8
|
/** Rescale `p` to sum to 1. Default `false`, in which case `p` must sum to 1. */
|
|
9
9
|
rescaleP?: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Compute the p-value by Monte Carlo simulation with `B` replicates (R's `simulate.p.value`), using the random
|
|
12
|
+
* stream of {@link setSeed} as R does. Default `false`.
|
|
13
|
+
*/
|
|
14
|
+
simulatePValue?: boolean;
|
|
15
|
+
/** Number of replicates for `simulatePValue`. Default `2000`. */
|
|
16
|
+
B?: number;
|
|
10
17
|
}
|
|
11
18
|
/**
|
|
12
19
|
* Result of {@link chisqTest}. Has no `alternative`, because R's `chisq.test()` does not return one.
|
|
@@ -27,6 +34,19 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
|
|
|
27
34
|
*/
|
|
28
35
|
stdres: number[] | number[][];
|
|
29
36
|
}
|
|
37
|
+
/** Result of {@link chisqTest} with two factor vectors: also the levels that label the rows and columns. */
|
|
38
|
+
export interface ChisqTestFactorsResult extends ChisqTestResult {
|
|
39
|
+
observed: number[][];
|
|
40
|
+
expected: number[][];
|
|
41
|
+
residuals: number[][];
|
|
42
|
+
stdres: number[][];
|
|
43
|
+
/** Levels of `x` (rows of the table), sorted by code point. */
|
|
44
|
+
rowLevels: string[];
|
|
45
|
+
/** Levels of `y` (columns of the table), sorted by code point. */
|
|
46
|
+
colLevels: string[];
|
|
47
|
+
}
|
|
48
|
+
/** A factor: category labels, with `null` or `undefined` for missing values (R's NA). */
|
|
49
|
+
export type Factor = readonly (string | null | undefined)[];
|
|
30
50
|
/**
|
|
31
51
|
* Pearson's chi-squared test. Equivalent to R's `chisq.test()`.
|
|
32
52
|
*
|
|
@@ -36,10 +56,16 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
|
|
|
36
56
|
* 2 x 2 tables by default; as in R, the amount subtracted is `min(0.5, min |O - E|)` over
|
|
37
57
|
* all cells. Sums are computed in extended precision, like R.
|
|
38
58
|
*
|
|
39
|
-
*
|
|
59
|
+
* With `simulatePValue: true` the p-value is computed from `B` simulated samples (multinomial for goodness of fit,
|
|
60
|
+
* random tables with the observed margins otherwise), drawn from the random stream of {@link setSeed} exactly as in
|
|
61
|
+
* R, so `setSeed(s)` before the call gives R's p-value after `set.seed(s)`.
|
|
62
|
+
*
|
|
63
|
+
* Given two factor vectors (arrays of labels of the same length), tests independence in their contingency table, as
|
|
64
|
+
* R's `chisq.test(x, y)`; pairs with a missing label are dropped and the levels are sorted by code point.
|
|
65
|
+
*
|
|
40
66
|
* R's warning for expected counts below 5 is not issued.
|
|
41
67
|
*
|
|
42
|
-
* @param x Counts, or a contingency table as an array of rows.
|
|
68
|
+
* @param x Counts, or a contingency table as an array of rows (or a factor, with `y`).
|
|
43
69
|
* @param options See {@link ChisqTestOptions}.
|
|
44
70
|
* @returns The test result, with `statisticName` `"X-squared"`; see {@link ChisqTestResult}.
|
|
45
71
|
*
|
|
@@ -50,6 +76,12 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
|
|
|
50
76
|
* r.pValue; // 0.03762001663483994
|
|
51
77
|
*
|
|
52
78
|
* chisqTest([20, 30, 50]).pValue; // 0.0009118819655545154 (goodness of fit, equal p)
|
|
79
|
+
*
|
|
80
|
+
* setSeed(1);
|
|
81
|
+
* chisqTest([20, 15, 25], { simulatePValue: true }).pValue; // 0.296351824087956 (R: set.seed(1); chisq.test(...))
|
|
82
|
+
*
|
|
83
|
+
* chisqTest(["a", "b", "a", "b"], ["u", "u", "v", "v"]).rowLevels; // ["a", "b"]
|
|
53
84
|
* ```
|
|
54
85
|
*/
|
|
55
86
|
export declare function chisqTest(x: Counts | readonly Counts[], options?: ChisqTestOptions): ChisqTestResult;
|
|
87
|
+
export declare function chisqTest(x: Factor, y: Factor, options?: ChisqTestOptions): ChisqTestFactorsResult;
|
package/dist/htest/chisqTest.js
CHANGED
|
@@ -12,9 +12,17 @@
|
|
|
12
12
|
// 1-row or 1-column matrix) rejects only negative and NaN (Inf just makes the statistic NaN).
|
|
13
13
|
// Fractional counts are accepted in both cases
|
|
14
14
|
// - Sums are taken in double-double (R's sum accumulates in extended precision)
|
|
15
|
-
// -
|
|
15
|
+
// - Simulated p-values (Hope 1968; R's documented behaviour): (1 + #{simulated statistics >= (1 - 64 eps) times the
|
|
16
|
+
// observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) at once with sampleInt (R's
|
|
17
|
+
// sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
|
|
18
|
+
// (src/random/r2dtable.ts). The statistic is then the uncorrected one, and the parameter is NaN (R's NA). Tables
|
|
19
|
+
// with a zero margin are not simulated (ordinary test), as in R
|
|
20
|
+
// - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
|
|
16
21
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
22
|
+
import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
|
|
23
|
+
import { sampleInt } from "../random/sample.js";
|
|
17
24
|
import { ddAdd } from "../special/dd.js";
|
|
25
|
+
import { simulatedMethod } from "./core/simulate.js";
|
|
18
26
|
/** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
|
|
19
27
|
function ddSum(x) {
|
|
20
28
|
let s = [0, 0];
|
|
@@ -25,33 +33,42 @@ function ddSum(x) {
|
|
|
25
33
|
}
|
|
26
34
|
return Number.isFinite(plain) ? s[0] : plain;
|
|
27
35
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
36
|
+
export function chisqTest(x, yOrOptions, maybeOptions) {
|
|
37
|
+
if (Array.isArray(yOrOptions))
|
|
38
|
+
return chisqFactors(x, yOrOptions, maybeOptions ?? {});
|
|
39
|
+
return chisqCounts(x, yOrOptions ?? {});
|
|
40
|
+
}
|
|
41
|
+
/** Code-point order (the C locale) */
|
|
42
|
+
const byCodePoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
43
|
+
function chisqFactors(x, y, options) {
|
|
44
|
+
if (x.length !== y.length)
|
|
45
|
+
throw new RangeError("'x' and 'y' must have the same length");
|
|
46
|
+
const missing = (v) => v === null || v === undefined;
|
|
47
|
+
for (const v of [...x, ...y]) {
|
|
48
|
+
if (!missing(v) && typeof v !== "string")
|
|
49
|
+
throw new TypeError("factor values must be strings (or null for missing values)");
|
|
50
|
+
}
|
|
51
|
+
const xs = [];
|
|
52
|
+
const ys = [];
|
|
53
|
+
x.forEach((v, i) => {
|
|
54
|
+
const w = y[i];
|
|
55
|
+
if (!missing(v) && !missing(w)) {
|
|
56
|
+
xs.push(v);
|
|
57
|
+
ys.push(w);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
const rowLevels = [...new Set(xs)].sort(byCodePoint);
|
|
61
|
+
const colLevels = [...new Set(ys)].sort(byCodePoint);
|
|
62
|
+
if (rowLevels.length < 2 || colLevels.length < 2)
|
|
63
|
+
throw new RangeError("'x' and 'y' must have at least 2 levels");
|
|
64
|
+
const ri = new Map(rowLevels.map((v, i) => [v, i]));
|
|
65
|
+
const ci = new Map(colLevels.map((v, i) => [v, i]));
|
|
66
|
+
const table = rowLevels.map(() => colLevels.map(() => 0));
|
|
67
|
+
xs.forEach((v, k) => table[ri.get(v)][ci.get(ys[k])]++);
|
|
68
|
+
const r = contingency(table, options);
|
|
69
|
+
return { ...r, rowLevels, colLevels };
|
|
70
|
+
}
|
|
71
|
+
function chisqCounts(x, options) {
|
|
55
72
|
const isMatrix = x.length > 0 && typeof x[0] !== "number";
|
|
56
73
|
if (isMatrix) {
|
|
57
74
|
const rows = x.map((r) => Array.from(r));
|
|
@@ -63,10 +80,26 @@ export function chisqTest(x, options = {}) {
|
|
|
63
80
|
return goodnessOfFit(rows[0], options);
|
|
64
81
|
if (nc === 1)
|
|
65
82
|
return goodnessOfFit(rows.map((r) => r[0]), options);
|
|
66
|
-
return contingency(rows,
|
|
83
|
+
return contingency(rows, options);
|
|
67
84
|
}
|
|
68
85
|
return goodnessOfFit(Array.from(x), options);
|
|
69
86
|
}
|
|
87
|
+
/** Number of replicates, checked when a simulation is run */
|
|
88
|
+
function replicates(options) {
|
|
89
|
+
const B = options.B ?? 2000;
|
|
90
|
+
if (!(B >= 0 && B < 2 ** 31))
|
|
91
|
+
throw new RangeError("'B' must be a non-negative number");
|
|
92
|
+
return B;
|
|
93
|
+
}
|
|
94
|
+
/** (1 + #{sims >= (1 - 64 eps) stat}) / (B + 1) */
|
|
95
|
+
function monteCarloP(sims, stat, B) {
|
|
96
|
+
const threshold = (1 - 64 * Number.EPSILON) * stat;
|
|
97
|
+
let count = 0;
|
|
98
|
+
for (let i = 0; i < sims.length; i++)
|
|
99
|
+
if (sims[i] >= threshold)
|
|
100
|
+
count++;
|
|
101
|
+
return (1 + count) / (B + 1);
|
|
102
|
+
}
|
|
70
103
|
function pValueOf(stat, df) {
|
|
71
104
|
return Number.isNaN(stat) ? NaN : pgamma1(stat, df / 2, 2, false, false);
|
|
72
105
|
}
|
|
@@ -105,21 +138,80 @@ function goodnessOfFit(x, options) {
|
|
|
105
138
|
checkExpected(E);
|
|
106
139
|
const V = p.map((v, i) => E[i] * (1 - v));
|
|
107
140
|
const stat = ddSum(x.map((v, i) => (v - E[i]) ** 2 / E[i]));
|
|
108
|
-
|
|
141
|
+
let method = "Chi-squared test for given probabilities";
|
|
142
|
+
let df = k - 1;
|
|
143
|
+
let pValue;
|
|
144
|
+
if (options.simulatePValue ?? false) {
|
|
145
|
+
const B = replicates(options);
|
|
146
|
+
method += simulatedMethod(B);
|
|
147
|
+
df = NaN;
|
|
148
|
+
pValue = monteCarloP(simulateGoodnessOfFit(n, p, E, B), stat, B);
|
|
149
|
+
}
|
|
150
|
+
else
|
|
151
|
+
pValue = pValueOf(stat, df);
|
|
109
152
|
return {
|
|
110
|
-
method
|
|
153
|
+
method,
|
|
111
154
|
statistic: stat,
|
|
112
155
|
statisticName: "X-squared",
|
|
113
156
|
parameter: df,
|
|
114
157
|
parameterName: "df",
|
|
115
|
-
pValue
|
|
158
|
+
pValue,
|
|
116
159
|
observed: x,
|
|
117
160
|
expected: E,
|
|
118
161
|
residuals: x.map((v, i) => (v - E[i]) / Math.sqrt(E[i])),
|
|
119
162
|
stdres: x.map((v, i) => (v - E[i]) / Math.sqrt(V[i])),
|
|
120
163
|
};
|
|
121
164
|
}
|
|
122
|
-
|
|
165
|
+
/**
|
|
166
|
+
* Statistics of B multinomial samples: B n categories drawn at once with probabilities p (sampleInt, R's
|
|
167
|
+
* sample.int(k, B n, TRUE, prob = p)), laid out column by column in a matrix of floor(n) rows (recycled to fill the
|
|
168
|
+
* last column, as R's matrix() does when n is not an integer) and counted per column
|
|
169
|
+
*/
|
|
170
|
+
function simulateGoodnessOfFit(n, p, E, B) {
|
|
171
|
+
const k = p.length;
|
|
172
|
+
const draws = sampleInt(k, { size: Math.trunc(B * n), replace: true, prob: p });
|
|
173
|
+
const rows = Math.trunc(n);
|
|
174
|
+
if (draws.length === 0)
|
|
175
|
+
return new Float64Array(0);
|
|
176
|
+
if (rows === 0)
|
|
177
|
+
throw new RangeError("invalid 'nrow' value (too large or NA)");
|
|
178
|
+
const cols = Math.ceil(draws.length / rows);
|
|
179
|
+
const out = new Float64Array(cols);
|
|
180
|
+
const counts = new Float64Array(k);
|
|
181
|
+
for (let j = 0; j < cols; j++) {
|
|
182
|
+
counts.fill(0);
|
|
183
|
+
for (let i = 0; i < rows; i++)
|
|
184
|
+
counts[draws[(j * rows + i) % draws.length]]++;
|
|
185
|
+
let s = 0;
|
|
186
|
+
for (let c = 0; c < k; c++)
|
|
187
|
+
s += (counts[c] - E[c]) ** 2 / E[c];
|
|
188
|
+
out[j] = s;
|
|
189
|
+
}
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
/** Statistics of B random tables with the margins sr, sc (Patefield's algorithm), summed column by column */
|
|
193
|
+
function simulateTables(sr, sc, E, B) {
|
|
194
|
+
const nr = sr.length;
|
|
195
|
+
const nc = sc.length;
|
|
196
|
+
const total = sr.reduce((a, b) => a + b, 0);
|
|
197
|
+
const fact = logFactorialTable(total);
|
|
198
|
+
const table = new Int32Array(nr * nc);
|
|
199
|
+
const out = new Float64Array(Math.trunc(B));
|
|
200
|
+
for (let b = 0; b < out.length; b++) {
|
|
201
|
+
rcont2(sr, sc, fact, table);
|
|
202
|
+
let s = 0;
|
|
203
|
+
for (let j = 0; j < nc; j++) {
|
|
204
|
+
for (let i = 0; i < nr; i++) {
|
|
205
|
+
const e = E[i][j];
|
|
206
|
+
s += (table[i + j * nr] - e) ** 2 / e;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
out[b] = s;
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
function contingency(x, options) {
|
|
214
|
+
const correct = options.correct ?? true;
|
|
123
215
|
const nr = x.length;
|
|
124
216
|
const nc = x[0].length;
|
|
125
217
|
const all = x.flat();
|
|
@@ -135,15 +227,26 @@ function contingency(x, correct) {
|
|
|
135
227
|
const diff = x.map((r, i) => r.map((v, j) => v - E[i][j]));
|
|
136
228
|
let method = "Pearson's Chi-squared test";
|
|
137
229
|
let stat;
|
|
138
|
-
|
|
139
|
-
|
|
230
|
+
let df = (nr - 1) * (nc - 1);
|
|
231
|
+
let pValue;
|
|
232
|
+
const simulate = (options.simulatePValue ?? false) && sr.every((v) => v > 0) && sc.every((v) => v > 0);
|
|
233
|
+
const yates = !simulate && correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
|
|
234
|
+
if (simulate) {
|
|
235
|
+
// counts are integers for the simulation (R's C code takes the margins as integers)
|
|
236
|
+
const B = replicates(options);
|
|
237
|
+
method += simulatedMethod(B);
|
|
238
|
+
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
|
|
239
|
+
df = NaN;
|
|
240
|
+
const sims = simulateTables(sr.map((v) => Math.trunc(v)), sc.map((v) => Math.trunc(v)), E, B);
|
|
241
|
+
pValue = monteCarloP(sims, stat, B);
|
|
242
|
+
}
|
|
243
|
+
else if (yates > 0) {
|
|
140
244
|
method += " with Yates' continuity correction";
|
|
141
245
|
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (Math.abs(d) - yates) ** 2 / E[i][j])));
|
|
142
246
|
}
|
|
143
247
|
else {
|
|
144
248
|
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
|
|
145
249
|
}
|
|
146
|
-
const df = (nr - 1) * (nc - 1);
|
|
147
250
|
const V = E.map((r, i) => r.map((e, j) => e * (1 - sr[i] / n) * (1 - sc[j] / n)));
|
|
148
251
|
return {
|
|
149
252
|
method,
|
|
@@ -151,7 +254,7 @@ function contingency(x, correct) {
|
|
|
151
254
|
statisticName: "X-squared",
|
|
152
255
|
parameter: df,
|
|
153
256
|
parameterName: "df",
|
|
154
|
-
pValue: pValueOf(stat, df),
|
|
257
|
+
pValue: pValue ?? pValueOf(stat, df),
|
|
155
258
|
observed: x,
|
|
156
259
|
expected: E,
|
|
157
260
|
residuals: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j]))),
|
package/dist/htest/cor.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type DD } from "../special/dd.js";
|
|
1
2
|
import { type Alternative, type HTest, type Sample } from "./types.js";
|
|
2
3
|
/** Correlation coefficient: Pearson's r, Kendall's tau or Spearman's rho. */
|
|
3
4
|
export type CorMethod = "pearson" | "kendall" | "spearman";
|
|
@@ -52,6 +53,18 @@ export interface CorTestResult extends HTest {
|
|
|
52
53
|
* @returns The correlation coefficient.
|
|
53
54
|
*/
|
|
54
55
|
export declare function cor(x: Sample, y: Sample, options?: CorOptions): number;
|
|
56
|
+
/** Pearson's correlation coefficient in double-double (so 1 - r is computed without cancellation near perfect correlation) */
|
|
57
|
+
export declare function pearsonDD(x: readonly number[], y: readonly number[]): DD;
|
|
58
|
+
interface KendallStats {
|
|
59
|
+
/** Number of concordant pairs minus number of discordant pairs */
|
|
60
|
+
s: number;
|
|
61
|
+
tau: number;
|
|
62
|
+
ties: boolean;
|
|
63
|
+
tx: number[];
|
|
64
|
+
ty: number[];
|
|
65
|
+
}
|
|
66
|
+
/** Count concordant and discordant pairs (O(n^2)). Two Infs are tied */
|
|
67
|
+
export declare function kendall(x: readonly number[], y: readonly number[]): KendallStats;
|
|
55
68
|
/**
|
|
56
69
|
* Test for correlation between paired samples. Equivalent to R's `cor.test()`.
|
|
57
70
|
*
|
|
@@ -79,3 +92,4 @@ export declare function cor(x: Sample, y: Sample, options?: CorOptions): number;
|
|
|
79
92
|
* ```
|
|
80
93
|
*/
|
|
81
94
|
export declare function corTest(x: Sample, y: Sample, options?: CorTestOptions): CorTestResult;
|
|
95
|
+
export {};
|
package/dist/htest/cor.js
CHANGED
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
// - Pairs containing NaN are dropped (Inf is kept). Pearson needs at least 3 pairs, Kendall and Spearman at least 2
|
|
14
14
|
// - Kendall's exact method is the default when n < 50 and there are no ties. Even with exact = true, ties force the normal approximation
|
|
15
15
|
// - Spearman's exact method (AS 89) is the default when n <= 1290 and there are no ties (off by one from "n < 1290" in R's help).
|
|
16
|
-
// Within AS 89, n <= 9 is enumerated exactly and n >= 10 uses the Edgeworth series
|
|
16
|
+
// Within AS 89, n <= 9 is enumerated exactly and n >= 10 uses the Edgeworth series (this n <= 9 switch follows
|
|
17
|
+
// R's behaviour). With ties, the t approximation is used
|
|
17
18
|
// - continuity only affects the approximations. For Kendall it moves S one step towards 0. For Spearman it
|
|
18
19
|
// replaces rho with (rho + 6 / (n^3 - n)) / (1 + 6 / (n^3 - n)) (regardless of sign or alternative; R's behaviour)
|
|
19
20
|
// - When the correlation is undefined (constant data), the statistic, p-value, estimate and interval are NaN. Kendall's
|
|
@@ -86,7 +87,7 @@ function scaledDeviations(x) {
|
|
|
86
87
|
return d.map((v) => [v[0] * f, v[1] * f]);
|
|
87
88
|
}
|
|
88
89
|
/** Pearson's correlation coefficient in double-double (so 1 - r is computed without cancellation near perfect correlation) */
|
|
89
|
-
function pearsonDD(x, y) {
|
|
90
|
+
export function pearsonDD(x, y) {
|
|
90
91
|
const n = x.length;
|
|
91
92
|
if (n < 2)
|
|
92
93
|
return [NaN, 0];
|
|
@@ -137,7 +138,7 @@ function pFromZ(z, alternative) {
|
|
|
137
138
|
return 2 * Math.min(pnorm(z), pnorm(z, { lowerTail: false }));
|
|
138
139
|
}
|
|
139
140
|
/** Count concordant and discordant pairs (O(n^2)). Two Infs are tied */
|
|
140
|
-
function kendall(x, y) {
|
|
141
|
+
export function kendall(x, y) {
|
|
141
142
|
const n = x.length;
|
|
142
143
|
let s = 0;
|
|
143
144
|
for (let i = 0; i < n; i++) {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* P(AB <= q) (lowerTail) or P(AB > q) for the Ansari-Bradley statistic with sample sizes m and n, without ties.
|
|
3
|
+
*
|
|
4
|
+
* @param q - Value of the statistic.
|
|
5
|
+
* @param m - Size of the first sample.
|
|
6
|
+
* @param n - Size of the second sample.
|
|
7
|
+
* @param lowerTail - `true` for P(AB <= q), `false` for P(AB > q).
|
|
8
|
+
*/
|
|
9
|
+
export declare function pansariExact(q: number, m: number, n: number, lowerTail?: boolean): number;
|
|
10
|
+
/**
|
|
11
|
+
* P(AB = x) for the Ansari-Bradley statistic with sample sizes m and n, without ties.
|
|
12
|
+
*/
|
|
13
|
+
export declare function dansariExact(x: number, m: number, n: number): number;
|
|
14
|
+
/**
|
|
15
|
+
* The smallest q with P(AB <= q) >= p (quantile of the Ansari-Bradley statistic), without ties. A relative slack of
|
|
16
|
+
* 64 ε on p keeps p = P(AB <= q) itself from being missed by rounding.
|
|
17
|
+
*/
|
|
18
|
+
export declare function qansariExact(p: number, m: number, n: number): number;
|
|
19
|
+
/**
|
|
20
|
+
* R's qansari, used by ansari.test's exact interval and estimate: the smallest q at which the running sum of
|
|
21
|
+
* count(k) / C(N, m) over k = min, ..., q, accumulated in double, reaches p (p = 0 gives the minimum, p = 1 the
|
|
22
|
+
* maximum). Unlike {@link qansariExact} there is no slack, so a cumulative probability that equals p mathematically
|
|
23
|
+
* (such as 1/2) may be missed by rounding, as in R.
|
|
24
|
+
*/
|
|
25
|
+
export declare function qansariR(p: number, m: number, n: number): number;
|