@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,112 @@
1
+ import { type AnovaTable, type AovStrataSummary } from "../models/anovaSequential.js";
2
+ import type { AovEzResult } from "../models/aovEz.js";
3
+ import type { AovStrataFit } from "../models/aovStrata.js";
4
+ import type { LmFormulaResult } from "../models/lm.js";
5
+ import type { Alternative, Sample } from "./types.js";
6
+ /** Options for {@link cohensD} and {@link hedgesG}. */
7
+ export interface CohensDOptions {
8
+ /** Two samples: standardize by the pooled standard deviation (default `true`) or by `sqrt((s1² + s2²)/2)`. */
9
+ pooledSd?: boolean;
10
+ /** The difference (or mean) under the null hypothesis. Default `0`. */
11
+ mu?: number;
12
+ /** Paired samples: the effect size of the differences `x - y`. Default `false`. */
13
+ paired?: boolean;
14
+ /** Confidence level of the interval, or `null` for no interval. Default `0.95`. */
15
+ ci?: number | null;
16
+ /** `"two.sided"` (default), `"less"` or `"greater"`: a one-sided interval is open on the other side. */
17
+ alternative?: Alternative | (string & {});
18
+ /** {@link cohensD} only: apply Hedges' small-sample correction (the result is Hedges' g). Default `false`. */
19
+ adjust?: boolean;
20
+ }
21
+ /** Result of {@link cohensD} and {@link hedgesG}. */
22
+ export interface CohensDResult {
23
+ /** `"Cohens_d"` or `"Hedges_g"`. */
24
+ name: "Cohens_d" | "Hedges_g";
25
+ value: number;
26
+ /** Confidence level (absent without an interval). */
27
+ ci?: number;
28
+ ciLow?: number;
29
+ ciHigh?: number;
30
+ /** effectsize's warnings. */
31
+ warnings: string[];
32
+ }
33
+ /**
34
+ * Cohen's d: the standardized difference of means of two samples (pooled or averaged standard deviation), of paired
35
+ * samples, or of one sample against `mu`, with a confidence interval from the noncentral t distribution. Equivalent
36
+ * to effectsize's `cohens_d()`.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * cohensD([5.1, 4.9, 6.2, 5.8], [4.1, 4.5, 3.9, 5.0]).value; // 2.049693834034246
41
+ * ```
42
+ */
43
+ export declare function cohensD(x: Sample, y?: Sample, options?: CohensDOptions): CohensDResult;
44
+ /**
45
+ * Hedges' g: Cohen's d and its interval multiplied by the small-sample correction J(df). Equivalent to effectsize's
46
+ * `hedges_g()`.
47
+ */
48
+ export declare function hedgesG(x: Sample, y?: Sample, options?: Omit<CohensDOptions, "adjust">): CohensDResult;
49
+ /** Options for {@link etaSquared}, {@link omegaSquared} and {@link epsilonSquared}. */
50
+ export interface AnovaEffectSizeOptions {
51
+ /**
52
+ * Partial effect sizes (default `true`). A table with a single term always gives the non-partial one (not so for
53
+ * models with error strata).
54
+ */
55
+ partial?: boolean;
56
+ /** Confidence level of the interval, or `null` for no interval. Default `0.95`. */
57
+ ci?: number | null;
58
+ /** `"greater"` (default: the interval is [lower, 1]), `"two.sided"` or `"less"` ([0, upper]). */
59
+ alternative?: Alternative | (string & {});
60
+ }
61
+ /** Options for {@link etaSquared}. */
62
+ export interface EtaSquaredOptions extends AnovaEffectSizeOptions {
63
+ /**
64
+ * Generalized eta squared: `true` (all factors manipulated) or the names of the observed factors. Default
65
+ * `false`.
66
+ */
67
+ generalized?: boolean | readonly string[];
68
+ }
69
+ /** Result of the ANOVA effect sizes: one row per term. */
70
+ export interface AnovaEffectSizeTable {
71
+ /** effectsize's columns: the effect size (`"Eta2_partial"`, `"Omega2"`, ...), then `"CI"`, `"CI_low"`, `"CI_high"`. */
72
+ colNames: string[];
73
+ /** The terms. */
74
+ rowNames: string[];
75
+ /** One array per term. */
76
+ table: number[][];
77
+ /** For aov with `Error()`: the error stratum of each row (`"id"`, `"id:W"`, `"Within"`). */
78
+ groups?: string[];
79
+ /** effectsize's warnings. */
80
+ warnings: string[];
81
+ }
82
+ /**
83
+ * A model of the ANOVA effect sizes: a table of `anova()` or `Anova()`, a fit from `lm()` or `aov()` (also with
84
+ * `Error()`), the `aovSummary()` of an `aov()` fit with `Error()`, or a result of `aovEz()`.
85
+ */
86
+ export type AnovaEffectSizeModel = AnovaTable | LmFormulaResult | AovStrataFit | AovStrataSummary | AovEzResult;
87
+ /**
88
+ * Eta squared of the terms of an analysis-of-variance table (partial by default, or generalized), with confidence
89
+ * intervals from the noncentral F distribution. Equivalent to effectsize's `eta_squared()` for a table of
90
+ * `anova()` or `Anova()`; a fit from `lm()` with a formula is replaced by its `anova()` table.
91
+ *
92
+ * Repeated measures: for a fit of `aov()` with an `Error()` term (or its {@link aovSummary}) each term is measured
93
+ * against the residual of its error stratum, the totals add up all strata, and the result has the stratum of each
94
+ * row in `groups`; for a result of {@link aovEz}, the same from car's univariate tests (rows as afex's table).
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * etaSquared(anova(lm("y ~ g", data))).colNames; // ["Eta2", "CI", "CI_low", "CI_high"]
99
+ * etaSquared(aov("y ~ W + Error(id/W)", long)).groups; // ["id:W"]
100
+ * ```
101
+ */
102
+ export declare function etaSquared(model: AnovaEffectSizeModel, options?: EtaSquaredOptions): AnovaEffectSizeTable;
103
+ /**
104
+ * Omega squared of the terms of an analysis-of-variance table, also of repeated-measures designs (see
105
+ * {@link etaSquared}). Equivalent to effectsize's `omega_squared()`.
106
+ */
107
+ export declare function omegaSquared(model: AnovaEffectSizeModel, options?: AnovaEffectSizeOptions): AnovaEffectSizeTable;
108
+ /**
109
+ * Epsilon squared of the terms of an analysis-of-variance table, also of repeated-measures designs (see
110
+ * {@link etaSquared}). Equivalent to effectsize's `epsilon_squared()`.
111
+ */
112
+ export declare function epsilonSquared(model: AnovaEffectSizeModel, options?: AnovaEffectSizeOptions): AnovaEffectSizeTable;
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import type { DataFrame } from "../models/modelFrame.js";
1
2
  import { type Alternative, type HTest, type Sample } from "./types.js";
2
3
  /** Options for {@link ksTest}. */
3
4
  export interface KsTestOptions {
@@ -27,5 +28,17 @@ export interface KsTestResult extends Omit<HTest, "alternative"> {
27
28
  * @param x Sample.
28
29
  * @param y A continuous distribution function, or a second sample.
29
30
  * @param options See {@link KsTestOptions}.
31
+ *
32
+ * There is also a formula form for two samples, `ksTest("y ~ g", data, options)` (next overload).
30
33
  */
31
34
  export declare function ksTest(x: Sample, y: Sample | ((q: number) => number), options?: KsTestOptions): KsTestResult;
35
+ /**
36
+ * Two-sample Kolmogorov-Smirnov test from a formula and a data frame. Equivalent to R's `ks.test(formula, data)`:
37
+ * `"y ~ g"` compares the two levels of `g` (the first level is `x`). Only the variables of the formula count: the
38
+ * rows where one of them is missing are dropped.
39
+ *
40
+ * @param formula `"y ~ g"`.
41
+ * @param data The data frame: an object of columns (`null` or `NaN` for a missing value).
42
+ * @param options See {@link KsTestOptions}.
43
+ */
44
+ export declare function ksTest(formula: string, data: DataFrame, options?: KsTestOptions): KsTestResult;
@@ -8,6 +8,7 @@
8
8
  // by counting lattice paths, asymptotic ones as for one sample with n replaced by m n / (m + n).
9
9
  import { pkolmogorovExact, pkolmogorovLimit, pkolmogorovOneSidedUpper } from "./core/kolmogorov.js";
10
10
  import { psmirnovUpper } from "./core/smirnov.js";
11
+ import { twoGroupData } from "./testFormula.js";
11
12
  import { matchAlternative } from "./types.js";
12
13
  function describe(alternative, oneSample) {
13
14
  if (alternative === "two.sided")
@@ -15,15 +16,11 @@ function describe(alternative, oneSample) {
15
16
  const where = alternative === "less" ? "below" : "above";
16
17
  return `the CDF of x lies ${where} ${oneSample ? "the null hypothesis" : "that of y"}`;
17
18
  }
18
- /**
19
- * Kolmogorov-Smirnov test. Equivalent to R's `ks.test()`, with a distribution function given as a function (for
20
- * example `(q) => pnorm(q)`) or a second sample. `NaN` values are dropped.
21
- *
22
- * @param x Sample.
23
- * @param y A continuous distribution function, or a second sample.
24
- * @param options See {@link KsTestOptions}.
25
- */
26
19
  export function ksTest(x, y, options = {}) {
20
+ if (typeof x === "string") {
21
+ const d = twoGroupData(x, y);
22
+ return ksTest(d.x, d.y, options);
23
+ }
27
24
  const xs = Array.from(x)
28
25
  .filter((v) => !Number.isNaN(v))
29
26
  .sort((a, b) => a - b);
@@ -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
+ }