@numero-uno-jpn/rstats 0.11.1 → 0.13.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 (112) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.ja.md +49 -19
  3. package/README.md +45 -15
  4. package/THIRD_PARTY_NOTICES.md +2 -2
  5. package/dist/chunks/chunk-22SXZNR6.js +2 -0
  6. package/dist/chunks/chunk-2IAT6MT2.js +2 -0
  7. package/dist/chunks/chunk-3AKA4KEL.js +3 -0
  8. package/dist/chunks/{chunk-2X7JYQBI.js → chunk-4AQNVF3Z.js} +2 -2
  9. package/dist/chunks/chunk-4GNJEYXR.js +2 -0
  10. package/dist/chunks/chunk-AGRKZXLG.js +2 -0
  11. package/dist/chunks/{chunk-GG4BJMJW.js → chunk-BJHBYEEU.js} +1 -1
  12. package/dist/chunks/chunk-BSOUJPDF.js +2 -0
  13. package/dist/chunks/{chunk-WQPFDDIY.js → chunk-CQNVEA22.js} +2 -2
  14. package/dist/chunks/{chunk-HITD7CX6.js → chunk-F44XUHWI.js} +1 -1
  15. package/dist/chunks/chunk-JGFUZKLJ.js +2 -0
  16. package/dist/chunks/{chunk-ETOEZTGL.js → chunk-MEMYFTYS.js} +1 -1
  17. package/dist/chunks/{chunk-ZRJQD7VS.js → chunk-N3FV6H3C.js} +2 -2
  18. package/dist/chunks/chunk-NRV3BH7I.js +2 -0
  19. package/dist/chunks/chunk-RTWLZPPG.js +2 -0
  20. package/dist/chunks/chunk-SLSDFIW2.js +2 -0
  21. package/dist/chunks/chunk-SVWU5T7C.js +2 -0
  22. package/dist/chunks/chunk-VG67L3JA.js +3 -0
  23. package/dist/chunks/chunk-VWGJYRE6.js +2 -0
  24. package/dist/data/grouping.d.ts +6 -3
  25. package/dist/data/grouping.js +30 -26
  26. package/dist/descriptive/basic.js +57 -49
  27. package/dist/descriptive/cov.js +7 -2
  28. package/dist/descriptive/factanal.d.ts +16 -0
  29. package/dist/descriptive/factanal.js +26 -0
  30. package/dist/descriptive/hist.d.ts +8 -2
  31. package/dist/descriptive/hist.js +10 -2
  32. package/dist/descriptive/quantile.d.ts +8 -3
  33. package/dist/descriptive/quantile.js +10 -6
  34. package/dist/descriptive/table.d.ts +7 -5
  35. package/dist/descriptive/table.js +39 -22
  36. package/dist/descriptive.js +2 -2
  37. package/dist/distributions/beta.js +17 -0
  38. package/dist/distributions/binomial.js +3 -0
  39. package/dist/distributions/gamma.js +7 -0
  40. package/dist/distributions.js +2 -2
  41. package/dist/entries/mixed.d.ts +1 -0
  42. package/dist/entries/mixed.js +2 -0
  43. package/dist/entries/tests.d.ts +1 -1
  44. package/dist/htest/agreement.js +7 -2
  45. package/dist/htest/groups.js +7 -3
  46. package/dist/htest/mcnemarTest.js +6 -2
  47. package/dist/htest/pairwise.js +6 -3
  48. package/dist/htest/polycor.js +5 -3
  49. package/dist/htest/tTest.d.ts +3 -2
  50. package/dist/htest/tTest.js +6 -3
  51. package/dist/htest/testFormula.js +6 -3
  52. package/dist/htest/trendTests.js +10 -5
  53. package/dist/internal/levels.d.ts +11 -0
  54. package/dist/internal/levels.js +48 -0
  55. package/dist/internal/summary.d.ts +19 -1
  56. package/dist/internal/summary.js +69 -8
  57. package/dist/linalg/balance.d.ts +21 -0
  58. package/dist/linalg/balance.js +191 -0
  59. package/dist/linalg/eigen.d.ts +1 -1
  60. package/dist/linalg/eigen.js +8 -2
  61. package/dist/linalg/expm.d.ts +1 -11
  62. package/dist/linalg/expm.js +2 -158
  63. package/dist/linalg/kappa.d.ts +6 -2
  64. package/dist/linalg/kappa.js +16 -7
  65. package/dist/linalg/lu.d.ts +13 -2
  66. package/dist/linalg/lu.js +17 -3
  67. package/dist/linalg/qr.d.ts +4 -1
  68. package/dist/linalg/qr.js +2 -2
  69. package/dist/linalg.js +2 -2
  70. package/dist/mixed.js +3 -0
  71. package/dist/models/aovEz.js +6 -4
  72. package/dist/models/aovStrata.d.ts +1 -1
  73. package/dist/models/aovStrata.js +5 -1
  74. package/dist/models/coxph.js +5 -2
  75. package/dist/models/formula.d.ts +26 -1
  76. package/dist/models/formula.js +125 -9
  77. package/dist/models/glm.d.ts +4 -1
  78. package/dist/models/glmFamily.d.ts +1 -1
  79. package/dist/models/glmFamily.js +24 -2
  80. package/dist/models/lm.d.ts +2 -2
  81. package/dist/models/lmer.d.ts +162 -0
  82. package/dist/models/lmer.js +457 -0
  83. package/dist/models/mauchly.js +2 -1
  84. package/dist/models/mixedDeviance.d.ts +44 -0
  85. package/dist/models/mixedDeviance.js +872 -0
  86. package/dist/models/mixedStructure.d.ts +82 -0
  87. package/dist/models/mixedStructure.js +309 -0
  88. package/dist/models/modelFrame.d.ts +12 -1
  89. package/dist/models/modelFrame.js +38 -22
  90. package/dist/models/modelMatrix.d.ts +15 -4
  91. package/dist/models/modelMatrix.js +18 -4
  92. package/dist/models/survival.js +5 -1
  93. package/dist/numerics/integrate.d.ts +1 -1
  94. package/dist/numerics/integrate.js +13 -3
  95. package/dist/numerics/interp.d.ts +1 -1
  96. package/dist/numerics/interp.js +3 -0
  97. package/dist/numerics.js +2 -2
  98. package/dist/rstats.js +14 -14
  99. package/dist/special/beta.js +10 -20
  100. package/dist/special.js +2 -2
  101. package/dist/tests.js +12 -12
  102. package/llms.txt +11 -3
  103. package/package.json +5 -1
  104. package/dist/chunks/chunk-36GVER3O.js +0 -2
  105. package/dist/chunks/chunk-3WUXRSM6.js +0 -2
  106. package/dist/chunks/chunk-6I6QKTFK.js +0 -2
  107. package/dist/chunks/chunk-FVPDVRJQ.js +0 -3
  108. package/dist/chunks/chunk-KK4GE65D.js +0 -2
  109. package/dist/chunks/chunk-LAUYSGV4.js +0 -3
  110. package/dist/chunks/chunk-M6GDXKKS.js +0 -2
  111. package/dist/chunks/chunk-PHHUHR7T.js +0 -2
  112. package/dist/chunks/chunk-X2AWQSVS.js +0 -2
@@ -23,6 +23,13 @@ export type FormulaNode = {
23
23
  } | {
24
24
  type: "Error";
25
25
  arg: FormulaNode;
26
+ }
27
+ /** A random-effects term `lhs | group` (`double`: `lhs || group`) */
28
+ | {
29
+ type: "bar";
30
+ double: boolean;
31
+ lhs: FormulaNode;
32
+ group: FormulaNode;
26
33
  };
27
34
  /** A parsed formula before expansion. */
28
35
  export interface ParsedFormula {
@@ -36,13 +43,26 @@ export interface ParsedFormula {
36
43
  * or uses something that is not supported (function calls other than Error(), backquoted names, ...).
37
44
  *
38
45
  * @param allowError Accept `Error(...)` terms (aov only).
46
+ * @param allowBars Accept the random-effects terms `(lhs | group)` and `(lhs || group)` (mixed models only).
39
47
  */
40
- export declare function parseFormula(formula: string, allowError?: boolean): ParsedFormula;
48
+ export declare function parseFormula(formula: string, allowError?: boolean, allowBars?: boolean): ParsedFormula;
41
49
  /** The `Error()` terms of a right-hand side (top-level summands) and the right-hand side without them. */
42
50
  export declare function splitErrorTerms(rhs: FormulaNode): {
43
51
  treatment: FormulaNode | undefined;
44
52
  errors: FormulaNode[];
45
53
  };
54
+ /** The random-effects terms of a right-hand side (summands, possibly in parentheses) and the right-hand side without them. */
55
+ export declare function splitBarTerms(rhs: FormulaNode): {
56
+ fixed: FormulaNode | undefined;
57
+ bars: Extract<FormulaNode, {
58
+ type: "bar";
59
+ }>[];
60
+ };
61
+ /**
62
+ * A formula node as R deparses it: `+`, `-`, `*` and `%in%` with a space on each side, `:`, `/` and `^` without,
63
+ * unary minus and plus without a space, parentheses as written.
64
+ */
65
+ export declare function deparseFormula(n: FormulaNode): string;
46
66
  /** Terms of a model: the variables of each term as indices into `variables`, in increasing order. */
47
67
  export interface Terms {
48
68
  /** The variable names: the response first (if any), then in order of first appearance in the formula. */
@@ -64,6 +84,11 @@ export interface Terms {
64
84
  /** Warnings of the expansion. */
65
85
  warnings: string[];
66
86
  }
87
+ /**
88
+ * The variable names of a right-hand side, in order of first appearance (`.` stands for `dot`), whatever its
89
+ * operators: R's variables of the model frame (aggregate's grouping variables).
90
+ */
91
+ export declare function formulaVariables(rhs: FormulaNode, dot: readonly string[]): string[];
67
92
  /**
68
93
  * Expands a right-hand side into terms (variable indices, increasing) and the intercept flag.
69
94
  *
@@ -3,11 +3,18 @@
3
3
  // Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Formulas" and "Coding"). The parser is an
4
4
  // operator-precedence parser with R's precedences (^, then unary - and +, then :, then %in%, then * and /, then binary
5
5
  // + and -). The expansion follows the rules listed there: + concatenates, : forms the unions of pairs, * is a + b + a:b,
6
- // ^n the unions of n terms, / and %in% nest, - removes terms (and in its right operand 0 and 1 swap meanings). The
6
+ // ^n the unions of n terms (n truncated towards zero), / and %in% nest, - removes terms (and in its right operand 0
7
+ // and 1 swap meanings); *, / and %in% with a left operand that expands to no terms give no terms. The
7
8
  // terms are then sorted stably by degree, and the variables of each term listed in order of first appearance in the
8
9
  // formula. `codes` gives R's "factors" attribute (1: contrasts, 2: indicators) from the rule on earlier terms.
10
+ //
11
+ // Random-effects terms `(lhs | group)` and `(lhs || group)` of linear mixed models (oracle/lmer-behaviour.md,
12
+ // "Formulas with random-effects terms") are parsed only when asked for: `|` and `||` bind more loosely than every
13
+ // other operator, `splitBarTerms` separates them from the fixed-effects part, and `deparseFormula` prints a node as
14
+ // R deparses it (for the terms' labels).
15
+ import { formatR } from "../htest/core/simulate.js";
9
16
  const invalid = (why) => new SyntaxError(`invalid formula: ${why}`);
10
- function tokenize(s) {
17
+ function tokenize(s, allowBars) {
11
18
  const out = [];
12
19
  let i = 0;
13
20
  while (i < s.length) {
@@ -33,6 +40,12 @@ function tokenize(s) {
33
40
  i += 4;
34
41
  continue;
35
42
  }
43
+ if (allowBars && c === "|") {
44
+ const text = s[i + 1] === "|" ? "||" : "|";
45
+ out.push({ kind: "op", text });
46
+ i += text.length;
47
+ continue;
48
+ }
36
49
  if ("~+-*/:^()".includes(c)) {
37
50
  out.push({ kind: "op", text: c });
38
51
  i++;
@@ -43,19 +56,20 @@ function tokenize(s) {
43
56
  out.push({ kind: "end" });
44
57
  return out;
45
58
  }
46
- /** Binding powers of the binary operators (higher binds tighter); ^ is right associative */
47
- const BINARY = { "+": 1, "-": 1, "*": 2, "/": 2, "%in%": 3, ":": 4, "^": 6 };
59
+ /** Binding powers of the binary operators (higher binds tighter); ^ is right associative; | and || bind loosest */
60
+ const BINARY = { "|": 0.5, "||": 0.5, "+": 1, "-": 1, "*": 2, "/": 2, "%in%": 3, ":": 4, "^": 6 };
48
61
  const UNARY = 5;
49
62
  /**
50
63
  * Parses a formula string. Throws a SyntaxError whose message starts with "invalid formula" if it cannot be parsed
51
64
  * or uses something that is not supported (function calls other than Error(), backquoted names, ...).
52
65
  *
53
66
  * @param allowError Accept `Error(...)` terms (aov only).
67
+ * @param allowBars Accept the random-effects terms `(lhs | group)` and `(lhs || group)` (mixed models only).
54
68
  */
55
- export function parseFormula(formula, allowError = false) {
69
+ export function parseFormula(formula, allowError = false, allowBars = false) {
56
70
  if (typeof formula !== "string")
57
71
  throw new TypeError("the formula must be a string");
58
- const toks = tokenize(formula);
72
+ const toks = tokenize(formula, allowBars);
59
73
  let pos = 0;
60
74
  const peek = () => toks[pos];
61
75
  const next = () => toks[pos++];
@@ -103,7 +117,7 @@ export function parseFormula(formula, allowError = false) {
103
117
  next();
104
118
  // ^ is right associative: its right operand may contain another ^
105
119
  const right = expr(t.text === "^" ? bp - 1 : bp);
106
- left = { type: "binary", op: t.text, left, right };
120
+ left = t.text === "|" || t.text === "||" ? { type: "bar", double: t.text === "||", lhs: left, group: right } : { type: "binary", op: t.text, left, right };
107
121
  }
108
122
  return left;
109
123
  }
@@ -162,6 +176,88 @@ export function splitErrorTerms(rhs) {
162
176
  errors.forEach(check);
163
177
  return { treatment, errors };
164
178
  }
179
+ /** The random-effects terms of a right-hand side (summands, possibly in parentheses) and the right-hand side without them. */
180
+ export function splitBarTerms(rhs) {
181
+ const bars = [];
182
+ const strip = (n) => {
183
+ switch (n.type) {
184
+ case "bar":
185
+ bars.push(n);
186
+ return undefined;
187
+ case "paren": {
188
+ const a = strip(n.arg);
189
+ return a === undefined ? undefined : { ...n, arg: a };
190
+ }
191
+ case "binary":
192
+ if (n.op === "+") {
193
+ const l = strip(n.left);
194
+ const r = strip(n.right);
195
+ if (l === undefined)
196
+ return r;
197
+ if (r === undefined)
198
+ return l;
199
+ return { ...n, left: l, right: r };
200
+ }
201
+ if (n.op === "-") {
202
+ // y ~ x + (1 | g) - 1: the random-effects term is a summand of the left operand
203
+ const l = strip(n.left);
204
+ if (l === undefined)
205
+ return { type: "unary", op: "-", arg: n.right };
206
+ return { ...n, left: l };
207
+ }
208
+ return n;
209
+ default:
210
+ return n;
211
+ }
212
+ };
213
+ const fixed = strip(rhs);
214
+ const check = (n) => {
215
+ if (n.type === "bar")
216
+ throw invalid("a random-effects term (lhs | group) must be a term of the right-hand side");
217
+ if (n.type === "binary") {
218
+ check(n.left);
219
+ check(n.right);
220
+ }
221
+ else if (n.type === "unary" || n.type === "paren" || n.type === "Error")
222
+ check(n.arg);
223
+ };
224
+ if (fixed !== undefined)
225
+ check(fixed);
226
+ for (const b of bars) {
227
+ check(b.lhs);
228
+ check(b.group);
229
+ }
230
+ return { fixed, bars };
231
+ }
232
+ /** Binary operators that R deparses with a space on each side */
233
+ const SPACED = new Set(["+", "-", "*", "%in%"]);
234
+ /**
235
+ * A formula node as R deparses it: `+`, `-`, `*` and `%in%` with a space on each side, `:`, `/` and `^` without,
236
+ * unary minus and plus without a space, parentheses as written.
237
+ */
238
+ export function deparseFormula(n) {
239
+ switch (n.type) {
240
+ case "var":
241
+ return n.name;
242
+ case "dot":
243
+ return ".";
244
+ case "num":
245
+ return formatR(n.value);
246
+ case "binary": {
247
+ const l = deparseFormula(n.left);
248
+ const r = deparseFormula(n.right);
249
+ return SPACED.has(n.op) ? `${l} ${n.op} ${r}` : `${l}${n.op}${r}`;
250
+ }
251
+ case "unary":
252
+ return `${n.op}${deparseFormula(n.arg)}`;
253
+ case "paren":
254
+ return `(${deparseFormula(n.arg)})`;
255
+ case "Error":
256
+ return `Error(${deparseFormula(n.arg)})`;
257
+ case "bar":
258
+ return `${deparseFormula(n.lhs)} ${n.double ? "||" : "|"} ${deparseFormula(n.group)}`;
259
+ }
260
+ }
165
261
  /** The variable names of a node, in order of first appearance (`.` expands to `dot`) */
166
262
  function collectVariables(n, dot, out) {
167
263
  if (n === undefined)
@@ -188,8 +284,21 @@ function collectVariables(n, dot, out) {
188
284
  case "paren":
189
285
  case "Error":
190
286
  collectVariables(n.arg, dot, out);
287
+ return;
288
+ case "bar":
289
+ collectVariables(n.lhs, dot, out);
290
+ collectVariables(n.group, dot, out);
191
291
  }
192
292
  }
293
+ /**
294
+ * The variable names of a right-hand side, in order of first appearance (`.` stands for `dot`), whatever its
295
+ * operators: R's variables of the model frame (aggregate's grouping variables).
296
+ */
297
+ export function formulaVariables(rhs, dot) {
298
+ const out = [];
299
+ collectVariables(rhs, dot, out);
300
+ return out;
301
+ }
193
302
  const keyOf = (t) => t.join(",");
194
303
  function dedupe(terms) {
195
304
  const seen = new Set();
@@ -228,6 +337,8 @@ export function expandRhs(rhs, index, dot) {
228
337
  return L(n.arg, negated);
229
338
  case "Error":
230
339
  throw invalid("Error() must be a term of the right-hand side");
340
+ case "bar":
341
+ throw invalid("a random-effects term (lhs | group) must be a term of the right-hand side");
231
342
  case "unary":
232
343
  if (n.op === "+")
233
344
  return L(n.arg, negated);
@@ -239,8 +350,9 @@ export function expandRhs(rhs, index, dot) {
239
350
  let e = n.right;
240
351
  while (e.type === "paren")
241
352
  e = e.arg;
242
- const p = e.type === "num" ? e.value : NaN;
243
- if (!Number.isInteger(p) || p < 2)
353
+ // n is truncated towards zero (R's asInteger: ^2.5 is ^2)
354
+ const p = e.type === "num" ? Math.trunc(e.value) : NaN;
355
+ if (!(p >= 2))
244
356
  throw new Error("invalid power in formula");
245
357
  let cur = a;
246
358
  for (let k = 1; k < p; k++) {
@@ -259,6 +371,10 @@ export function expandRhs(rhs, index, dot) {
259
371
  }
260
372
  const a = L(n.left, negated);
261
373
  const b = L(n.right, negated);
374
+ // R builds *, / and %in% by appending to the left operand's list: an empty left operand gives no terms (the
375
+ // right operand has still been expanded, for its effect on the intercept)
376
+ if (a.length === 0 && n.op !== "+")
377
+ return [];
262
378
  const cross = () => {
263
379
  const out = [];
264
380
  for (const s of a)
@@ -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")
@@ -122,8 +122,8 @@ export declare function lmFormulaFit(formula: string, d: Design, aov: boolean):
122
122
  * Fit a linear model from a formula. Equivalent to R's `lm(formula, data)`. With `weights` and `contrasts`, and the
123
123
  * quantities of `summary()`.
124
124
  *
125
- * The model matrix is that of {@link modelMatrix} (but levels without rows are dropped, as R's
126
- * `drop.unused.levels`); the fit is that of the matrix form (same pivoting and tolerance), its sums of squares computed
125
+ * The model matrix is that of {@link modelMatrix} (but the levels given by `levels` that have no row left are
126
+ * dropped, as R's `drop.unused.levels`; a boolean column keeps both levels FALSE and TRUE); the fit is that of the matrix form (same pivoting and tolerance), its sums of squares computed
127
127
  * in double-double so that data with a large mean keep their accuracy. Rows with a missing value in a variable of the
128
128
  * formula or in the weights are dropped (`rows` lists those used).
129
129
  *
@@ -0,0 +1,162 @@
1
+ import type { DataFrame } from "./modelFrame.js";
2
+ import type { ContrastName } from "./modelMatrix.js";
3
+ import { type MixedModelStructure } from "./mixedStructure.js";
4
+ /**
5
+ * Options of {@link lmer}.
6
+ *
7
+ * @category Mixed models
8
+ */
9
+ export interface LmerOptions {
10
+ /** Whether to minimise the REML criterion (default `true`) or the ML deviance (`false`). */
11
+ REML?: boolean;
12
+ /**
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`.
16
+ */
17
+ contrasts?: Record<string, ContrastName>;
18
+ /** The order of the levels of a factor (`{ A: ["c", "a", "b"] }`), as `factor(x, levels = ...)` in R. */
19
+ levels?: Record<string, readonly string[]>;
20
+ }
21
+ /**
22
+ * The variance and correlation parameters of a random-effects term in a {@link LmerResult}: one entry of R's
23
+ * `VarCorr()`.
24
+ *
25
+ * @category Mixed models
26
+ */
27
+ export interface LmerVarCorr {
28
+ /** The grouping factor's name, such as `"Subject"` or `"cask:batch"`. */
29
+ group: string;
30
+ /** The names of the term's columns, such as `["(Intercept)", "Days"]`. */
31
+ columns: string[];
32
+ /** The standard deviations of the random effects, one per column. */
33
+ sd: number[];
34
+ /** Their correlation matrix (array of rows; 1 on the diagonal). */
35
+ corr: number[][];
36
+ }
37
+ /**
38
+ * The conditional modes of the random effects of a grouping factor in a {@link LmerResult}: one entry of R's
39
+ * `ranef()`.
40
+ *
41
+ * @category Mixed models
42
+ */
43
+ export interface LmerRanef {
44
+ /** The grouping factor's name. */
45
+ group: string;
46
+ /** Its levels (the rows of `values`). */
47
+ levels: string[];
48
+ /** The columns of all the terms of this grouping factor, in term order. */
49
+ columns: string[];
50
+ /** One array per level, one value per column. */
51
+ values: number[][];
52
+ }
53
+ /**
54
+ * Result of {@link lmer}: the fit of a linear mixed model and the quantities of R's methods for it.
55
+ *
56
+ * @category Mixed models
57
+ */
58
+ export interface LmerResult {
59
+ /** The formula. */
60
+ formula: string;
61
+ /** Whether the REML criterion was minimised (otherwise the ML deviance). */
62
+ REML: boolean;
63
+ /** Number of rows used. */
64
+ nObs: number;
65
+ /** 0-based indices of the rows of `data` used (rows with a missing value in a variable of the formula dropped). */
66
+ rows: number[];
67
+ /** The estimate of the covariance parameters θ (R's `getME(fit, "theta")`): the lower triangles of the relative covariance factors, by term, column-major. */
68
+ theta: number[];
69
+ /** Names of the columns of the fixed-effects model matrix (aliased columns dropped). */
70
+ fixefNames: string[];
71
+ /** The fixed effects β̂ (R's `fixef()`). */
72
+ fixef: number[];
73
+ /** The coefficient table of the fixed effects (R's `coef(summary(fit))`). */
74
+ coefTable: {
75
+ /** Estimates (R's `Estimate`). */
76
+ estimate: number[];
77
+ /** Standard errors (R's `Std. Error`). */
78
+ stdError: number[];
79
+ /** t statistics (R's `t value`). */
80
+ tValue: number[];
81
+ };
82
+ /** The covariance matrix of the fixed effects (R's `vcov()`), array of rows. */
83
+ vcov: number[][];
84
+ /** The residual standard deviation (R's `sigma()`). */
85
+ sigma: number;
86
+ /** The variance components, one entry per random-effects term (R's `VarCorr()`). */
87
+ varCorr: LmerVarCorr[];
88
+ /** The conditional modes of the random effects, one entry per grouping factor (R's `ranef()`). */
89
+ ranef: LmerRanef[];
90
+ /** Fitted values Xβ̂ + Zb̂, one per row used (R's `fitted()`). */
91
+ fitted: number[];
92
+ /** Residuals y − fitted (R's `residuals()`). */
93
+ residuals: number[];
94
+ /** The log-likelihood, or the REML log-likelihood for a REML fit (R's `logLik()`). */
95
+ logLik: number;
96
+ /** Degrees of freedom of the log-likelihood: the numbers of fixed effects and of θ, plus 1 (for σ). */
97
+ df: number;
98
+ /** Akaike's information criterion (R's `AIC()`). */
99
+ AIC: number;
100
+ /** Schwarz's Bayesian information criterion (R's `BIC()`). */
101
+ BIC: number;
102
+ /** The ML deviance at the estimates, for either kind of fit (R's `deviance(fit, REML = FALSE)`). */
103
+ deviance: number;
104
+ /** The REML criterion at the estimates, for either kind of fit (R's `REMLcrit()`). */
105
+ REMLcrit: number;
106
+ /** Whether the fit is singular: a diagonal element of a relative covariance factor below 1e-4 (R's `isSingular()`). */
107
+ singular: boolean;
108
+ /** R's messages (a rank-deficient fixed-effects matrix, a singular fit). */
109
+ messages: string[];
110
+ /** R's warnings (predictors on very different scales). */
111
+ warnings: string[];
112
+ }
113
+ /**
114
+ * The criterion (REML criterion or ML deviance) and its gradient with respect to θ at `theta`. Internal: the fit uses
115
+ * the sparse {@link profiledDeviance}; the regression test injects the dense reference implementation.
116
+ */
117
+ export type MixedCriterion = (s: MixedModelStructure, theta: readonly number[], reml: boolean) => {
118
+ f: number;
119
+ g: number[];
120
+ };
121
+ /**
122
+ * Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
123
+ * quantities of its methods: `fixef()`, `coef(summary())` (without p-values), `vcov()`, `sigma()`, `VarCorr()`,
124
+ * `ranef()`, `fitted()`, `residuals()`, `logLik()`, `AIC()`, `BIC()`, `deviance()`, `REMLcrit()` and `isSingular()`.
125
+ *
126
+ * The formula has random-effects terms `(lhs | group)` (correlated effects of the columns of `lhs` within each level
127
+ * of `group`) or `(lhs || group)` (uncorrelated); `group` may be `a:b` (the combinations), `a/b` (nested: `b:a` and
128
+ * `a`) and so on, as in lme4. The fixed-effects part is coded as in {@link lm}; aliased columns are dropped (with a
129
+ * message). Rows with a missing value in a variable of the formula are dropped (`rows` lists those used).
130
+ *
131
+ * The covariance parameters θ are the lower triangles of the relative covariance factors of the terms; the estimate
132
+ * is the exact minimiser of the profiled criterion (lme4's optimiser stops close to it, so lme4's values typically
133
+ * differ in the 5th to 9th significant digit). Elements on the boundary are exactly 0, and the fit is then singular.
134
+ * The computation is sparse (a sparse Cholesky factorisation, as in lme4), so many groups are handled quickly.
135
+ *
136
+ * @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
137
+ * @param data The data frame: an object of columns.
138
+ * @param options `REML`, and `contrasts` and `levels` as in {@link lm}.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * // R: lme4::lmer(y ~ 1 + (1 | g), data)
143
+ * const fit = lmer("y ~ 1 + (1 | g)", {
144
+ * y: [9.8, 10.4, 10.1, 12.3, 12.9, 12.0, 8.1, 7.6, 8.4],
145
+ * g: ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
146
+ * });
147
+ * fit.fixef; // [10.177778]
148
+ * fit.sigma; // 0.39299
149
+ * fit.varCorr[0].sd; // [2.1726]
150
+ * fit.ranef[0].levels; // ["a", "b", "c"]
151
+ * fit.ranef[0].values; // [[-0.076939], [2.1982], [-2.1213]]
152
+ * fit.REMLcrit; // 19.015
153
+ * ```
154
+ *
155
+ * @category Mixed models
156
+ */
157
+ export declare function lmer(formula: string, data: DataFrame, options?: LmerOptions): LmerResult;
158
+ /**
159
+ * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
160
+ * test of the sparse computation fits with the dense reference implementation through it.
161
+ */
162
+ export declare function lmerWithCriterion(formula: string, data: DataFrame, options: LmerOptions, criterion: MixedCriterion): LmerResult;