@numero-uno-jpn/rstats 0.8.0 → 0.10.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 (122) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.ja.md +89 -13
  3. package/README.md +90 -13
  4. package/THIRD_PARTY_NOTICES.md +12 -2
  5. package/dist/chunks/{chunk-OHPHNE3O.js → chunk-2XKG3DX4.js} +1 -1
  6. package/dist/chunks/{chunk-3I6EKGB6.js → chunk-4NM37MGA.js} +2 -2
  7. package/dist/chunks/chunk-7HPVUVZB.js +2 -0
  8. package/dist/chunks/{chunk-I3LAZE6C.js → chunk-AECGWZHD.js} +2 -2
  9. package/dist/chunks/chunk-ENL43FNO.js +2 -0
  10. package/dist/chunks/chunk-EWC6I75B.js +2 -0
  11. package/dist/chunks/chunk-IT354SHV.js +3 -0
  12. package/dist/chunks/{chunk-VIPSPG3Y.js → chunk-LIMZKONM.js} +2 -2
  13. package/dist/chunks/chunk-O6PT7IVU.js +2 -0
  14. package/dist/chunks/{chunk-YGWPU67I.js → chunk-QFULZNHL.js} +1 -1
  15. package/dist/chunks/{chunk-XU4BGFZ6.js → chunk-QJJWGNJP.js} +2 -2
  16. package/dist/chunks/{chunk-32PRRONF.js → chunk-QULPY6YM.js} +1 -1
  17. package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
  18. package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
  19. package/dist/descriptive/factanal.d.ts +56 -0
  20. package/dist/descriptive/factanal.js +186 -0
  21. package/dist/descriptive/omega.d.ts +56 -0
  22. package/dist/descriptive/omega.js +323 -0
  23. package/dist/descriptive.js +2 -2
  24. package/dist/distributions/bvnorm.d.ts +15 -0
  25. package/dist/distributions/bvnorm.js +131 -0
  26. package/dist/distributions/nbeta.js +34 -1
  27. package/dist/distributions/nchisq.d.ts +10 -0
  28. package/dist/distributions/nchisq.js +46 -0
  29. package/dist/distributions.js +2 -2
  30. package/dist/entries/distributions.d.ts +1 -0
  31. package/dist/entries/distributions.js +1 -0
  32. package/dist/entries/linalg.d.ts +2 -0
  33. package/dist/entries/linalg.js +2 -0
  34. package/dist/entries/numerics.d.ts +2 -0
  35. package/dist/entries/numerics.js +1 -0
  36. package/dist/entries/tests.d.ts +25 -1
  37. package/dist/entries/tests.js +22 -1
  38. package/dist/htest/agreement.d.ts +141 -0
  39. package/dist/htest/agreement.js +274 -0
  40. package/dist/htest/aov.d.ts +19 -0
  41. package/dist/htest/aov.js +22 -15
  42. package/dist/htest/core/simulate.d.ts +2 -0
  43. package/dist/htest/core/simulate.js +1 -1
  44. package/dist/htest/dunnett.d.ts +5 -0
  45. package/dist/htest/dunnett.js +89 -0
  46. package/dist/htest/effectSize.d.ts +112 -0
  47. package/dist/htest/effectSize.js +385 -0
  48. package/dist/htest/leveneTest.d.ts +30 -0
  49. package/dist/htest/leveneTest.js +41 -0
  50. package/dist/htest/multipleComparisons.d.ts +147 -0
  51. package/dist/htest/multipleComparisons.js +369 -0
  52. package/dist/htest/normalityTests.d.ts +44 -0
  53. package/dist/htest/normalityTests.js +164 -0
  54. package/dist/htest/polycor.d.ts +117 -0
  55. package/dist/htest/polycor.js +468 -0
  56. package/dist/htest/power.d.ts +132 -0
  57. package/dist/htest/power.js +227 -0
  58. package/dist/htest/pwr.d.ts +263 -0
  59. package/dist/htest/pwr.js +440 -0
  60. package/dist/htest/rankTests.d.ts +7 -0
  61. package/dist/htest/rankTests.js +11 -1
  62. package/dist/htest/trendTests.d.ts +57 -0
  63. package/dist/htest/trendTests.js +167 -0
  64. package/dist/linalg/eigen.d.ts +8 -0
  65. package/dist/linalg/eigen.js +5 -4
  66. package/dist/linalg/expm.d.ts +48 -0
  67. package/dist/linalg/expm.js +472 -0
  68. package/dist/linalg/schur.d.ts +48 -0
  69. package/dist/linalg/schur.js +225 -0
  70. package/dist/linalg.js +2 -2
  71. package/dist/models/anovaSequential.d.ts +58 -0
  72. package/dist/models/anovaSequential.js +138 -0
  73. package/dist/models/aovEz.d.ts +64 -0
  74. package/dist/models/aovEz.js +332 -0
  75. package/dist/models/aovStrata.d.ts +32 -0
  76. package/dist/models/aovStrata.js +104 -0
  77. package/dist/models/carAnova.d.ts +30 -0
  78. package/dist/models/carAnova.js +121 -0
  79. package/dist/models/coxph.d.ts +101 -0
  80. package/dist/models/coxph.js +502 -0
  81. package/dist/models/ddLeastSquares.d.ts +30 -0
  82. package/dist/models/ddLeastSquares.js +90 -0
  83. package/dist/models/ddMatrix.d.ts +10 -0
  84. package/dist/models/ddMatrix.js +91 -0
  85. package/dist/models/formula.d.ts +83 -0
  86. package/dist/models/formula.js +333 -0
  87. package/dist/models/glm.d.ts +226 -0
  88. package/dist/models/glm.js +546 -0
  89. package/dist/models/glmAnova.d.ts +31 -0
  90. package/dist/models/glmAnova.js +146 -0
  91. package/dist/models/glmConfint.d.ts +25 -0
  92. package/dist/models/glmConfint.js +139 -0
  93. package/dist/models/glmFamily.d.ts +66 -0
  94. package/dist/models/glmFamily.js +359 -0
  95. package/dist/models/lm.d.ts +84 -3
  96. package/dist/models/lm.js +141 -44
  97. package/dist/models/mauchly.d.ts +48 -0
  98. package/dist/models/mauchly.js +123 -0
  99. package/dist/models/modelFrame.d.ts +40 -0
  100. package/dist/models/modelFrame.js +131 -0
  101. package/dist/models/modelMatrix.d.ts +88 -0
  102. package/dist/models/modelMatrix.js +170 -0
  103. package/dist/models/survival.d.ts +87 -0
  104. package/dist/models/survival.js +238 -0
  105. package/dist/numerics.js +2 -2
  106. package/dist/optim/lbfgsb.d.ts +20 -0
  107. package/dist/optim/lbfgsb.js +1240 -0
  108. package/dist/optim/optim.d.ts +85 -0
  109. package/dist/optim/optim.js +610 -0
  110. package/dist/rstats.js +19 -3
  111. package/dist/special.js +2 -2
  112. package/dist/tests.js +18 -3
  113. package/llms.txt +102 -0
  114. package/package.json +3 -2
  115. package/dist/chunks/chunk-EJRCDJ76.js +0 -2
  116. package/dist/chunks/chunk-JERGQKZM.js +0 -2
  117. package/dist/chunks/chunk-JVYV4633.js +0 -2
  118. package/dist/chunks/chunk-LXMMKO26.js +0 -2
  119. package/dist/chunks/chunk-MJQLKEO5.js +0 -2
  120. package/dist/chunks/chunk-RZ7SBJEG.js +0 -2
  121. package/dist/chunks/chunk-SPQC445Q.js +0 -2
  122. package/dist/chunks/chunk-U633VFH3.js +0 -2
@@ -0,0 +1,385 @@
1
+ // Effect sizes as the effectsize package computes them: the standardized differences Cohen's d and Hedges' g with
2
+ // their confidence intervals, and eta, omega and epsilon squared of the terms of an analysis-of-variance table, also
3
+ // of repeated-measures designs (aov with Error() strata, aovEz).
4
+ //
5
+ // Written for rStats.js from oracle/effectsize-behaviour.md and oracle/rm-tests-behaviour.md (no ported code;
6
+ // effectsize's source was not read). The confidence intervals invert the noncentral t and F distributions; unlike
7
+ // effectsize, which finds the noncentrality parameters with an optimiser (about 1e-9 accurate), the limits here are
8
+ // the exact roots (Brent's method run to the resolution of doubles).
9
+ import { pf, qf } from "../distributions/f.js";
10
+ import { pt } from "../distributions/t.js";
11
+ import { completePairs, dropNaN, mean, variance } from "../internal/summary.js";
12
+ import { anova, aovSummary } from "../models/anovaSequential.js";
13
+ import { uniroot } from "../numerics/integrate.js";
14
+ import { lgamma } from "../special/gamma.js";
15
+ import { matchChoice } from "./power.js";
16
+ const NA_WARNING = "Missing values detected. NAs dropped.";
17
+ /** Brent's method run until the bracket is as narrow as doubles allow */
18
+ const EXACT = { tol: 0, maxiter: 5000 };
19
+ /** Hedges' correction J(df) = Γ(df/2) / (sqrt(df/2) Γ((df − 1)/2)) */
20
+ function hedgesJ(df) {
21
+ return Math.exp(lgamma(df / 2) - Math.log(Math.sqrt(df / 2)) - lgamma((df - 1) / 2));
22
+ }
23
+ /** The noncentrality parameter with pt(t, df, ncp) = p (pt decreases in ncp) */
24
+ function ncpOfT(t, df, p) {
25
+ return uniroot((ncp) => pt(t, df, { ncp }) - p, t - 1, t + 1, { ...EXACT, extendInt: "downX" }).root;
26
+ }
27
+ function standardizedDifference(x, y, options, adjust) {
28
+ const pooled = options.pooledSd ?? true;
29
+ const mu = options.mu ?? 0;
30
+ const paired = options.paired ?? false;
31
+ const ci = options.ci === undefined ? 0.95 : options.ci;
32
+ const alt = matchChoice(options.alternative, ["two.sided", "less", "greater"]);
33
+ const xs = Array.from(x);
34
+ const ys = y === undefined ? undefined : Array.from(y);
35
+ const warnings = [];
36
+ if (xs.some(Number.isNaN) || (ys?.some(Number.isNaN) ?? false))
37
+ warnings.push(NA_WARNING);
38
+ let d;
39
+ let s;
40
+ let se;
41
+ let h;
42
+ let df;
43
+ if (ys === undefined || paired) {
44
+ let v;
45
+ if (ys === undefined)
46
+ v = dropNaN(xs);
47
+ else {
48
+ const [a, b] = completePairs(xs, ys);
49
+ v = a.map((ai, i) => ai - b[i]);
50
+ }
51
+ const n = v.length;
52
+ d = mean(v);
53
+ s = Math.sqrt(variance(v));
54
+ se = s / Math.sqrt(n);
55
+ h = 1 / n;
56
+ df = n - 1;
57
+ }
58
+ else {
59
+ const a = dropNaN(xs);
60
+ const b = dropNaN(ys);
61
+ const n1 = a.length;
62
+ const n2 = b.length;
63
+ d = mean(a) - mean(b);
64
+ const s1 = Math.sqrt(variance(a));
65
+ const s2 = Math.sqrt(variance(b));
66
+ if (pooled) {
67
+ s = Math.sqrt(((n1 - 1) * s1 ** 2 + (n2 - 1) * s2 ** 2) / (n1 + n2 - 2));
68
+ se = s * Math.sqrt(1 / n1 + 1 / n2);
69
+ h = 1 / n1 + 1 / n2;
70
+ df = n1 + n2 - 2;
71
+ }
72
+ else {
73
+ s = Math.sqrt((s1 ** 2 + s2 ** 2) / 2);
74
+ h = (2 * (n2 * s1 ** 2 + n1 * s2 ** 2)) / (n1 * n2 * (s1 ** 2 + s2 ** 2));
75
+ se = Math.sqrt(s1 ** 2 / n1 + s2 ** 2 / n2);
76
+ df = se ** 4 / ((s1 ** 2 / n1) ** 2 / (n1 - 1) + (s2 ** 2 / n2) ** 2 / (n2 - 1));
77
+ }
78
+ }
79
+ const j = adjust ? hedgesJ(df) : 1;
80
+ const value = ((d - mu) / s) * j;
81
+ const name = adjust ? "Hedges_g" : "Cohens_d";
82
+ if (ci === null)
83
+ return { name, value, warnings };
84
+ const level = alt === "two.sided" ? ci : 2 * ci - 1;
85
+ const t = (d - mu) / se;
86
+ let ciLow = ncpOfT(t, df, (1 + level) / 2) * Math.sqrt(h) * j;
87
+ let ciHigh = ncpOfT(t, df, (1 - level) / 2) * Math.sqrt(h) * j;
88
+ if (alt === "less")
89
+ ciLow = -Infinity;
90
+ if (alt === "greater")
91
+ ciHigh = Infinity;
92
+ return { name, value, ci, ciLow, ciHigh, warnings };
93
+ }
94
+ /**
95
+ * Cohen's d: the standardized difference of means of two samples (pooled or averaged standard deviation), of paired
96
+ * samples, or of one sample against `mu`, with a confidence interval from the noncentral t distribution. Equivalent
97
+ * to effectsize's `cohens_d()`.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * cohensD([5.1, 4.9, 6.2, 5.8], [4.1, 4.5, 3.9, 5.0]).value; // 2.049693834034246
102
+ * ```
103
+ */
104
+ export function cohensD(x, y, options = {}) {
105
+ return standardizedDifference(x, y, options, options.adjust ?? false);
106
+ }
107
+ /**
108
+ * Hedges' g: Cohen's d and its interval multiplied by the small-sample correction J(df). Equivalent to effectsize's
109
+ * `hedges_g()`.
110
+ */
111
+ export function hedgesG(x, y, options = {}) {
112
+ return standardizedDifference(x, y, options, true);
113
+ }
114
+ const isFit = (m) => Array.isArray(m.effects);
115
+ const isStrataFit = (m) => m.multistratum === true;
116
+ const isStrataSummary = (m) => Array.isArray(m.strata);
117
+ const isEz = (m) => {
118
+ const e = m;
119
+ return typeof e.univariate === "object" && typeof e.anova === "object";
120
+ };
121
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
122
+ /** A name as a whole word */
123
+ const word = (name) => new RegExp(`\\b${escapeRegExp(name)}\\b`);
124
+ /** The strata of aov with Error() from its summary (intercept stratum left out), and the subject stratum */
125
+ function summaryStrata(s) {
126
+ const strata = s.strata
127
+ .filter((st) => st.stratum !== "Error: (Intercept)")
128
+ .map((st) => {
129
+ const name = st.stratum.replace(/^Error: /, "");
130
+ const iDf = st.colNames.indexOf("Df");
131
+ const iSS = st.colNames.indexOf("Sum Sq");
132
+ const rows = st.rowNames.map((r, i) => ({ name: r, df: st.table[i][iDf], ss: st.table[i][iSS] }));
133
+ const res = rows.find((r) => r.name === "Residuals");
134
+ if (res === undefined)
135
+ throw new Error(`the error stratum '${name}' has no residual degrees of freedom`);
136
+ return { name, terms: rows.filter((r) => r !== res), sse: res.ss, dfe: res.df };
137
+ });
138
+ if (strata.length === 0)
139
+ throw new TypeError("the fit has no error strata");
140
+ // the subject stratum is named by the first variable of the Error() term: the first variable of the first stratum
141
+ // (the strata follow the terms of the error model)
142
+ const first = strata[0].name.split(":")[0];
143
+ const subject = strata.find((st) => st.name === first);
144
+ if (subject === undefined)
145
+ throw new Error(`there is no error stratum '${first}'`);
146
+ return { strata, subject };
147
+ }
148
+ /**
149
+ * The strata of aovEz from car's univariate tests: a row without a within-subject factor in its name belongs to the
150
+ * subject stratum, any other to the stratum of the within-subject term made of the factors in its name; a stratum's
151
+ * residual is the Error SS and den Df of its rows (for the subject stratum also those of the intercept row, which is
152
+ * not a term). Returns the terms in the order of afex's table.
153
+ */
154
+ function ezStrata(m) {
155
+ const u = m.univariate;
156
+ const iSS = u.colNames.indexOf("Sum Sq");
157
+ const strata = [];
158
+ const stratumOf = (name, sse, dfe) => {
159
+ let st = strata.find((s) => s.name === name);
160
+ if (st === undefined)
161
+ strata.push((st = { name, terms: [], sse, dfe }));
162
+ return st;
163
+ };
164
+ const terms = new Map();
165
+ if (u.colNames.includes("Error SS")) {
166
+ const iDf = u.colNames.indexOf("num Df");
167
+ const iE = u.colNames.indexOf("Error SS");
168
+ const iDen = u.colNames.indexOf("den Df");
169
+ u.rowNames.forEach((name, i) => {
170
+ const row = u.table[i];
171
+ const ws = m.within.filter((w) => word(w).test(name));
172
+ const st = stratumOf(ws.length === 0 ? "Subject" : `Subject:${ws.join(":")}`, row[iE], row[iDen]);
173
+ if (name === "(Intercept)")
174
+ return;
175
+ const t = { name, df: row[iDf], ss: row[iSS] };
176
+ st.terms.push(t);
177
+ terms.set(name, t);
178
+ });
179
+ }
180
+ else {
181
+ // between-subjects factors only: car's Anova table, every term in the subject stratum
182
+ const iDf = u.colNames.indexOf("Df");
183
+ const r = u.rowNames.indexOf("Residuals");
184
+ const st = stratumOf("Subject", u.table[r][iSS], u.table[r][iDf]);
185
+ u.rowNames.forEach((name, i) => {
186
+ if (name === "(Intercept)" || name === "Residuals")
187
+ return;
188
+ const t = { name, df: u.table[i][iDf], ss: u.table[i][iSS] };
189
+ st.terms.push(t);
190
+ terms.set(name, t);
191
+ });
192
+ }
193
+ const subject = strata.find((s) => s.name === "Subject");
194
+ if (subject === undefined)
195
+ throw new Error("the result has no subject stratum");
196
+ const order = m.anova.rowNames.map((name) => {
197
+ const t = terms.get(name);
198
+ if (t === undefined)
199
+ throw new Error(`there is no univariate test of '${name}'`);
200
+ return t;
201
+ });
202
+ return { strata, subject, order };
203
+ }
204
+ /** The observed factors of a generalized eta squared: the test of a term, and the sum of SS over those terms */
205
+ function observedTerms(gen, terms) {
206
+ const observed = Array.isArray(gen) ? gen : [];
207
+ const missing = observed.filter((o) => !terms.some((t) => word(o).test(t.name)));
208
+ if (missing.length > 0)
209
+ throw new Error(`Observed variable not in data: ${missing.join(", ")}`);
210
+ const isObserved = (name) => observed.some((o) => word(o).test(name));
211
+ return { isObserved, ssObserved: terms.reduce((a, t) => (isObserved(t.name) ? a + t.ss : a), 0) };
212
+ }
213
+ /** The noncentrality limits of an F value: ncp ≥ 0 with pf(F, df1, df2, ncp) = p (pf decreases in ncp), 0 if none */
214
+ function ncpOfF(f, df1, df2, p) {
215
+ const g = (ncp) => pf(f, df1, df2, { ncp }) - p;
216
+ if (!(g(0) > 0))
217
+ return 0;
218
+ if (f === Infinity)
219
+ return Infinity;
220
+ return uniroot(g, 0, Math.max(10, f * df1 * 4), { ...EXACT, extendInt: "downX" }).root;
221
+ }
222
+ /** The effect size with its interval (on the eta-squared scale of the F value it implies) on df and dfe */
223
+ function withInterval(es, df, dfe, ci, alt) {
224
+ const level = alt === "two.sided" ? ci : 2 * ci - 1;
225
+ const e = Math.max(0, es);
226
+ const f = e / df / ((1 - e) / dfe);
227
+ let lo = ncpOfF(f, df, dfe, (1 + level) / 2);
228
+ let hi = ncpOfF(f, df, dfe, (1 - level) / 2);
229
+ if (f <= qf((1 - level) / 2, df, dfe))
230
+ hi = 0;
231
+ if (f <= qf((1 + level) / 2, df, dfe))
232
+ lo = 0;
233
+ let ciLow = lo === Infinity ? 1 : lo / (lo + dfe);
234
+ let ciHigh = hi === Infinity ? 1 : hi / (hi + dfe);
235
+ if (alt === "less")
236
+ ciLow = 0;
237
+ if (alt === "greater")
238
+ ciHigh = 1;
239
+ return [es, ci, ciLow, ciHigh];
240
+ }
241
+ const NEEDS = "needs a table of anova() or Anova(), a fit from lm() or aov() with a formula, its aovSummary(), or a result of aovEz()";
242
+ function anovaEffectSize(model, kind, options) {
243
+ if (typeof model !== "object" || model === null)
244
+ throw new TypeError(NEEDS);
245
+ if (isStrataFit(model) || isStrataSummary(model) || isEz(model))
246
+ return strataEffectSize(model, kind, options);
247
+ const tab = isFit(model) ? anova(model) : model;
248
+ if (!Array.isArray(tab.colNames) || !Array.isArray(tab.table))
249
+ throw new TypeError(NEEDS);
250
+ const ci = options.ci === undefined ? 0.95 : options.ci;
251
+ const alt = matchChoice(options.alternative ?? "greater", ["two.sided", "less", "greater"]);
252
+ const iDf = tab.colNames.indexOf("Df");
253
+ const iSS = tab.colNames.indexOf("Sum Sq");
254
+ if (iDf < 0 || iSS < 0)
255
+ throw new TypeError("the table needs the columns 'Df' and 'Sum Sq'");
256
+ const rows = tab.rowNames.map((name, i) => ({ name, df: tab.table[i][iDf], ss: tab.table[i][iSS] })).filter((r) => r.name !== "(Intercept)");
257
+ const res = rows.find((r) => r.name === "Residuals");
258
+ if (res === undefined)
259
+ throw new TypeError("the table has no row 'Residuals'");
260
+ const terms = rows.filter((r) => r !== res);
261
+ const dfe = res.df;
262
+ const sse = res.ss;
263
+ const mse = sse / dfe;
264
+ const ssTot = rows.reduce((a, r) => a + r.ss, 0);
265
+ const nObs = rows.reduce((a, r) => a + r.df, 0) + 1;
266
+ const gen = kind === "Eta2" ? (options.generalized ?? false) : false;
267
+ const single = terms.length === 1;
268
+ const mode = single ? "plain" : gen !== false ? "generalized" : (options.partial ?? true) ? "partial" : "plain";
269
+ // the terms that contain an observed factor as a whole word
270
+ const { isObserved, ssObserved } = observedTerms(gen, terms);
271
+ const value = (t) => {
272
+ const { ss, df } = t;
273
+ if (kind === "Eta2") {
274
+ if (mode === "partial")
275
+ return ss / (ss + sse);
276
+ if (mode === "plain")
277
+ return ss / ssTot;
278
+ return ss / (ss + sse + ssObserved - (isObserved(t.name) ? ss : 0));
279
+ }
280
+ if (kind === "Omega2") {
281
+ const v = mode === "partial" ? (ss - df * mse) / (ss + (nObs - df) * mse) : (ss - df * mse) / (ssTot + mse);
282
+ return Math.max(0, v);
283
+ }
284
+ const v = mode === "partial" ? (ss - df * mse) / (ss + sse) : (ss - df * mse) / ssTot;
285
+ return Math.max(0, v);
286
+ };
287
+ const column = `${kind}${mode === "plain" ? "" : `_${mode}`}`;
288
+ return {
289
+ colNames: ci === null ? [column] : [column, "CI", "CI_low", "CI_high"],
290
+ rowNames: terms.map((t) => t.name),
291
+ table: terms.map((t) => (ci === null ? [value(t)] : withInterval(value(t), t.df, dfe, ci, alt))),
292
+ warnings: [],
293
+ };
294
+ }
295
+ /**
296
+ * The effect sizes of a model with error strata: each term measured against the residual of its own stratum, the
297
+ * totals over all strata, and the subject stratum's residual in every partial omega squared
298
+ */
299
+ function strataEffectSize(model, kind, options) {
300
+ const ci = options.ci === undefined ? 0.95 : options.ci;
301
+ const alt = matchChoice(options.alternative ?? "greater", ["two.sided", "less", "greater"]);
302
+ const ez = isEz(model);
303
+ let strata;
304
+ let subject;
305
+ let rows;
306
+ if (ez) {
307
+ const s = ezStrata(model);
308
+ ({ strata, subject } = s);
309
+ rows = s.order.map((term) => ({ term, stratum: s.strata.find((st) => st.terms.includes(term)) }));
310
+ }
311
+ else {
312
+ ({ strata, subject } = summaryStrata(isStrataFit(model) ? aovSummary(model) : model));
313
+ rows = strata.flatMap((stratum) => stratum.terms.map((term) => ({ term, stratum })));
314
+ }
315
+ const allTerms = strata.flatMap((st) => st.terms);
316
+ const sseAll = strata.reduce((a, st) => a + st.sse, 0);
317
+ const ssTot = allTerms.reduce((a, t) => a + t.ss, 0) + sseAll;
318
+ const mseSubject = subject.sse / subject.dfe;
319
+ const gen = kind === "Eta2" ? (options.generalized ?? false) : false;
320
+ const mode = gen !== false ? "generalized" : (options.partial ?? true) ? "partial" : "plain";
321
+ const { isObserved, ssObserved } = observedTerms(gen, allTerms);
322
+ const value = (t, st) => {
323
+ const { ss, df } = t;
324
+ const mse = st.sse / st.dfe;
325
+ if (kind === "Eta2") {
326
+ if (mode === "partial")
327
+ return ss / (ss + st.sse);
328
+ if (mode === "plain")
329
+ return ss / ssTot;
330
+ return ss / (ss + sseAll + ssObserved - (isObserved(t.name) ? ss : 0));
331
+ }
332
+ if (kind === "Omega2") {
333
+ const w = st === subject ? 0 : 1;
334
+ const v = mode === "partial" ? (ss - df * mse) / (ss + w * st.sse + subject.sse + mseSubject) : (ss - df * mse) / (ssTot + mseSubject);
335
+ return Math.max(0, v);
336
+ }
337
+ const v = mode === "partial" ? (ss - df * mse) / (ss + st.sse) : (ss - df * mse) / ssTot;
338
+ return Math.max(0, v);
339
+ };
340
+ const column = `${kind}${mode === "plain" ? "" : `_${mode}`}`;
341
+ const out = {
342
+ colNames: ci === null ? [column] : [column, "CI", "CI_low", "CI_high"],
343
+ rowNames: rows.map((r) => r.term.name),
344
+ table: rows.map(({ term, stratum }) => {
345
+ const es = value(term, stratum);
346
+ return ci === null ? [es] : withInterval(es, term.df, stratum.dfe, ci, alt);
347
+ }),
348
+ warnings: [],
349
+ };
350
+ if (!ez)
351
+ out.groups = rows.map((r) => r.stratum.name);
352
+ return out;
353
+ }
354
+ /**
355
+ * Eta squared of the terms of an analysis-of-variance table (partial by default, or generalized), with confidence
356
+ * intervals from the noncentral F distribution. Equivalent to effectsize's `eta_squared()` for a table of
357
+ * `anova()` or `Anova()`; a fit from `lm()` with a formula is replaced by its `anova()` table.
358
+ *
359
+ * Repeated measures: for a fit of `aov()` with an `Error()` term (or its {@link aovSummary}) each term is measured
360
+ * against the residual of its error stratum, the totals add up all strata, and the result has the stratum of each
361
+ * row in `groups`; for a result of {@link aovEz}, the same from car's univariate tests (rows as afex's table).
362
+ *
363
+ * @example
364
+ * ```ts
365
+ * etaSquared(anova(lm("y ~ g", data))).colNames; // ["Eta2", "CI", "CI_low", "CI_high"]
366
+ * etaSquared(aov("y ~ W + Error(id/W)", long)).groups; // ["id:W"]
367
+ * ```
368
+ */
369
+ export function etaSquared(model, options = {}) {
370
+ return anovaEffectSize(model, "Eta2", options);
371
+ }
372
+ /**
373
+ * Omega squared of the terms of an analysis-of-variance table, also of repeated-measures designs (see
374
+ * {@link etaSquared}). Equivalent to effectsize's `omega_squared()`.
375
+ */
376
+ export function omegaSquared(model, options = {}) {
377
+ return anovaEffectSize(model, "Omega2", options);
378
+ }
379
+ /**
380
+ * Epsilon squared of the terms of an analysis-of-variance table, also of repeated-measures designs (see
381
+ * {@link etaSquared}). Equivalent to effectsize's `epsilon_squared()`.
382
+ */
383
+ export function epsilonSquared(model, options = {}) {
384
+ return anovaEffectSize(model, "Epsilon2", options);
385
+ }
@@ -0,0 +1,30 @@
1
+ import { type GroupLabel } from "./groups.js";
2
+ import type { Sample } from "./types.js";
3
+ /** Options for {@link leveneTest}. */
4
+ export interface LeveneTestOptions {
5
+ /** The centre of each group: `"median"` (default) or `"mean"`. */
6
+ center?: "median" | "mean" | (string & {});
7
+ }
8
+ /** Result of {@link leveneTest}: car's table. */
9
+ export interface LeveneTestResult {
10
+ /** `["Df", "F value", "Pr(>F)"]`. */
11
+ colNames: string[];
12
+ /** `["group", ""]` (the second row is the residuals). */
13
+ rowNames: string[];
14
+ /** One array per row; NaN where car prints nothing. */
15
+ table: number[][];
16
+ }
17
+ /**
18
+ * Levene's test for homogeneity of variance across groups. Equivalent to car's `leveneTest(y ~ g, center =
19
+ * median)` (or `mean`). Pairs with a missing value are dropped; groups are ordered by their sorted labels.
20
+ *
21
+ * @param y The values.
22
+ * @param g Group labels, parallel to `y`.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const g = ["a", "a", "a", "b", "b", "b", "c", "c", "c"];
27
+ * leveneTest([4.2, 5.1, 6.3, 5.8, 7.9, 8.4, 6.6, 7.0, 5.5], g).table[0]; // [2, 0.15936952714535912, 0.8561748951935417]
28
+ * ```
29
+ */
30
+ export declare function leveneTest(y: Sample, g: readonly GroupLabel[], options?: LeveneTestOptions): LeveneTestResult;
@@ -0,0 +1,41 @@
1
+ // Levene's test of equal variances as car's leveneTest computes it: the one-way analysis of variance of the absolute
2
+ // deviations of the values from the centre (median or mean) of their group (Brown and Forsythe's form with the
3
+ // median).
4
+ //
5
+ // Written for rStats.js from oracle/rm-tests-behaviour.md (no ported code; car's source was not read).
6
+ import { mean } from "../internal/summary.js";
7
+ import { aov } from "./aov.js";
8
+ import { labelledGroups, median } from "./groups.js";
9
+ import { matchChoice } from "./power.js";
10
+ /**
11
+ * Levene's test for homogeneity of variance across groups. Equivalent to car's `leveneTest(y ~ g, center =
12
+ * median)` (or `mean`). Pairs with a missing value are dropped; groups are ordered by their sorted labels.
13
+ *
14
+ * @param y The values.
15
+ * @param g Group labels, parallel to `y`.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const g = ["a", "a", "a", "b", "b", "b", "c", "c", "c"];
20
+ * leveneTest([4.2, 5.1, 6.3, 5.8, 7.9, 8.4, 6.6, 7.0, 5.5], g).table[0]; // [2, 0.15936952714535912, 0.8561748951935417]
21
+ * ```
22
+ */
23
+ export function leveneTest(y, g, options = {}) {
24
+ const center = matchChoice(options.center ?? "median", ["median", "mean"]);
25
+ const { groups } = labelledGroups(y, g);
26
+ if (groups.length < 2)
27
+ throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
28
+ const deviations = groups.map((s) => {
29
+ const c = center === "median" ? median(s) : mean(s);
30
+ return s.map((v) => Math.abs(v - c));
31
+ });
32
+ const r = aov(deviations);
33
+ return {
34
+ colNames: ["Df", "F value", "Pr(>F)"],
35
+ rowNames: ["group", ""],
36
+ table: [
37
+ [r.df[0], r.fValue, r.pValue],
38
+ [r.df[1], NaN, NaN],
39
+ ],
40
+ };
41
+ }
@@ -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;