@numero-uno-jpn/rstats 0.9.0 → 0.11.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.ja.md +64 -12
  3. package/README.md +63 -11
  4. package/THIRD_PARTY_NOTICES.md +7 -2
  5. package/dist/chunks/chunk-5WDJPHYY.js +2 -0
  6. package/dist/chunks/chunk-7GQMKH3Z.js +2 -0
  7. package/dist/chunks/chunk-AHHS6AC4.js +3 -0
  8. package/dist/chunks/chunk-ALM3VHFP.js +2 -0
  9. package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-C5XTWMGB.js} +1 -1
  10. package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
  11. package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-EZAFN5CD.js} +1 -1
  12. package/dist/chunks/{chunk-H2AP6TCR.js → chunk-EZWBRCJL.js} +1 -1
  13. package/dist/chunks/chunk-F5EDJFEO.js +2 -0
  14. package/dist/chunks/{chunk-FC2TLHZC.js → chunk-JWBO5WVN.js} +2 -2
  15. package/dist/chunks/{chunk-LE7TBHNI.js → chunk-TOGXTCZO.js} +2 -2
  16. package/dist/chunks/chunk-VJ4BDBMU.js +3 -0
  17. package/dist/chunks/chunk-Y5CNQ266.js +2 -0
  18. package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-Y5PYRAYP.js} +2 -2
  19. package/dist/chunks/{chunk-5K4PS7IV.js → chunk-YSWGDOWK.js} +2 -2
  20. package/dist/data/grouping.d.ts +79 -0
  21. package/dist/data/grouping.js +262 -0
  22. package/dist/descriptive/dataFrames.d.ts +110 -0
  23. package/dist/descriptive/dataFrames.js +392 -0
  24. package/dist/descriptive/factanal.d.ts +56 -0
  25. package/dist/descriptive/factanal.js +186 -0
  26. package/dist/descriptive/missing.d.ts +35 -0
  27. package/dist/descriptive/missing.js +50 -0
  28. package/dist/descriptive/omega.d.ts +56 -0
  29. package/dist/descriptive/omega.js +323 -0
  30. package/dist/descriptive/pivot.d.ts +89 -0
  31. package/dist/descriptive/pivot.js +343 -0
  32. package/dist/descriptive.js +2 -2
  33. package/dist/distributions/bvnorm.d.ts +15 -0
  34. package/dist/distributions/bvnorm.js +131 -0
  35. package/dist/distributions/nbeta.js +34 -1
  36. package/dist/distributions/nchisq.d.ts +10 -0
  37. package/dist/distributions/nchisq.js +46 -0
  38. package/dist/distributions.js +2 -2
  39. package/dist/entries/descriptive.d.ts +4 -0
  40. package/dist/entries/descriptive.js +4 -0
  41. package/dist/entries/distributions.d.ts +1 -0
  42. package/dist/entries/distributions.js +1 -0
  43. package/dist/entries/linalg.d.ts +2 -0
  44. package/dist/entries/linalg.js +2 -0
  45. package/dist/entries/numerics.d.ts +2 -0
  46. package/dist/entries/numerics.js +1 -0
  47. package/dist/entries/tests.d.ts +22 -1
  48. package/dist/entries/tests.js +19 -1
  49. package/dist/htest/agreement.d.ts +141 -0
  50. package/dist/htest/agreement.js +274 -0
  51. package/dist/htest/ansariTest.d.ts +12 -0
  52. package/dist/htest/ansariTest.js +5 -17
  53. package/dist/htest/aov.d.ts +19 -0
  54. package/dist/htest/aov.js +22 -15
  55. package/dist/htest/cor.d.ts +12 -0
  56. package/dist/htest/cor.js +9 -27
  57. package/dist/htest/core/simulate.d.ts +2 -0
  58. package/dist/htest/core/simulate.js +1 -1
  59. package/dist/htest/dunnett.d.ts +5 -0
  60. package/dist/htest/dunnett.js +89 -0
  61. package/dist/htest/effectSize.d.ts +112 -0
  62. package/dist/htest/effectSize.js +385 -0
  63. package/dist/htest/ksTest.d.ts +13 -0
  64. package/dist/htest/ksTest.js +5 -8
  65. package/dist/htest/leveneTest.d.ts +30 -0
  66. package/dist/htest/leveneTest.js +41 -0
  67. package/dist/htest/multipleComparisons.d.ts +147 -0
  68. package/dist/htest/multipleComparisons.js +369 -0
  69. package/dist/htest/normalityTests.d.ts +44 -0
  70. package/dist/htest/normalityTests.js +164 -0
  71. package/dist/htest/onewayTest.d.ts +14 -0
  72. package/dist/htest/onewayTest.js +5 -7
  73. package/dist/htest/polycor.d.ts +117 -0
  74. package/dist/htest/polycor.js +468 -0
  75. package/dist/htest/power.d.ts +132 -0
  76. package/dist/htest/power.js +227 -0
  77. package/dist/htest/pwr.d.ts +263 -0
  78. package/dist/htest/pwr.js +440 -0
  79. package/dist/htest/rankTests.d.ts +64 -0
  80. package/dist/htest/rankTests.js +27 -29
  81. package/dist/htest/tTest.d.ts +20 -0
  82. package/dist/htest/tTest.js +19 -24
  83. package/dist/htest/testFormula.d.ts +57 -0
  84. package/dist/htest/testFormula.js +171 -0
  85. package/dist/htest/trendTests.d.ts +57 -0
  86. package/dist/htest/trendTests.js +167 -0
  87. package/dist/htest/varTest.d.ts +23 -0
  88. package/dist/htest/varTest.js +11 -21
  89. package/dist/htest/wilcoxTest.d.ts +14 -0
  90. package/dist/htest/wilcoxTest.js +9 -24
  91. package/dist/linalg/eigen.d.ts +8 -0
  92. package/dist/linalg/eigen.js +5 -4
  93. package/dist/linalg/expm.d.ts +48 -0
  94. package/dist/linalg/expm.js +472 -0
  95. package/dist/linalg/ops.d.ts +13 -2
  96. package/dist/linalg/ops.js +20 -5
  97. package/dist/linalg/schur.d.ts +48 -0
  98. package/dist/linalg/schur.js +225 -0
  99. package/dist/linalg.js +2 -2
  100. package/dist/models/anovaSequential.d.ts +58 -0
  101. package/dist/models/anovaSequential.js +138 -0
  102. package/dist/models/aovEz.d.ts +64 -0
  103. package/dist/models/aovEz.js +332 -0
  104. package/dist/models/aovStrata.d.ts +32 -0
  105. package/dist/models/aovStrata.js +104 -0
  106. package/dist/models/carAnova.d.ts +30 -0
  107. package/dist/models/carAnova.js +121 -0
  108. package/dist/models/coxph.d.ts +101 -0
  109. package/dist/models/coxph.js +502 -0
  110. package/dist/models/ddLeastSquares.d.ts +30 -0
  111. package/dist/models/ddLeastSquares.js +90 -0
  112. package/dist/models/ddMatrix.d.ts +10 -0
  113. package/dist/models/ddMatrix.js +91 -0
  114. package/dist/models/formula.d.ts +83 -0
  115. package/dist/models/formula.js +333 -0
  116. package/dist/models/lm.d.ts +84 -3
  117. package/dist/models/lm.js +141 -44
  118. package/dist/models/mauchly.d.ts +48 -0
  119. package/dist/models/mauchly.js +123 -0
  120. package/dist/models/modelFrame.d.ts +40 -0
  121. package/dist/models/modelFrame.js +131 -0
  122. package/dist/models/modelMatrix.d.ts +88 -0
  123. package/dist/models/modelMatrix.js +170 -0
  124. package/dist/models/survival.d.ts +87 -0
  125. package/dist/models/survival.js +238 -0
  126. package/dist/numerics.js +2 -2
  127. package/dist/optim/lbfgsb.d.ts +20 -0
  128. package/dist/optim/lbfgsb.js +1240 -0
  129. package/dist/optim/optim.d.ts +85 -0
  130. package/dist/optim/optim.js +610 -0
  131. package/dist/rstats.js +19 -4
  132. package/dist/special.js +2 -2
  133. package/dist/tests.js +17 -4
  134. package/llms.txt +114 -0
  135. package/package.json +3 -2
  136. package/dist/chunks/chunk-24U4DKRY.js +0 -2
  137. package/dist/chunks/chunk-IVOBWYLV.js +0 -2
  138. package/dist/chunks/chunk-JLSTEMSN.js +0 -2
  139. package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
  140. package/dist/chunks/chunk-MSAUU6PY.js +0 -2
  141. package/dist/chunks/chunk-YC4JWUKG.js +0 -2
  142. package/dist/chunks/chunk-ZRO446BP.js +0 -2
@@ -0,0 +1,147 @@
1
+ import { type GroupLabel } from "./groups.js";
2
+ import { type PAdjustMethod } from "./pAdjust.js";
3
+ import { type Alternative, type Sample } from "./types.js";
4
+ /** Result of the PMCMRplus tests (R's `PMCMR` objects). */
5
+ export interface PMCMRResult {
6
+ /** Description of the test (R's `method`). */
7
+ method: string;
8
+ /**
9
+ * Statistics as a table: for the all-pairs tests row `r` compares group `rowNames[r]` with each group
10
+ * `colNames[c]` (lower triangle; `NaN` above the diagonal), for the many-to-one tests each group with the control
11
+ * (one column).
12
+ */
13
+ statistic: number[][];
14
+ /** p-values, in the same layout as `statistic`. */
15
+ pValue: number[][];
16
+ /** Labels of the rows (groups 2..k). */
17
+ rowNames: string[];
18
+ /** Labels of the columns (groups 1..k-1, or the control). */
19
+ colNames: string[];
20
+ /** How the p-values were adjusted (`"single-step"` for the simultaneous probabilities). */
21
+ pAdjustMethod: string;
22
+ /** R's warnings. */
23
+ warnings: string[];
24
+ }
25
+ /** Options of the all-pairs Dunn test. */
26
+ export interface KwAllPairsDunnTestOptions {
27
+ /** p-value adjustment (see `pAdjust`). Default `"holm"`. */
28
+ pAdjustMethod?: PAdjustMethod | (string & {});
29
+ }
30
+ /** Options of the many-to-one tests. */
31
+ export interface ManyOneTestOptions {
32
+ /** Alternative hypothesis for each group against the control. Default `"two.sided"`. */
33
+ alternative?: Alternative | "two" | "l" | "g";
34
+ }
35
+ /** Options of the many-to-one Dunn test. */
36
+ export interface KwManyOneDunnTestOptions extends ManyOneTestOptions {
37
+ /** `"single-step"` (simultaneous normal probabilities, the default) or a `pAdjust` method. */
38
+ pAdjustMethod?: "single-step" | PAdjustMethod | (string & {});
39
+ }
40
+ /** Options of Steel's many-to-one rank test (`manyOneUTest`). */
41
+ export type ManyOneUTestOptions = KwManyOneDunnTestOptions;
42
+ /**
43
+ * Dunn's all-pairs test of mean ranks with adjusted p-values. Equivalent to PMCMRplus's `kwAllPairsDunnTest()`.
44
+ *
45
+ * @param x Response values.
46
+ * @param g Group labels, parallel to `x` (groups in the order of the sorted labels).
47
+ */
48
+ export declare function kwAllPairsDunnTest(x: Sample, g: readonly GroupLabel[], options?: KwAllPairsDunnTestOptions): PMCMRResult;
49
+ /**
50
+ * Dunn's many-to-one test of mean ranks against the control (the first group). Equivalent to PMCMRplus's
51
+ * `kwManyOneDunnTest()`. With `pAdjustMethod` `"single-step"` (the default) the p-values are the exact simultaneous
52
+ * normal probabilities (R approximates them by randomised integration).
53
+ */
54
+ export declare function kwManyOneDunnTest(x: Sample, g: readonly GroupLabel[], options?: KwManyOneDunnTestOptions): PMCMRResult;
55
+ /**
56
+ * Dunnett's many-to-one test of means against the control (the first group), with the pooled variance. Equivalent to
57
+ * PMCMRplus's `dunnettTest()`. The p-values are the exact multivariate t probabilities (R approximates them by
58
+ * randomised integration); two-sided, as in PMCMRplus, `min(1, 2 P(max T_i >= |t|))`.
59
+ */
60
+ export declare function dunnettTest(x: Sample, g: readonly GroupLabel[], options?: ManyOneTestOptions): PMCMRResult;
61
+ /**
62
+ * Steel's many-to-one rank test in its normal approximation: the Mann-Whitney statistic of each group against the
63
+ * control (the first group), each pair ranked on its own (midranks), standardised with the tie-corrected variance.
64
+ * Equivalent to PMCMRplus's `manyOneUTest()`. The statistic is positive when the group ranks higher than the
65
+ * control. With `pAdjustMethod` `"single-step"` (the default; at least three groups) the p-values are the exact
66
+ * simultaneous normal probabilities (R approximates them by randomised integration).
67
+ *
68
+ * @param x Response values.
69
+ * @param g Group labels, parallel to `x` (groups in the order of the sorted labels).
70
+ */
71
+ export declare function manyOneUTest(x: Sample, g: readonly GroupLabel[], options?: ManyOneUTestOptions): PMCMRResult;
72
+ /**
73
+ * Dwass-Steel-Critchlow-Fligner all-pairs test of pairwise Mann-Whitney statistics. Equivalent to PMCMRplus's
74
+ * `dscfAllPairsTest()`. The statistic, sqrt(2) (U - n_i n_j / 2) / sqrt(Var U) with the smaller U, is never positive.
75
+ */
76
+ export declare function dscfAllPairsTest(x: Sample, g: readonly GroupLabel[]): PMCMRResult;
77
+ /**
78
+ * Games-Howell all-pairs test of means with Welch's standard errors and degrees of freedom. Equivalent to
79
+ * PMCMRplus's `gamesHowellTest()`.
80
+ */
81
+ export declare function gamesHowellTest(x: Sample, g: readonly GroupLabel[]): PMCMRResult;
82
+ /** Tukey's all-pairs test of means (Tukey-Kramer for unequal sizes). Equivalent to PMCMRplus's `tukeyTest()`. */
83
+ export declare function tukeyTest(x: Sample, g: readonly GroupLabel[]): PMCMRResult;
84
+ /**
85
+ * Steel's many-to-one rank test, as PMCMRplus 1.9.12's `steelTest()` behaves: it fails on every input, so this
86
+ * reproduces its errors. A two-sided alternative is rejected (`'arg' should be one of “greater”, “less”`), unequal
87
+ * group sizes give `Steel's test is only valid for balanced designs.`, and balanced data the error PMCMRplus raises
88
+ * internally.
89
+ *
90
+ * @throws Always.
91
+ */
92
+ export declare function steelTest(x: Sample, g: readonly GroupLabel[], options?: ManyOneTestOptions): never;
93
+ /** Adjustment method of {@link dunnTest} (dunn.test's `method`). */
94
+ export type DunnTestMethod = "none" | "bonferroni" | "sidak" | "holm" | "hs" | "hochberg" | "bh" | "by";
95
+ /** Options of {@link dunnTest}. */
96
+ export interface DunnTestOptions {
97
+ /** Adjustment of the p-values. Default `"none"`. */
98
+ method?: DunnTestMethod;
99
+ /** Report two-sided p-values (twice the upper tail of |Z|) instead of one-sided ones. Default `false`. */
100
+ altp?: boolean;
101
+ }
102
+ /** Result of {@link dunnTest} (dunn.test's list). */
103
+ export interface DunnTestResult {
104
+ /** Kruskal-Wallis chi-squared statistic (with the tie correction). */
105
+ chi2: number;
106
+ /** Dunn's z for each comparison. */
107
+ Z: number[];
108
+ /** p-values: the upper tail of |Z|, or twice that with `altp`. */
109
+ P: number[];
110
+ /** Adjusted p-values (no monotonicity step). */
111
+ PAdjusted: number[];
112
+ /** Labels of the comparisons, `"<label j> - <label i>"`, in the order (2,1), (3,1), (3,2), (4,1), ... */
113
+ comparisons: string[];
114
+ }
115
+ /**
116
+ * Dunn's test of all pairs of mean ranks. Equivalent to dunn.test's `dunn.test(x, g, method, altp)`. The step-wise
117
+ * adjustments multiply (or transform) each p-value by the factor of its rank and cap it at 1, without enforcing
118
+ * monotonicity, as dunn.test does (unlike `pAdjust`).
119
+ */
120
+ export declare function dunnTest(x: Sample, g: readonly GroupLabel[], options?: DunnTestOptions): DunnTestResult;
121
+ /** Options of {@link glhtDunnett}. */
122
+ export interface GlhtDunnettOptions {
123
+ /** Alternative hypothesis for each group against the control. Default `"two.sided"`. */
124
+ alternative?: Alternative | "two" | "l" | "g";
125
+ }
126
+ /** Result of {@link glhtDunnett}. */
127
+ export interface GlhtDunnettResult {
128
+ /** Labels of the contrasts, `"<level> - <level 1>"`. */
129
+ names: string[];
130
+ /** Differences of the group means from the control's. */
131
+ estimate: number[];
132
+ /** Their standard errors (pooled). */
133
+ se: number[];
134
+ /** t statistics. */
135
+ t: number[];
136
+ /** Simultaneous (single-step) p-values. */
137
+ p: number[];
138
+ /** Residual degrees of freedom, N - k. */
139
+ df: number;
140
+ }
141
+ /**
142
+ * Dunnett's many-to-one comparisons of a one-way ANOVA with simultaneous p-values. Equivalent to multcomp's
143
+ * `summary(glht(aov(y ~ g), linfct = mcp(g = "Dunnett"), alternative))`, with the exact multivariate t probabilities
144
+ * (R approximates them by randomised integration): two-sided `P(max |T_i| >= |t|)`, greater `P(max T_i >= t)`, less
145
+ * `P(min T_i <= t)`.
146
+ */
147
+ export declare function glhtDunnett(x: Sample, g: readonly GroupLabel[], options?: GlhtDunnettOptions): GlhtDunnettResult;
@@ -0,0 +1,369 @@
1
+ // Multiple comparisons after a one-way layout: PMCMRplus's dscfAllPairsTest, kwAllPairsDunnTest, kwManyOneDunnTest,
2
+ // dunnettTest, gamesHowellTest, tukeyTest, steelTest and manyOneUTest, dunn.test's dunn.test and multcomp's Dunnett contrasts
3
+ // (summary(glht(aov(y ~ g), mcp(g = "Dunnett")))).
4
+ //
5
+ // Written for rStats.js from the published statistics and the behaviour described in oracle/mcomp-behaviour.md (no
6
+ // ported code):
7
+ // - Dunn (Technometrics 6, 1964): z = (mean rank difference) / sqrt((N (N + 1) / 12 - C) (1/n_i + 1/n_j)) with the
8
+ // tie term C = sum (t^3 - t) / (12 (N - 1)).
9
+ // - Dunnett (JASA 50, 1955): t = (m_j - m_1) / (s sqrt(1/n_j + 1/n_1)) with the pooled s; the simultaneous
10
+ // probabilities are computed exactly by src/htest/dunnett.ts (R computes them by randomised integration).
11
+ // - Dwass (1960), Steel (1960), Critchlow and Fligner (1991): pairwise Mann-Whitney statistics standardised and
12
+ // compared with the studentized range for k means and infinite degrees of freedom.
13
+ // - Steel (Biometrics 15, 1959): the Mann-Whitney statistic of each group against the control, standardised, with
14
+ // simultaneous normal probabilities for the correlations of Dunnett's many-to-one comparisons.
15
+ // - Games and Howell (1976): Welch's standard error and degrees of freedom per pair, studentized range.
16
+ // - Tukey (1953), Tukey-Kramer: the pooled standard error, studentized range on N - k degrees of freedom.
17
+ import { pnorm } from "../distributions/normal.js";
18
+ import { ptukey } from "../distributions/tukey.js";
19
+ import { mean, rank, tieCounts, variance } from "../internal/summary.js";
20
+ import { pDunnettUpper } from "./dunnett.js";
21
+ import { labelledGroups } from "./groups.js";
22
+ import { pAdjust } from "./pAdjust.js";
23
+ import { kruskalTest } from "./rankTests.js";
24
+ import { matchAlternative } from "./types.js";
25
+ const TIES_WARNING = "Ties are present. z-quantiles were corrected for ties.";
26
+ function layout(x, g) {
27
+ const { labels, groups } = labelledGroups(x, g);
28
+ const k = groups.length;
29
+ if (k < 2)
30
+ throw new RangeError("there must be at least two groups");
31
+ const n = groups.map((s) => s.length);
32
+ return { labels, groups, n, N: n.reduce((a, b) => a + b, 0), k };
33
+ }
34
+ /** Mean ranks of the groups in the ranking of all observations, and the tie term C */
35
+ function meanRanks(d) {
36
+ const all = d.groups.flat();
37
+ const r = rank(all);
38
+ const R = [];
39
+ let pos = 0;
40
+ for (const ni of d.n) {
41
+ let s = 0;
42
+ for (let i = 0; i < ni; i++)
43
+ s += r[pos + i];
44
+ pos += ni;
45
+ R.push(s / ni);
46
+ }
47
+ let t3 = 0;
48
+ for (const t of tieCounts(all))
49
+ t3 += t * t * t - t;
50
+ return { R, C: t3 / (12 * (d.N - 1)) };
51
+ }
52
+ /** Lower-triangular table of f(i, j), i > j (row i - 1, column j), NaN above the diagonal */
53
+ function lowerTable(k, f) {
54
+ const out = Array.from({ length: k - 1 }, () => new Array(k - 1).fill(NaN));
55
+ for (let j = 0; j < k - 1; j++)
56
+ for (let i = j + 1; i < k; i++)
57
+ out[i - 1][j] = f(i, j);
58
+ return out;
59
+ }
60
+ /** p.adjust over the lower-triangle cells, column by column (as R's pairwise.table) */
61
+ function adjustLower(p, method) {
62
+ const k = p.length + 1;
63
+ const raw = [];
64
+ for (let j = 0; j < k - 1; j++)
65
+ for (let i = j + 1; i < k; i++)
66
+ raw.push(p[i - 1][j]);
67
+ const adj = pAdjust(raw, method);
68
+ let idx = 0;
69
+ const out = p.map((row) => row.slice());
70
+ for (let j = 0; j < k - 1; j++)
71
+ for (let i = j + 1; i < k; i++)
72
+ out[i - 1][j] = adj[idx++];
73
+ return out;
74
+ }
75
+ function allPairs(d, method, statistic, pValue, adjust, warnings = []) {
76
+ return {
77
+ method,
78
+ statistic,
79
+ pValue,
80
+ rowNames: d.labels.slice(1),
81
+ colNames: d.labels.slice(0, -1),
82
+ pAdjustMethod: adjust,
83
+ warnings,
84
+ };
85
+ }
86
+ function manyOne(d, method, statistic, pValue, adjust, warnings = []) {
87
+ return {
88
+ method,
89
+ statistic: statistic.map((v) => [v]),
90
+ pValue: pValue.map((v) => [v]),
91
+ rowNames: d.labels.slice(1),
92
+ colNames: d.labels.slice(0, 1),
93
+ pAdjustMethod: adjust,
94
+ warnings,
95
+ };
96
+ }
97
+ const upperNormal = (z) => pnorm(z, { lowerTail: false });
98
+ const upperRange = (q, k, df) => ptukey(Math.abs(q), k, df, { lowerTail: false });
99
+ /** Group means, and the pooled variance sum (n_i - 1) s_i^2 / sum (n_i - 1) with its degrees of freedom */
100
+ function pooled(d) {
101
+ let ss = 0;
102
+ let df = 0;
103
+ for (const grp of d.groups) {
104
+ if (grp.length < 2)
105
+ continue;
106
+ ss += (grp.length - 1) * variance(grp);
107
+ df += grp.length - 1;
108
+ }
109
+ return { m: d.groups.map(mean), s2: ss / df, df: d.N - d.k };
110
+ }
111
+ /**
112
+ * Dunn's all-pairs test of mean ranks with adjusted p-values. Equivalent to PMCMRplus's `kwAllPairsDunnTest()`.
113
+ *
114
+ * @param x Response values.
115
+ * @param g Group labels, parallel to `x` (groups in the order of the sorted labels).
116
+ */
117
+ export function kwAllPairsDunnTest(x, g, options = {}) {
118
+ const adjust = options.pAdjustMethod ?? "holm";
119
+ const d = layout(x, g);
120
+ const { R, C } = meanRanks(d);
121
+ const v = (d.N * (d.N + 1)) / 12 - C;
122
+ const z = lowerTable(d.k, (i, j) => Math.abs(R[i] - R[j]) / Math.sqrt(v * (1 / d.n[i] + 1 / d.n[j])));
123
+ const p = adjustLower(z.map((row) => row.map((s) => 2 * upperNormal(s))), adjust);
124
+ return allPairs(d, "Dunn's all-pairs test", z, p, adjust, C !== 0 ? [TIES_WARNING] : []);
125
+ }
126
+ /**
127
+ * Dunn's many-to-one test of mean ranks against the control (the first group). Equivalent to PMCMRplus's
128
+ * `kwManyOneDunnTest()`. With `pAdjustMethod` `"single-step"` (the default) the p-values are the exact simultaneous
129
+ * normal probabilities (R approximates them by randomised integration).
130
+ */
131
+ export function kwManyOneDunnTest(x, g, options = {}) {
132
+ const alternative = matchAlternative(options.alternative);
133
+ const adjust = options.pAdjustMethod ?? "single-step";
134
+ const d = layout(x, g);
135
+ const { R, C } = meanRanks(d);
136
+ const v = (d.N * (d.N + 1)) / 12 - C;
137
+ const idx = d.n.slice(1).map((_, i) => i + 1);
138
+ const z = idx.map((j) => (R[j] - R[0]) / Math.sqrt(v * (1 / d.n[0] + 1 / d.n[j])));
139
+ const lambda = idx.map((j) => d.n[j] / (d.n[j] + d.n[0]));
140
+ const p = manyOneNormalP(z, lambda, alternative, adjust);
141
+ return manyOne(d, "Dunn's many-to-one test", z, p, adjust, C !== 0 ? [TIES_WARNING] : []);
142
+ }
143
+ /**
144
+ * Many-to-one p-values of normal statistics z (one per group against the control): `"single-step"`, the exact
145
+ * simultaneous normal probabilities for the correlations sqrt(lambda_i lambda_j), or the marginal normal tails
146
+ * adjusted by `pAdjust`.
147
+ */
148
+ function manyOneNormalP(z, lambda, alternative, adjust) {
149
+ if (adjust === "single-step") {
150
+ return z.map((s) => alternative === "two.sided"
151
+ ? pDunnettUpper(s, lambda, Infinity, true)
152
+ : pDunnettUpper(alternative === "greater" ? s : -s, lambda, Infinity, false));
153
+ }
154
+ return pAdjust(z.map((s) => (alternative === "two.sided" ? 2 * upperNormal(Math.abs(s)) : upperNormal(alternative === "greater" ? s : -s))), adjust);
155
+ }
156
+ /**
157
+ * Dunnett's many-to-one test of means against the control (the first group), with the pooled variance. Equivalent to
158
+ * PMCMRplus's `dunnettTest()`. The p-values are the exact multivariate t probabilities (R approximates them by
159
+ * randomised integration); two-sided, as in PMCMRplus, `min(1, 2 P(max T_i >= |t|))`.
160
+ */
161
+ export function dunnettTest(x, g, options = {}) {
162
+ const alternative = matchAlternative(options.alternative);
163
+ const d = layout(x, g);
164
+ const { m, s2, df } = pooled(d);
165
+ const s = Math.sqrt(s2);
166
+ const idx = d.n.slice(1).map((_, i) => i + 1);
167
+ const t = idx.map((j) => (m[j] - m[0]) / (s * Math.sqrt(1 / d.n[j] + 1 / d.n[0])));
168
+ const lambda = idx.map((j) => d.n[j] / (d.n[j] + d.n[0]));
169
+ const p = t.map((v) => alternative === "two.sided"
170
+ ? Math.min(1, 2 * pDunnettUpper(Math.abs(v), lambda, df, false))
171
+ : pDunnettUpper(alternative === "greater" ? v : -v, lambda, df, false));
172
+ return manyOne(d, "Dunnett's-test for multiple\t\n comparisons with one control", t, p, "single-step");
173
+ }
174
+ /**
175
+ * Steel's many-to-one rank test in its normal approximation: the Mann-Whitney statistic of each group against the
176
+ * control (the first group), each pair ranked on its own (midranks), standardised with the tie-corrected variance.
177
+ * Equivalent to PMCMRplus's `manyOneUTest()`. The statistic is positive when the group ranks higher than the
178
+ * control. With `pAdjustMethod` `"single-step"` (the default; at least three groups) the p-values are the exact
179
+ * simultaneous normal probabilities (R approximates them by randomised integration).
180
+ *
181
+ * @param x Response values.
182
+ * @param g Group labels, parallel to `x` (groups in the order of the sorted labels).
183
+ */
184
+ export function manyOneUTest(x, g, options = {}) {
185
+ const alternative = matchAlternative(options.alternative);
186
+ const adjust = options.pAdjustMethod ?? "single-step";
187
+ const d = layout(x, g);
188
+ if (adjust === "single-step" && d.k < 3) {
189
+ throw new RangeError("for 'p.adjust.method = single-step' at least\n\n k = 3 groups are required.");
190
+ }
191
+ const n1 = d.n[0];
192
+ const idx = d.n.slice(1).map((_, i) => i + 1);
193
+ const z = idx.map((j) => {
194
+ const nj = d.n[j];
195
+ const pair = [...d.groups[0], ...d.groups[j]];
196
+ const r = rank(pair);
197
+ let rankSumControl = 0;
198
+ for (let a = 0; a < n1; a++)
199
+ rankSumControl += r[a];
200
+ const S = n1 + nj;
201
+ const rankSumGroup = (S * (S + 1)) / 2 - rankSumControl;
202
+ const uControl = n1 * nj + (n1 * (n1 + 1)) / 2 - rankSumControl;
203
+ const uGroup = n1 * nj + (nj * (nj + 1)) / 2 - rankSumGroup;
204
+ let t3 = 0;
205
+ for (const t of tieCounts(pair))
206
+ t3 += t * t * t - t;
207
+ const v = ((n1 * nj) / (S * (S - 1))) * ((S * S * S - S) / 12 - t3 / 12);
208
+ const stat = (Math.min(uControl, uGroup) - (n1 * nj) / 2) / Math.sqrt(v);
209
+ return rankSumControl < rankSumGroup ? -stat : stat;
210
+ });
211
+ const lambda = idx.map((j) => d.n[j] / (d.n[j] + n1));
212
+ const p = manyOneNormalP(z, lambda, alternative, adjust);
213
+ return manyOne(d, "Wilcoxon, Mann, Whittney U-test\n\tfor multiple comparisons with one control", z, p, adjust);
214
+ }
215
+ /**
216
+ * Dwass-Steel-Critchlow-Fligner all-pairs test of pairwise Mann-Whitney statistics. Equivalent to PMCMRplus's
217
+ * `dscfAllPairsTest()`. The statistic, sqrt(2) (U - n_i n_j / 2) / sqrt(Var U) with the smaller U, is never positive.
218
+ */
219
+ export function dscfAllPairsTest(x, g) {
220
+ const d = layout(x, g);
221
+ const stat = lowerTable(d.k, (i, j) => {
222
+ const ni = d.n[i];
223
+ const nj = d.n[j];
224
+ const both = [...d.groups[i], ...d.groups[j]];
225
+ const r = rank(both);
226
+ let ri = 0;
227
+ for (let a = 0; a < ni; a++)
228
+ ri += r[a];
229
+ const ui = ri - (ni * (ni + 1)) / 2;
230
+ const u = Math.min(ui, ni * nj - ui);
231
+ const S = ni + nj;
232
+ let t3 = 0;
233
+ for (const t of tieCounts(both))
234
+ t3 += t * t * t - t;
235
+ const v = ((ni * nj) / (S * (S - 1))) * ((S * S * S - S) / 12 - t3 / 12);
236
+ return (Math.SQRT2 * (u - (ni * nj) / 2)) / Math.sqrt(v);
237
+ });
238
+ const p = stat.map((row) => row.map((q) => (Number.isNaN(q) ? NaN : upperRange(q, d.k, Infinity))));
239
+ return allPairs(d, "Dwass-Steele-Critchlow-Fligner all-pairs test", stat, p, "single-step");
240
+ }
241
+ /**
242
+ * Games-Howell all-pairs test of means with Welch's standard errors and degrees of freedom. Equivalent to
243
+ * PMCMRplus's `gamesHowellTest()`.
244
+ */
245
+ export function gamesHowellTest(x, g) {
246
+ const d = layout(x, g);
247
+ const m = d.groups.map(mean);
248
+ const w = d.groups.map((grp, i) => variance(grp) / d.n[i]);
249
+ const q = lowerTable(d.k, (i, j) => ((m[i] - m[j]) / Math.sqrt(w[i] + w[j])) * Math.SQRT2);
250
+ const p = lowerTable(d.k, (i, j) => {
251
+ const df = (w[i] + w[j]) ** 2 / (w[i] ** 2 / (d.n[i] - 1) + w[j] ** 2 / (d.n[j] - 1));
252
+ return upperRange(q[i - 1][j], d.k, df);
253
+ });
254
+ return allPairs(d, "Games-Howell test", q, p, "none");
255
+ }
256
+ /** Tukey's all-pairs test of means (Tukey-Kramer for unequal sizes). Equivalent to PMCMRplus's `tukeyTest()`. */
257
+ export function tukeyTest(x, g) {
258
+ const d = layout(x, g);
259
+ const { m, s2, df } = pooled(d);
260
+ const q = lowerTable(d.k, (i, j) => (m[i] - m[j]) / Math.sqrt((s2 * (1 / d.n[i] + 1 / d.n[j])) / 2));
261
+ const p = q.map((row) => row.map((v) => (Number.isNaN(v) ? NaN : upperRange(v, d.k, df))));
262
+ return allPairs(d, "Tukey's test", q, p, "single-step");
263
+ }
264
+ /**
265
+ * Steel's many-to-one rank test, as PMCMRplus 1.9.12's `steelTest()` behaves: it fails on every input, so this
266
+ * reproduces its errors. A two-sided alternative is rejected (`'arg' should be one of “greater”, “less”`), unequal
267
+ * group sizes give `Steel's test is only valid for balanced designs.`, and balanced data the error PMCMRplus raises
268
+ * internally.
269
+ *
270
+ * @throws Always.
271
+ */
272
+ export function steelTest(x, g, options = {}) {
273
+ const alternative = options.alternative === undefined ? "greater" : matchAlternative(options.alternative);
274
+ if (alternative === "two.sided")
275
+ throw new RangeError("'arg' should be one of “greater”, “less”");
276
+ const d = layout(x, g);
277
+ if (d.n.some((v) => v !== d.n[0]))
278
+ throw new RangeError("Steel's test is only valid for balanced designs.");
279
+ throw new Error("'data' must be of a vector type, was 'NULL'");
280
+ }
281
+ /**
282
+ * Dunn's test of all pairs of mean ranks. Equivalent to dunn.test's `dunn.test(x, g, method, altp)`. The step-wise
283
+ * adjustments multiply (or transform) each p-value by the factor of its rank and cap it at 1, without enforcing
284
+ * monotonicity, as dunn.test does (unlike `pAdjust`).
285
+ */
286
+ export function dunnTest(x, g, options = {}) {
287
+ const method = options.method ?? "none";
288
+ const altp = options.altp ?? false;
289
+ const d = layout(x, g);
290
+ const chi2 = kruskalTest(x, g).statistic;
291
+ const { R, C } = meanRanks(d);
292
+ const v = (d.N * (d.N + 1)) / 12 - C;
293
+ const Z = [];
294
+ const comparisons = [];
295
+ for (let i = 1; i < d.k; i++) {
296
+ for (let j = 0; j < i; j++) {
297
+ Z.push((R[j] - R[i]) / Math.sqrt(v * (1 / d.n[j] + 1 / d.n[i])));
298
+ comparisons.push(`${d.labels[j]} - ${d.labels[i]}`);
299
+ }
300
+ }
301
+ const P = Z.map((z) => (altp ? 2 : 1) * upperNormal(Math.abs(z)));
302
+ return { chi2, Z, P, PAdjusted: dunnAdjust(P, method), comparisons };
303
+ }
304
+ /** dunn.test's adjustments: each value by the factor of its rank, capped at 1 */
305
+ function dunnAdjust(P, method) {
306
+ const m = P.length;
307
+ const sidakLike = (p, e) => Math.min(1, -Math.expm1(e * Math.log1p(-p)));
308
+ // i = 1..m: rank among the increasing (or decreasing) values, ties in the order of the comparisons
309
+ const ranks = (decreasing) => {
310
+ const order = P.map((_, k) => k).sort((a, b) => (decreasing ? P[b] - P[a] : P[a] - P[b]) || a - b);
311
+ const r = new Array(m);
312
+ order.forEach((k, pos) => (r[k] = pos + 1));
313
+ return r;
314
+ };
315
+ switch (method) {
316
+ case "none":
317
+ return P.slice();
318
+ case "bonferroni":
319
+ return P.map((p) => Math.min(1, m * p));
320
+ case "sidak":
321
+ return P.map((p) => sidakLike(p, m));
322
+ case "holm": {
323
+ const r = ranks(false);
324
+ return P.map((p, k) => Math.min(1, (m + 1 - r[k]) * p));
325
+ }
326
+ case "hs": {
327
+ const r = ranks(false);
328
+ return P.map((p, k) => sidakLike(p, m + 1 - r[k]));
329
+ }
330
+ case "hochberg": {
331
+ const r = ranks(true);
332
+ return P.map((p, k) => Math.min(1, r[k] * p));
333
+ }
334
+ case "bh": {
335
+ const r = ranks(true);
336
+ return P.map((p, k) => Math.min(1, (m / (m + 1 - r[k])) * p));
337
+ }
338
+ case "by": {
339
+ const r = ranks(true);
340
+ let h = 0;
341
+ for (let l = 1; l <= m; l++)
342
+ h += 1 / l;
343
+ return P.map((p, k) => Math.min(1, (m / (m + 1 - r[k])) * h * p));
344
+ }
345
+ default:
346
+ throw new RangeError(`invalid method "${String(method)}"`);
347
+ }
348
+ }
349
+ /**
350
+ * Dunnett's many-to-one comparisons of a one-way ANOVA with simultaneous p-values. Equivalent to multcomp's
351
+ * `summary(glht(aov(y ~ g), linfct = mcp(g = "Dunnett"), alternative))`, with the exact multivariate t probabilities
352
+ * (R approximates them by randomised integration): two-sided `P(max |T_i| >= |t|)`, greater `P(max T_i >= t)`, less
353
+ * `P(min T_i <= t)`.
354
+ */
355
+ export function glhtDunnett(x, g, options = {}) {
356
+ const alternative = matchAlternative(options.alternative);
357
+ const d = layout(x, g);
358
+ const { m, s2, df } = pooled(d);
359
+ const s = Math.sqrt(s2);
360
+ const idx = d.n.slice(1).map((_, i) => i + 1);
361
+ const estimate = idx.map((j) => m[j] - m[0]);
362
+ const se = idx.map((j) => s * Math.sqrt(1 / d.n[j] + 1 / d.n[0]));
363
+ const t = estimate.map((e, i) => e / se[i]);
364
+ const lambda = idx.map((j) => d.n[j] / (d.n[j] + d.n[0]));
365
+ const p = t.map((v) => alternative === "two.sided"
366
+ ? pDunnettUpper(v, lambda, df, true)
367
+ : pDunnettUpper(alternative === "greater" ? v : -v, lambda, df, false));
368
+ return { names: idx.map((j) => `${d.labels[j]} - ${d.labels[0]}`), estimate, se, t, p, df };
369
+ }
@@ -0,0 +1,44 @@
1
+ import type { HTest, Sample } from "./types.js";
2
+ /** Result of a normality test: no `alternative`, as nortest returns none. */
3
+ export type NormalityTestResult = Omit<HTest, "alternative">;
4
+ /** Result of {@link cvmTest}, with nortest's warning for a p-value below the approximation's range. */
5
+ export interface CvmTestResult extends NormalityTestResult {
6
+ warnings: string[];
7
+ }
8
+ /**
9
+ * Anderson-Darling test for normality. Equivalent to nortest's `ad.test()`. `NaN` values are dropped; at least 8
10
+ * values are needed.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * adTest([2.1, 3.4, 1.9, 5.6, 4.4, 3.8, 2.9, 4.1, 3.3, 2.6]).statistic; // 0.15414195923525043
15
+ * ```
16
+ */
17
+ export declare function adTest(x: Sample): NormalityTestResult;
18
+ /**
19
+ * Cramer-von Mises test for normality. Equivalent to nortest's `cvm.test()`. `NaN` values are dropped; at least 8
20
+ * values are needed.
21
+ */
22
+ export declare function cvmTest(x: Sample): CvmTestResult;
23
+ /**
24
+ * Lilliefors (Kolmogorov-Smirnov) test for normality. Equivalent to nortest's `lillie.test()`. `NaN` values are
25
+ * dropped; at least 5 values are needed.
26
+ */
27
+ export declare function lillieTest(x: Sample): NormalityTestResult;
28
+ /**
29
+ * Shapiro-Francia test for normality. Equivalent to nortest's `sf.test()`. `NaN` values are dropped; the sample size
30
+ * must be between 5 and 5000.
31
+ */
32
+ export declare function sfTest(x: Sample): NormalityTestResult;
33
+ /** Options for {@link pearsonTest}. */
34
+ export interface PearsonTestOptions {
35
+ /** Number of classes. Default `ceil(2 n^(2/5))`. */
36
+ nClasses?: number;
37
+ /** Subtract the 2 estimated parameters from the degrees of freedom. Default `true`. */
38
+ adjust?: boolean;
39
+ }
40
+ /**
41
+ * Pearson chi-square test for normality, with classes of equal probability under the fitted normal distribution.
42
+ * Equivalent to nortest's `pearson.test()`. `NaN` values are dropped.
43
+ */
44
+ export declare function pearsonTest(x: Sample, options?: PearsonTestOptions): NormalityTestResult;