@numero-uno-jpn/rstats 0.12.0 → 0.14.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 (119) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.ja.md +26 -17
  3. package/README.md +25 -16
  4. package/THIRD_PARTY_NOTICES.md +2 -2
  5. package/dist/chunks/{chunk-VQHEOBTM.js → chunk-6JRESWVF.js} +2 -2
  6. package/dist/chunks/chunk-7CPM3M6Q.js +2 -0
  7. package/dist/chunks/chunk-7PSGKKOP.js +2 -0
  8. package/dist/chunks/{chunk-LEIH4U5X.js → chunk-7T74KLE5.js} +2 -2
  9. package/dist/chunks/{chunk-XJQKSR52.js → chunk-A76XBA3D.js} +1 -1
  10. package/dist/chunks/chunk-ACE64PMM.js +3 -0
  11. package/dist/chunks/chunk-DCGBYO44.js +2 -0
  12. package/dist/chunks/chunk-DWNGNTS6.js +2 -0
  13. package/dist/chunks/chunk-FBDZ6B2G.js +2 -0
  14. package/dist/chunks/chunk-IBJ7RI44.js +2 -0
  15. package/dist/chunks/chunk-IGSR4GIF.js +2 -0
  16. package/dist/chunks/{chunk-6BH65HGN.js → chunk-NTETWLP3.js} +1 -1
  17. package/dist/chunks/chunk-Q4JF4QHS.js +2 -0
  18. package/dist/chunks/chunk-RZIWVCHO.js +2 -0
  19. package/dist/chunks/chunk-SD7ML5PE.js +2 -0
  20. package/dist/chunks/chunk-SZ357HRC.js +3 -0
  21. package/dist/chunks/chunk-WM33ADZV.js +2 -0
  22. package/dist/chunks/{chunk-OX3SBG5X.js → chunk-XCAMWVNO.js} +1 -1
  23. package/dist/chunks/chunk-YQLEXH2Y.js +3 -0
  24. package/dist/chunks/chunk-YTV3RFCA.js +2 -0
  25. package/dist/chunks/chunk-ZUESNU7W.js +2 -0
  26. package/dist/data/grouping.js +11 -4
  27. package/dist/descriptive/basic.js +57 -49
  28. package/dist/descriptive/cov.js +7 -2
  29. package/dist/descriptive/factanal.d.ts +16 -0
  30. package/dist/descriptive/factanal.js +26 -0
  31. package/dist/descriptive/hist.d.ts +8 -2
  32. package/dist/descriptive/hist.js +10 -2
  33. package/dist/descriptive/quantile.d.ts +8 -3
  34. package/dist/descriptive/quantile.js +10 -6
  35. package/dist/descriptive/table.d.ts +7 -5
  36. package/dist/descriptive/table.js +39 -22
  37. package/dist/descriptive.js +2 -2
  38. package/dist/distributions/beta.js +17 -0
  39. package/dist/distributions/binomial.js +3 -0
  40. package/dist/distributions/gamma.js +7 -0
  41. package/dist/distributions.js +2 -2
  42. package/dist/entries/mixed.d.ts +3 -1
  43. package/dist/entries/mixed.js +4 -1
  44. package/dist/entries/tests.d.ts +1 -1
  45. package/dist/htest/agreement.js +7 -2
  46. package/dist/htest/groups.js +7 -3
  47. package/dist/htest/mcnemarTest.js +6 -2
  48. package/dist/htest/pairwise.js +6 -3
  49. package/dist/htest/polycor.js +5 -3
  50. package/dist/htest/tTest.d.ts +3 -2
  51. package/dist/htest/tTest.js +6 -3
  52. package/dist/htest/trendTests.js +10 -5
  53. package/dist/internal/fround.d.ts +12 -0
  54. package/dist/internal/fround.js +89 -0
  55. package/dist/internal/levels.d.ts +11 -0
  56. package/dist/internal/levels.js +48 -0
  57. package/dist/internal/summary.d.ts +19 -1
  58. package/dist/internal/summary.js +69 -8
  59. package/dist/linalg/balance.d.ts +21 -0
  60. package/dist/linalg/balance.js +191 -0
  61. package/dist/linalg/eigen.d.ts +1 -1
  62. package/dist/linalg/eigen.js +8 -2
  63. package/dist/linalg/expm.d.ts +1 -11
  64. package/dist/linalg/expm.js +2 -158
  65. package/dist/linalg/kappa.d.ts +6 -2
  66. package/dist/linalg/kappa.js +16 -7
  67. package/dist/linalg/lu.d.ts +13 -2
  68. package/dist/linalg/lu.js +17 -3
  69. package/dist/linalg/qr.d.ts +4 -1
  70. package/dist/linalg/qr.js +2 -2
  71. package/dist/linalg.js +2 -2
  72. package/dist/mixed.js +4 -3
  73. package/dist/models/aovEz.js +6 -4
  74. package/dist/models/coxph.js +5 -2
  75. package/dist/models/glm.d.ts +4 -1
  76. package/dist/models/glmFamily.d.ts +1 -1
  77. package/dist/models/glmFamily.js +24 -2
  78. package/dist/models/lmer.d.ts +37 -4
  79. package/dist/models/lmer.js +18 -1
  80. package/dist/models/lmerAnova.d.ts +138 -0
  81. package/dist/models/lmerAnova.js +134 -0
  82. package/dist/models/lmerHypotheses.d.ts +105 -0
  83. package/dist/models/lmerHypotheses.js +303 -0
  84. package/dist/models/lmerTest.d.ts +233 -0
  85. package/dist/models/lmerTest.js +306 -0
  86. package/dist/models/mauchly.js +2 -1
  87. package/dist/models/mixedDerivatives.d.ts +27 -0
  88. package/dist/models/mixedDerivatives.js +342 -0
  89. package/dist/models/mixedDeviance.d.ts +112 -0
  90. package/dist/models/mixedDeviance.js +216 -86
  91. package/dist/models/mixedStructure.d.ts +5 -3
  92. package/dist/models/modelFrame.js +2 -1
  93. package/dist/models/modelMatrix.d.ts +10 -3
  94. package/dist/models/modelMatrix.js +23 -2
  95. package/dist/models/survival.js +5 -1
  96. package/dist/numerics/integrate.d.ts +1 -1
  97. package/dist/numerics/integrate.js +13 -3
  98. package/dist/numerics/interp.d.ts +1 -1
  99. package/dist/numerics/interp.js +3 -0
  100. package/dist/numerics.js +2 -2
  101. package/dist/rstats.js +14 -14
  102. package/dist/special/beta.js +10 -20
  103. package/dist/special.js +2 -2
  104. package/dist/tests.js +11 -12
  105. package/llms.txt +6 -1
  106. package/package.json +1 -1
  107. package/dist/chunks/chunk-3VMBBQLV.js +0 -3
  108. package/dist/chunks/chunk-4OKAZJJG.js +0 -3
  109. package/dist/chunks/chunk-ATC4F4BX.js +0 -2
  110. package/dist/chunks/chunk-EDH53DXN.js +0 -2
  111. package/dist/chunks/chunk-EZ2KD5NA.js +0 -2
  112. package/dist/chunks/chunk-GSPOO2G3.js +0 -2
  113. package/dist/chunks/chunk-K7AZ65H7.js +0 -2
  114. package/dist/chunks/chunk-SGZQDJRR.js +0 -2
  115. package/dist/chunks/chunk-UH2N3ZQW.js +0 -2
  116. package/dist/chunks/chunk-UV2MZYDQ.js +0 -2
  117. package/dist/chunks/chunk-WJQZZYOI.js +0 -2
  118. package/dist/chunks/chunk-WKEFHOFR.js +0 -2
  119. package/dist/chunks/chunk-WXC25OPJ.js +0 -2
@@ -9,6 +9,7 @@
9
9
  // orthogonal to the others for the hypothesis, the residual space for the error. The sums of squares are the traces
10
10
  // of these matrices times (P'P)^-1, and the epsilons and Mauchly's W follow from P'EP (src/models/ddMatrix.ts).
11
11
  import { pf1 } from "../distributions/f.js";
12
+ import { levelText, numberLevels } from "../internal/levels.js";
12
13
  import { eigen } from "../linalg/eigen.js";
13
14
  import { qr } from "../linalg/qr.js";
14
15
  import { ddAdd, ddDiv, ddDivNum, ddMul, ddMulNum } from "../special/dd.js";
@@ -27,7 +28,7 @@ function column(data, name) {
27
28
  throw new Error(`object '${name}' not found`);
28
29
  return Array.from(c);
29
30
  }
30
- const label = (v) => (typeof v === "boolean" ? (v ? "TRUE" : "FALSE") : String(v));
31
+ const label = (v) => (typeof v === "boolean" ? (v ? "TRUE" : "FALSE") : levelText(v));
31
32
  /** Levels sorted (numbers as numbers, strings by code point) */
32
33
  function sortedLevels(values) {
33
34
  const distinct = [...new Set(values)];
@@ -95,14 +96,15 @@ export function aovEz(data, options) {
95
96
  const observed = list(options.observed);
96
97
  const warnings = [];
97
98
  // 1. the columns as factors
98
- const ids = column(data, options.id).map(label);
99
+ // (the id and factor columns as R's factor() makes them: numbers with the same 15-digit text are one level)
100
+ const ids = numberLevels(column(data, options.id)).map(label);
99
101
  const dv = column(data, options.dv).map((v) => {
100
102
  if (typeof v !== "number")
101
103
  throw new TypeError(`the response '${options.dv}' must be numeric`);
102
104
  return v;
103
105
  });
104
- const bcols = between.map((b) => column(data, b));
105
- const wcols = within.map((w) => column(data, w));
106
+ const bcols = between.map((b) => numberLevels(column(data, b)));
107
+ const wcols = within.map((w) => numberLevels(column(data, w)));
106
108
  const nrow = ids.length;
107
109
  for (const c of [dv, ...bcols, ...wcols])
108
110
  if (c.length !== nrow)
@@ -11,6 +11,7 @@
11
11
  // (R's NA) coefficients.
12
12
  import { pchisq } from "../distributions/chisq.js";
13
13
  import { qnorm } from "../distributions/normal.js";
14
+ import { numberLevels } from "../internal/levels.js";
14
15
  import { Warnings } from "./glmFamily.js";
15
16
  const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
16
17
  const compareLabels = (a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
@@ -310,10 +311,12 @@ export function coxph(time, status, x, options = {}) {
310
311
  const mergedTime = mergeTiedTimes(keep.map((i) => time[i]));
311
312
  let stratumOf = new Array(n).fill(0);
312
313
  if (strata !== undefined) {
313
- const labels = Array.from(new Set(keep.map((i) => strata[i]))).sort(compareLabels);
314
+ // numeric labels with the same 15-digit text are one stratum, as in R's factor()
315
+ const sl = numberLevels(strata);
316
+ const labels = Array.from(new Set(keep.map((i) => sl[i]))).sort(compareLabels);
314
317
  const index = new Map();
315
318
  labels.forEach((l, k) => index.set(l, k));
316
- stratumOf = keep.map((i) => index.get(strata[i]));
319
+ stratumOf = keep.map((i) => index.get(sl[i]));
317
320
  }
318
321
  const order = Array.from({ length: n }, (_, k) => k).sort((a, b) => stratumOf[a] - stratumOf[b] || mergedTime[a] - mergedTime[b] || a - b);
319
322
  // 2. centring and scaling (sums over the sorted observations)
@@ -15,7 +15,10 @@ export interface GlmOptions {
15
15
  * as R's `quasi(link = "log", variance = "mu^2")`.
16
16
  */
17
17
  family?: GlmFamilyName | GlmFamilySpec;
18
- /** The link (overrides the family object's): a name such as `"logit"` or `{ power: lambda }` (quasi only). */
18
+ /**
19
+ * The link (overrides the family object's): a name such as `"logit"` or `{ power: lambda }` (quasi only). As in R,
20
+ * any named link may be used with any family except `quasi`, which takes only its own list.
21
+ */
19
22
  link?: GlmLink;
20
23
  /** Prior weights (non-negative). */
21
24
  weights?: Sample;
@@ -33,7 +33,7 @@ export type QuasiVariance = "constant" | "mu(1-mu)" | "mu" | "mu^2" | "mu^3";
33
33
  export interface GlmFamilySpec {
34
34
  /** The family's name, such as `"binomial"`. */
35
35
  family: GlmFamilyName;
36
- /** The link. Default: the family's default (the first of its allowed links). */
36
+ /** The link: any named link (for `quasi`, one of its own list). Default: the family's default link. */
37
37
  link?: GlmLink;
38
38
  /** Variance function of `quasi`. Default `"constant"`. */
39
39
  variance?: QuasiVariance;
@@ -49,6 +49,24 @@ function sqrtWarn(x) {
49
49
  currentWarnings?.add("NaNs produced");
50
50
  return Math.sqrt(x);
51
51
  }
52
+ /** A number as C's printf("%g") writes it: 6 significant digits, fixed or scientific, trailing zeros dropped */
53
+ function formatG(v) {
54
+ if (!Number.isFinite(v))
55
+ return Number.isNaN(v) ? "nan" : v > 0 ? "inf" : "-inf";
56
+ const sci = v.toExponential(5);
57
+ const e = Number(sci.slice(sci.indexOf("e") + 1));
58
+ if (e >= -4 && e < 6)
59
+ return v.toFixed(5 - e).replace(/\.?0+$/, "");
60
+ const [mant, exp] = sci.split("e");
61
+ return `${mant.replace(/\.?0+$/, "")}e${e < 0 ? "-" : "+"}${String(Math.abs(Number(exp))).padStart(2, "0")}`;
62
+ }
63
+ /** The logit link function: a mean outside [0, 1] is an error, as in R (0 and 1 give -Inf and Inf) */
64
+ function logit(m) {
65
+ if (m < 0 || m > 1)
66
+ throw new RangeError(`Value ${formatG(m)} out of range (0, 1)`);
67
+ return Math.log(m / (1 - m));
68
+ }
69
+ const LINK_NAMES = ["logit", "probit", "cauchit", "cloglog", "identity", "log", "sqrt", "1/mu^2", "inverse"];
52
70
  function namedLink(name) {
53
71
  switch (name) {
54
72
  case "identity":
@@ -82,7 +100,7 @@ function namedLink(name) {
82
100
  case "logit":
83
101
  return {
84
102
  name,
85
- link: (m) => Math.log(m / (1 - m)),
103
+ link: logit,
86
104
  linkinv: (e) => {
87
105
  const t = e < -30 ? EPS : e > 30 ? 1 / EPS : Math.exp(e);
88
106
  return t / (1 + t);
@@ -194,9 +212,13 @@ export function makeFamily(family, link) {
194
212
  lf = powerLink(lk.power);
195
213
  }
196
214
  else {
197
- if (!allowed.includes(lk)) {
215
+ // As in R, a link given by name may be any link R knows, whatever the family; the family's list of usual links
216
+ // restricts only the quasi family
217
+ if (name === "quasi" && !allowed.includes(lk)) {
198
218
  throw new RangeError(`link "${lk}" not available for ${name} family; available links are ${allowed.map((a) => `'${a}'`).join(", ")}`);
199
219
  }
220
+ if (!LINK_NAMES.includes(lk))
221
+ throw new RangeError(`\u2018${lk}\u2019 link not recognised`);
200
222
  lf = namedLink(lk);
201
223
  }
202
224
  if (spec.variance !== undefined && name !== "quasi")
@@ -1,6 +1,13 @@
1
1
  import type { DataFrame } from "./modelFrame.js";
2
2
  import type { ContrastName } from "./modelMatrix.js";
3
3
  import { type MixedModelStructure } from "./mixedStructure.js";
4
+ /**
5
+ * A contrast of a factor of lmer's fixed effects: R's `contr.treatment`, `contr.sum`, `contr.helmert` or `contr.poly`
6
+ * (orthogonal polynomials in the level scores 1, 2, ..., columns `.L`, `.Q`, `.C`, `^4`, ...).
7
+ *
8
+ * @category Mixed models
9
+ */
10
+ export type LmerContrastName = ContrastName | "contr.poly";
4
11
  /**
5
12
  * Options of {@link lmer}.
6
13
  *
@@ -10,11 +17,12 @@ export interface LmerOptions {
10
17
  /** Whether to minimise the REML criterion (default `true`) or the ML deviance (`false`). */
11
18
  REML?: boolean;
12
19
  /**
13
- * A contrast per factor of the fixed-effects part (default `"contr.treatment"`); the random-effects terms always use
14
- * treatment contrasts. A name that is not a variable of the fixed-effects part (a grouping variable alone included)
15
- * gives the warning `variable 'B' is absent, its contrast will be ignored`.
20
+ * A contrast per factor of the fixed-effects part: `"contr.treatment"` (default), `"contr.sum"`, `"contr.helmert"` or
21
+ * `"contr.poly"` (see {@link LmerContrastName}); the random-effects terms always use treatment contrasts. A name that
22
+ * is not a variable of the fixed-effects part (a grouping variable alone included) gives the warning
23
+ * `variable 'B' is absent, its contrast will be ignored`.
16
24
  */
17
- contrasts?: Record<string, ContrastName>;
25
+ contrasts?: Record<string, LmerContrastName>;
18
26
  /** The order of the levels of a factor (`{ A: ["c", "a", "b"] }`), as `factor(x, levels = ...)` in R. */
19
27
  levels?: Record<string, readonly string[]>;
20
28
  }
@@ -155,6 +163,31 @@ export type MixedCriterion = (s: MixedModelStructure, theta: readonly number[],
155
163
  * @category Mixed models
156
164
  */
157
165
  export declare function lmer(formula: string, data: DataFrame, options?: LmerOptions): LmerResult;
166
+ /**
167
+ * What a fit by {@link lmer} was made from and with (internal: not exported from the package), for the functions that
168
+ * work on a fit beyond its result fields (lmerTest's tests in src/models/lmerTest.ts, the ANOVA tables, the comparison
169
+ * of fits): they need the model's structure, the data object (model comparison requires the same object), the options
170
+ * (to refit, for example by maximum likelihood) and the criterion (so that a refit uses the same one).
171
+ */
172
+ export interface LmerInternals {
173
+ /** The structure of the model (X, Z, the terms, the layout of θ, the model frame's rows) */
174
+ structure: MixedModelStructure;
175
+ /** The data frame given to lmer (the same object, not a copy) */
176
+ data: DataFrame;
177
+ /** The options given to lmer (a copy) */
178
+ options: LmerOptions;
179
+ /** Whether the REML criterion was minimised */
180
+ reml: boolean;
181
+ /** The criterion with its gradient that was minimised (the sparse one, or the injected one of the regression test) */
182
+ criterion: MixedCriterion;
183
+ /** The estimate θ̂ (a copy, unaffected by changes to the result's `theta`) */
184
+ theta: number[];
185
+ }
186
+ /**
187
+ * The internals of a fit (see {@link LmerInternals}). Internal. Throws a TypeError for an object that is not a result
188
+ * returned by {@link lmer}.
189
+ */
190
+ export declare function lmerInternals(fit: LmerResult): LmerInternals;
158
191
  /**
159
192
  * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
160
193
  * test of the sparse computation fits with the dense reference implementation through it.
@@ -367,6 +367,21 @@ function minimiseCriterion(s, reml, criterion) {
367
367
  export function lmer(formula, data, options = {}) {
368
368
  return lmerWithCriterion(formula, data, options, sparseCriterion);
369
369
  }
370
+ /**
371
+ * The internals of every result returned by {@link lmer} (and {@link lmerWithCriterion}), keyed by the result object
372
+ * itself: a copy of a result (`{ ...fit }`) has none.
373
+ */
374
+ const internalsByFit = new WeakMap();
375
+ /**
376
+ * The internals of a fit (see {@link LmerInternals}). Internal. Throws a TypeError for an object that is not a result
377
+ * returned by {@link lmer}.
378
+ */
379
+ export function lmerInternals(fit) {
380
+ const internals = typeof fit === "object" && fit !== null ? internalsByFit.get(fit) : undefined;
381
+ if (internals === undefined)
382
+ throw new TypeError("fit must be a result returned by lmer (not a copy of one)");
383
+ return internals;
384
+ }
370
385
  /**
371
386
  * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
372
387
  * test of the sparse computation fits with the dense reference implementation through it.
@@ -429,7 +444,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
429
444
  const messages = [...s.messages];
430
445
  if (singular)
431
446
  messages.push("boundary (singular) fit: see help('isSingular')");
432
- return {
447
+ const result = {
433
448
  formula,
434
449
  REML: reml,
435
450
  nObs: n,
@@ -454,4 +469,6 @@ export function lmerWithCriterion(formula, data, options, criterion) {
454
469
  messages,
455
470
  warnings: [...s.warnings],
456
471
  };
472
+ internalsByFit.set(result, { structure: s, data, options: { ...options }, reml, criterion, theta: [...theta] });
473
+ return result;
457
474
  }
@@ -0,0 +1,138 @@
1
+ import { Warnings } from "./glmFamily.js";
2
+ import { type LmerResult } from "./lmer.js";
3
+ import { type HypothesisType, type LmerHypotheses } from "./lmerHypotheses.js";
4
+ import { type LmerFRow, type LmerSatterthwaite } from "./lmerTest.js";
5
+ /**
6
+ * Options of {@link lmerAnova} for one fit.
7
+ *
8
+ * @category Mixed models
9
+ */
10
+ export interface LmerAnovaOptions {
11
+ /** The type of the sums of squares: `"III"` (default), `"II"` or `"I"` (also `3`, `2`, `1`). */
12
+ type?: LmerAnovaType | 1 | 2 | 3;
13
+ }
14
+ /**
15
+ * Result of {@link lmerAnova} for one fit: lmerTest's ANOVA table, one row per term of the fixed effects.
16
+ *
17
+ * @category Mixed models
18
+ */
19
+ export interface LmerAnovaTable {
20
+ /** The type of the sums of squares. */
21
+ type: LmerAnovaType;
22
+ /** The terms (R's row names), in the order of the formula's terms; terms without a test come last. */
23
+ terms: string[];
24
+ /** R's `Sum Sq`: F σ² NumDF. */
25
+ sumSq: number[];
26
+ /** R's `Mean Sq`: F σ². */
27
+ meanSq: number[];
28
+ /** R's `NumDF`. */
29
+ numDF: number[];
30
+ /** R's `DenDF`: Satterthwaite's denominator degrees of freedom. */
31
+ denDF: number[];
32
+ /** R's `F value`. */
33
+ F: number[];
34
+ /** R's `Pr(>F)`. */
35
+ pValue: number[];
36
+ /** R's messages (Type III: `Missing cells for: ...`). */
37
+ messages: string[];
38
+ /** R's warnings (about the eigenvalues of the Hessian of the deviance in the variance parameters). */
39
+ warnings: string[];
40
+ }
41
+ /**
42
+ * Options of {@link lmerAnova} for several fits.
43
+ *
44
+ * @category Mixed models
45
+ */
46
+ export interface LmerCompareOptions {
47
+ /** Refit the REML fits by maximum likelihood before comparing them (default `true`). */
48
+ refit?: boolean;
49
+ /** The names of the models, in the order given (default `"MODEL1"`, `"MODEL2"`, ...). */
50
+ names?: readonly string[];
51
+ }
52
+ /**
53
+ * Result of {@link lmerAnova} for several fits: lme4's comparison table, one row per model, sorted by the number of
54
+ * parameters.
55
+ *
56
+ * @category Mixed models
57
+ */
58
+ export interface LmerCompareTable {
59
+ /** The models' names (R's row names), in the order of the rows. */
60
+ names: string[];
61
+ /** The number of parameters of each model (fixed effects, θ and σ). */
62
+ npar: number[];
63
+ /** Akaike's information criterion, −2 logLik + 2 npar. */
64
+ AIC: number[];
65
+ /** Schwarz's criterion, −2 logLik + log(n) npar. */
66
+ BIC: number[];
67
+ /** The log-likelihood (of the ML refit, or the fit's own with `refit: false`). */
68
+ logLik: number[];
69
+ /** −2 logLik (R's `-2*log(L)`). */
70
+ deviance: number[];
71
+ /** The likelihood-ratio statistic against the row before (NaN in the first row). */
72
+ Chisq: number[];
73
+ /** The difference of npar from the row before (NaN in the first row). */
74
+ Df: number[];
75
+ /** R's `Pr(>Chisq)` (NaN in the first row and where Df is 0). */
76
+ pValue: number[];
77
+ /** R's messages (`refitting model(s) with ML (instead of REML)`). */
78
+ messages: string[];
79
+ /** R's warnings (duplicated names, a mix of REML and ML fits without refitting). */
80
+ warnings: string[];
81
+ }
82
+ /**
83
+ * The type of the sums of squares of an ANOVA table of {@link lmerAnova}.
84
+ *
85
+ * @category Mixed models
86
+ */
87
+ export type LmerAnovaType = "I" | "II" | "III";
88
+ /** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
89
+ export declare function anovaHypotheses(fit: LmerResult, type: HypothesisType): {
90
+ hypotheses: LmerHypotheses;
91
+ termLabels: string[];
92
+ };
93
+ /** The rows of an ANOVA table from the hypotheses and given Satterthwaite quantities (internal) */
94
+ export declare function anovaRowsOf(s: LmerSatterthwaite, { hypotheses }: LmerHypotheses, termLabels: readonly string[], warnings: Warnings): {
95
+ terms: string[];
96
+ rows: LmerFRow[];
97
+ };
98
+ /**
99
+ * The ANOVA table of a linear mixed model fitted by {@link lmer}, with Satterthwaite's denominator degrees of freedom
100
+ * (lmerTest's `anova()`), or, given an array of fits, the likelihood-ratio comparison of the models (lme4's
101
+ * `anova()` of several fits). Equivalent to `lmerTest::anova()` in R.
102
+ *
103
+ * For one fit: each term of the fixed effects is tested jointly (an F-test of its hypothesis matrix, of Type III by
104
+ * default, II or I as in lmerTest; see {@link lmerContest} for the test). Type III with an empty cell of an
105
+ * interaction gives the message `Missing cells for: ...`. A term without a test is listed last, with NaN.
106
+ *
107
+ * For several fits (fitted to the same data object, with the same rows): REML fits are first refitted by maximum
108
+ * likelihood (unless `refit: false`), the models are sorted by their number of parameters, and each is compared with
109
+ * the one before by the likelihood-ratio test.
110
+ *
111
+ * @param fit A result of {@link lmer} (the object it returned, not a copy), or an array of at least two.
112
+ * @param options For one fit `type`; for several `refit` and `names`.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * // R: anova(lmerTest::lmer(y ~ x * f + (1 | g), data))
117
+ * const data = {
118
+ * y: [3.1, 4.0, 5.2, 6.8, 7.1, 8.3, 2.2, 3.5, 3.9, 5.9, 6.1, 7.4, 4.4, 5.0, 6.9, 3.0, 4.1, 4.9],
119
+ * x: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
120
+ * f: ["u", "u", "v", "v", "u", "v", "u", "v", "v", "u", "v", "u", "v", "u", "u", "v", "u", "v"],
121
+ * g: ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d", "d", "e", "e", "e", "f", "f", "f"],
122
+ * };
123
+ * const fit = lmer("y ~ x * f + (1 | g)", data);
124
+ * const t = lmerAnova(fit);
125
+ * t.terms; // ["x", "f", "x:f"]
126
+ * t.numDF; // [1, 1, 1]
127
+ * t.F; // [82.027, 0.44207, 0.53285]
128
+ * // R: anova(lme4::lmer(y ~ x + (1 | g), data), fit)
129
+ * const c = lmerAnova([lmer("y ~ x + (1 | g)", data), fit], { names: ["small", "full"] });
130
+ * c.npar; // [4, 6]
131
+ * c.Chisq; // [NaN, 0.6817]
132
+ * c.messages; // ["refitting model(s) with ML (instead of REML)"]
133
+ * ```
134
+ *
135
+ * @category Mixed models
136
+ */
137
+ export declare function lmerAnova(fit: LmerResult, options?: LmerAnovaOptions): LmerAnovaTable;
138
+ export declare function lmerAnova(fits: readonly LmerResult[], options?: LmerCompareOptions): LmerCompareTable;
@@ -0,0 +1,134 @@
1
+ // ANOVA tables of linear mixed models fitted by lmer (src/models/lmer.ts): lmerTest's Type I, II and III tables of one
2
+ // fit (each term's hypothesis tested jointly with Satterthwaite's denominator degrees of freedom), and lme4's
3
+ // likelihood-ratio comparison of several fits.
4
+ //
5
+ // Written for rStats.js (no ported code) from oracle/lmertest-behaviour.md (sections 2 and 3). The hypothesis
6
+ // matrices come from src/models/lmerHypotheses.ts, the F-tests from src/models/lmerTest.ts; the comparison refits REML
7
+ // fits by maximum likelihood with lmer's own minimiser (the exact ML optimum).
8
+ import { pgamma1 } from "../distributions/gamma.js";
9
+ import { Warnings } from "./glmFamily.js";
10
+ import { lmerInternals, lmerWithCriterion } from "./lmer.js";
11
+ import { fixedEffectsDescription, lmerHypotheses } from "./lmerHypotheses.js";
12
+ import { fTestOf, lmerSatterthwaite } from "./lmerTest.js";
13
+ const TYPES = { I: "I", II: "II", III: "III", 1: "I", 2: "II", 3: "III" };
14
+ /** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
15
+ export function anovaHypotheses(fit, type) {
16
+ const { structure, data, options } = lmerInternals(fit);
17
+ const descOptions = {};
18
+ if (options.contrasts !== undefined)
19
+ descOptions.contrasts = options.contrasts;
20
+ if (options.levels !== undefined)
21
+ descOptions.levels = options.levels;
22
+ const desc = fixedEffectsDescription(fit.formula, data, descOptions);
23
+ if (desc.colNames.length !== structure.xColNames.length || desc.colNames.some((c, j) => c !== structure.xColNames[j])) {
24
+ throw new Error("lmerAnova: the columns of the hypotheses differ from the fit's fixed effects");
25
+ }
26
+ // an intercept-only model (or one without fixed effects) has an empty table
27
+ if (desc.terms.length === 0)
28
+ return { hypotheses: { hypotheses: [], messages: [] }, termLabels: [] };
29
+ return { hypotheses: lmerHypotheses(desc, type), termLabels: desc.terms.map((t) => t.label) };
30
+ }
31
+ /** The rows of an ANOVA table from the hypotheses and given Satterthwaite quantities (internal) */
32
+ export function anovaRowsOf(s, { hypotheses }, termLabels, warnings) {
33
+ const terms = [];
34
+ const rows = [];
35
+ for (const h of hypotheses) {
36
+ const row = h.values.length === 0 ? undefined : fTestOf(s, h.values, undefined, warnings);
37
+ if (row === undefined)
38
+ continue;
39
+ terms.push(h.term);
40
+ rows.push(row);
41
+ }
42
+ for (const label of termLabels) {
43
+ if (terms.includes(label))
44
+ continue;
45
+ terms.push(label);
46
+ rows.push({ sumSq: NaN, meanSq: NaN, numDF: NaN, denDF: NaN, F: NaN, pValue: NaN });
47
+ }
48
+ return { terms, rows };
49
+ }
50
+ function anovaOfFit(fit, options) {
51
+ const type = TYPES[String(options.type ?? "III")];
52
+ if (type === undefined)
53
+ throw new RangeError(`type must be "I", "II" or "III", not ${JSON.stringify(options.type)}`);
54
+ const { hypotheses, termLabels } = anovaHypotheses(fit, type);
55
+ const s = lmerSatterthwaite(fit);
56
+ const warnings = new Warnings();
57
+ s.warnings.forEach((w) => warnings.add(w));
58
+ const { terms, rows } = anovaRowsOf(s, hypotheses, termLabels, warnings);
59
+ const column = (k) => rows.map((r) => r[k]);
60
+ return {
61
+ type,
62
+ terms,
63
+ sumSq: column("sumSq"),
64
+ meanSq: column("meanSq"),
65
+ numDF: column("numDF"),
66
+ denDF: column("denDF"),
67
+ F: column("F"),
68
+ pValue: column("pValue"),
69
+ messages: [...hypotheses.messages],
70
+ warnings: warnings.list,
71
+ };
72
+ }
73
+ function compareFits(fits, options) {
74
+ if (fits.length < 2)
75
+ throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
76
+ const internals = fits.map(lmerInternals);
77
+ if (fits.some((f) => f.nObs !== fits[0].nObs))
78
+ throw new Error("models were not all fitted to the same size of dataset");
79
+ if (internals.some((i) => i.data !== internals[0].data))
80
+ throw new Error("all models must be fit to the same data object");
81
+ const warnings = new Warnings();
82
+ const messages = [];
83
+ let names = fits.map((_, i) => `MODEL${i + 1}`);
84
+ if (options.names !== undefined) {
85
+ if (options.names.length !== fits.length || options.names.some((n) => typeof n !== "string")) {
86
+ throw new TypeError(`names must be ${fits.length} strings, one per fit`);
87
+ }
88
+ if (new Set(options.names).size === options.names.length)
89
+ names = [...options.names];
90
+ else
91
+ warnings.add("failed to find model names, assigning generic names");
92
+ }
93
+ const refit = options.refit ?? true;
94
+ let logLik;
95
+ if (refit) {
96
+ if (fits.some((f) => f.REML))
97
+ messages.push("refitting model(s) with ML (instead of REML)");
98
+ logLik = fits.map((f, i) => {
99
+ if (!f.REML)
100
+ return f.logLik;
101
+ const { data, options: o, criterion } = internals[i];
102
+ return lmerWithCriterion(f.formula, data, { ...o, REML: false }, criterion).logLik;
103
+ });
104
+ }
105
+ else {
106
+ if (fits.some((f) => f.REML) && fits.some((f) => !f.REML))
107
+ warnings.add("some models fit with REML = TRUE, some not");
108
+ logLik = fits.map((f) => f.logLik);
109
+ }
110
+ // sorted by the number of parameters (stable)
111
+ const order = fits.map((_, i) => i).sort((a, b) => fits[a].df - fits[b].df || a - b);
112
+ const n = fits[0].nObs;
113
+ const npar = order.map((i) => fits[i].df);
114
+ const ll = order.map((i) => logLik[i]);
115
+ const Chisq = ll.map((v, k) => (k === 0 ? NaN : 2 * Math.max(0, v - ll[k - 1])));
116
+ const Df = npar.map((v, k) => (k === 0 ? NaN : v - npar[k - 1]));
117
+ const pValue = Chisq.map((x, k) => (k === 0 || Df[k] === 0 ? NaN : pgamma1(x, Df[k] / 2, 2, false, false)));
118
+ return {
119
+ names: order.map((i) => names[i]),
120
+ npar,
121
+ AIC: ll.map((v, k) => -2 * v + 2 * npar[k]),
122
+ BIC: ll.map((v, k) => -2 * v + Math.log(n) * npar[k]),
123
+ logLik: ll,
124
+ deviance: ll.map((v) => -2 * v),
125
+ Chisq,
126
+ Df,
127
+ pValue,
128
+ messages,
129
+ warnings: warnings.list,
130
+ };
131
+ }
132
+ export function lmerAnova(fit, options = {}) {
133
+ return Array.isArray(fit) ? compareFits(fit, options) : anovaOfFit(fit, options);
134
+ }
@@ -0,0 +1,105 @@
1
+ import type { DataFrame, FrameVariable } from "./modelFrame.js";
2
+ import { type DesignContrast } from "./modelMatrix.js";
3
+ /** A term of the fixed-effects formula. */
4
+ export interface FixedEffectsTerm {
5
+ /** The term's label, such as `"A"`, `"x:f"`. */
6
+ label: string;
7
+ /** Its variables, in the order of the label. */
8
+ variables: string[];
9
+ }
10
+ /**
11
+ * The fixed-effects design of a mixed model, everything the hypothesis matrices depend on.
12
+ */
13
+ export interface FixedEffectsDescription {
14
+ /** The model matrix X (array of rows, the rows used), aliased columns dropped. */
15
+ x: number[][];
16
+ /** Names of the columns of X, such as `"(Intercept)"`, `"Aa2"`, `"x:flo"`. */
17
+ colNames: string[];
18
+ /** The term of each column of X: 0 for the intercept, k + 1 for `terms[k]`. */
19
+ assign: number[];
20
+ /** Whether the model has an intercept. */
21
+ intercept: boolean;
22
+ /** The terms of the fixed-effects formula, in the order of the formula's terms (sorted by order). */
23
+ terms: FixedEffectsTerm[];
24
+ /**
25
+ * The variables of the terms, in the order of the formula (that of their first appearance), each with its
26
+ * column of the model frame (rows used): numeric values, or a factor's levels and codes.
27
+ */
28
+ variables: {
29
+ name: string;
30
+ frame: FrameVariable;
31
+ }[];
32
+ /** The contrast of each factor among `variables` (`"contr.treatment"` unless another was given). */
33
+ contrasts: Record<string, DesignContrast>;
34
+ }
35
+ /** Options of {@link fixedEffectsDescription}: those of lmer that shape X. */
36
+ export interface FixedEffectsDescriptionOptions {
37
+ /** A contrast per factor of the fixed-effects part (default `"contr.treatment"`). */
38
+ contrasts?: Record<string, DesignContrast>;
39
+ /** The order of the levels of a factor. */
40
+ levels?: Record<string, readonly string[]>;
41
+ }
42
+ /** The hypothesis matrix of one term. */
43
+ export interface TermHypothesis {
44
+ /** The term's label. */
45
+ term: string;
46
+ /** The names of the rows (columns of X for Types I and II, of X with treatment contrasts for Type III). */
47
+ rows: string[];
48
+ /** The names of the columns: the columns of X. */
49
+ columns: string[];
50
+ /** The matrix (array of rows). */
51
+ values: number[][];
52
+ }
53
+ /** The type of an ANOVA table. */
54
+ export type HypothesisType = "I" | "II" | "III";
55
+ /** Result of {@link lmerHypotheses}. */
56
+ export interface LmerHypotheses {
57
+ /** One hypothesis per term with columns in X, in the order of the terms (a term with no rows included). */
58
+ hypotheses: TermHypothesis[];
59
+ /** R's messages (Type III: "Missing cells for: ..."). */
60
+ messages: string[];
61
+ }
62
+ /**
63
+ * The fixed-effects design of an lmer fit, from lmer's inputs: the formula's fixed part coded on the model frame of
64
+ * the whole formula (rows with a missing value in any of its variables dropped, unused levels dropped), the
65
+ * contrasts given, and the aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
66
+ */
67
+ export declare function fixedEffectsDescription(formula: string, data: DataFrame, options?: FixedEffectsDescriptionOptions): FixedEffectsDescription;
68
+ /**
69
+ * The Doolittle factorisation S = L U of a symmetric matrix without pivoting: L unit lower triangular, U upper
70
+ * triangular; a column of L below a pivot |U_ii| < 1e-6 is 0, and entries below 1e-6 in absolute value are set to 0
71
+ * at the end.
72
+ */
73
+ export declare function doolittle(s: readonly (readonly number[])[]): {
74
+ L: number[][];
75
+ U: number[][];
76
+ };
77
+ /**
78
+ * For each term, the indices of the terms that contain it: those whose variables include all of its own and at
79
+ * least one more, with the same numeric variables (in the order of the terms).
80
+ */
81
+ export declare function containingTerms(desc: FixedEffectsDescription): number[][];
82
+ /**
83
+ * The full-dummy matrix rdX: an intercept column (with an intercept), then for each term the columns of its model
84
+ * matrix with every level of each factor (the first variable varying fastest, numeric variables multiplying), and
85
+ * the "Missing cells" message for its columns that are all 0.
86
+ */
87
+ export declare function fullDummyMatrix(desc: FixedEffectsDescription): {
88
+ x: number[][];
89
+ colNames: string[];
90
+ messages: string[];
91
+ };
92
+ /**
93
+ * X remade from the same terms and model frame with treatment contrasts for every factor, restricted (if it is not
94
+ * of full column rank) to the first r pivot columns of its pivoted QR decomposition (tolerance 1e-7), r its rank.
95
+ */
96
+ export declare function treatmentModelMatrix(desc: FixedEffectsDescription): {
97
+ x: number[][];
98
+ colNames: string[];
99
+ assign: number[];
100
+ };
101
+ /**
102
+ * The hypothesis matrices of lmerTest's ANOVA table of the given type, one per term (oracle/lmertest-behaviour.md,
103
+ * section 2). If X has at most one column or the formula at most one term, every type is built as Type I.
104
+ */
105
+ export declare function lmerHypotheses(desc: FixedEffectsDescription, type?: HypothesisType): LmerHypotheses;