@numero-uno-jpn/rstats 1.14.0 → 1.15.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 (73) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.ja.md +6 -6
  3. package/README.md +6 -6
  4. package/dist/causal.js +2 -2
  5. package/dist/chunks/{chunk-A5DZG7FH.js → chunk-3K47QLCY.js} +2 -2
  6. package/dist/chunks/{chunk-AQHG7BEZ.js → chunk-4EH3O466.js} +2 -2
  7. package/dist/chunks/{chunk-NA7EDZ4Q.js → chunk-5BCXHJPF.js} +2 -2
  8. package/dist/chunks/{chunk-7FGVMDJE.js → chunk-5JKKIVYL.js} +2 -2
  9. package/dist/chunks/{chunk-4O6XLQBN.js → chunk-5Q5YVM7S.js} +2 -2
  10. package/dist/chunks/{chunk-6VY3XNAF.js → chunk-6SZLUVSL.js} +2 -2
  11. package/dist/chunks/{chunk-CKUBQW2A.js → chunk-AGA7JCRF.js} +2 -2
  12. package/dist/chunks/{chunk-7VMGP2U7.js → chunk-AILN2NGE.js} +2 -2
  13. package/dist/chunks/{chunk-SEKOIW43.js → chunk-APOF7BLH.js} +2 -2
  14. package/dist/chunks/chunk-CIBAGTO2.js +4 -0
  15. package/dist/chunks/{chunk-EDRBKZ3C.js → chunk-FD375XBW.js} +2 -2
  16. package/dist/chunks/{chunk-XXH5OIUO.js → chunk-FV4ZQPRI.js} +2 -2
  17. package/dist/chunks/{chunk-D25AVVVI.js → chunk-GBNGGBU3.js} +2 -2
  18. package/dist/chunks/{chunk-TGXUU5NB.js → chunk-HF4TT233.js} +1 -1
  19. package/dist/chunks/{chunk-MJHFGGPU.js → chunk-HSVVCFEN.js} +2 -2
  20. package/dist/chunks/{chunk-FPJ2CWLK.js → chunk-IMSXMJ43.js} +2 -2
  21. package/dist/chunks/{chunk-DZQWGBTW.js → chunk-JAXYZJV7.js} +2 -2
  22. package/dist/chunks/{chunk-B6NPCYFO.js → chunk-JGZSGGMD.js} +2 -2
  23. package/dist/chunks/{chunk-EWNJT27V.js → chunk-KQGH6SEW.js} +2 -2
  24. package/dist/chunks/chunk-L7HJGM52.js +2 -0
  25. package/dist/chunks/{chunk-YLUF4WTL.js → chunk-M3HFLMXL.js} +2 -2
  26. package/dist/chunks/{chunk-ZWSHIUBZ.js → chunk-MKCPS5QQ.js} +2 -2
  27. package/dist/chunks/{chunk-ZJJJDLRL.js → chunk-NULJXDAR.js} +2 -2
  28. package/dist/chunks/{chunk-3DA7CMFN.js → chunk-OBTCIG5D.js} +2 -2
  29. package/dist/chunks/{chunk-MXOBCQQP.js → chunk-OO22LZ7Q.js} +2 -2
  30. package/dist/chunks/chunk-P4TKSL4W.js +2 -0
  31. package/dist/chunks/{chunk-QLKZ2OFQ.js → chunk-PZRABNMZ.js} +2 -2
  32. package/dist/chunks/{chunk-2426YL2X.js → chunk-R74QJUYU.js} +2 -2
  33. package/dist/chunks/{chunk-IXFWR3LH.js → chunk-RHNGF7R7.js} +2 -2
  34. package/dist/chunks/{chunk-VWCCPBBG.js → chunk-RV4JZHTE.js} +2 -2
  35. package/dist/chunks/{chunk-3746VXPM.js → chunk-SMA62635.js} +2 -2
  36. package/dist/chunks/{chunk-3XUHCWLU.js → chunk-SNQABDAT.js} +1 -1
  37. package/dist/chunks/{chunk-SDIIGAY5.js → chunk-U5UOVXKD.js} +2 -2
  38. package/dist/chunks/{chunk-PHDTVTKV.js → chunk-UFJFVNC6.js} +1 -1
  39. package/dist/chunks/{chunk-Y7VD43TO.js → chunk-VHBIWPB4.js} +2 -2
  40. package/dist/chunks/{chunk-BCXYAILN.js → chunk-VHMFOILD.js} +2 -2
  41. package/dist/chunks/{chunk-H5GBKP57.js → chunk-VO3E4Q6H.js} +1 -1
  42. package/dist/chunks/{chunk-6HUTVWPO.js → chunk-WL3JGBLZ.js} +2 -2
  43. package/dist/chunks/{chunk-62Y36UKH.js → chunk-XVRRYHLM.js} +2 -2
  44. package/dist/chunks/{chunk-I2OTBVRK.js → chunk-YYLBBEWZ.js} +2 -2
  45. package/dist/chunks/{chunk-JCGCJT7T.js → chunk-ZDUVFNFH.js} +1 -1
  46. package/dist/chunks/{chunk-MCEZRRQO.js → chunk-ZUTVNRML.js} +2 -2
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions.js +2 -2
  49. package/dist/entries/tests.d.ts +2 -1
  50. package/dist/entries/tests.js +1 -0
  51. package/dist/linalg.js +2 -2
  52. package/dist/mixed.js +4 -5
  53. package/dist/models/fitOptions.d.ts +4 -0
  54. package/dist/models/fitOptions.js +14 -0
  55. package/dist/models/glm.d.ts +67 -5
  56. package/dist/models/glm.js +105 -27
  57. package/dist/models/glmerStructure.d.ts +5 -0
  58. package/dist/models/glmerStructure.js +2 -2
  59. package/dist/models/lm.js +3 -1
  60. package/dist/models/step.d.ts +250 -0
  61. package/dist/models/step.js +592 -0
  62. package/dist/multivariate.js +2 -2
  63. package/dist/numerics.js +2 -2
  64. package/dist/regression.js +2 -2
  65. package/dist/rstats.js +17 -17
  66. package/dist/special.js +2 -2
  67. package/dist/tests.js +14 -14
  68. package/dist/timeseries.js +2 -2
  69. package/package.json +1 -1
  70. package/dist/chunks/chunk-7BBIQY4W.js +0 -2
  71. package/dist/chunks/chunk-AONDWNMF.js +0 -2
  72. package/dist/chunks/chunk-F6KKW5YN.js +0 -2
  73. package/dist/chunks/chunk-KITNZUYC.js +0 -3
@@ -3,6 +3,8 @@ import { type QR } from "../linalg/qr.js";
3
3
  import type { Sample } from "../htest/types.js";
4
4
  import { type Family, type GlmFamilyName, type GlmFamilySpec, type GlmLink } from "./glmFamily.js";
5
5
  import { Warnings } from "../internal/warnings.js";
6
+ import { type ModelMatrixOptions } from "./modelMatrix.js";
7
+ import type { DataFrame } from "./modelFrame.js";
6
8
  export type { GlmFamilyName, GlmFamilySpec, GlmLink, GlmLinkName, QuasiVariance } from "./glmFamily.js";
7
9
  /**
8
10
  * Options for {@link glm}.
@@ -34,6 +36,45 @@ export interface GlmOptions {
34
36
  /** Include an intercept (a column of ones before the columns of `x`). Default `true`. */
35
37
  intercept?: boolean;
36
38
  }
39
+ /**
40
+ * Options for {@link glm} with a formula: those of the matrix form (the intercept is the formula's), the weights and
41
+ * the offset as arrays parallel to the rows of `data` or as column names, and the coding of factors.
42
+ *
43
+ * @category Generalized linear models
44
+ */
45
+ export interface GlmFormulaOptions extends Omit<GlmOptions, "weights" | "offset" | "intercept"> {
46
+ /** Prior weights: an array parallel to the rows of `data` (null for missing), or the name of a numeric column. */
47
+ weights?: readonly (number | null)[] | Float64Array | string;
48
+ /** Offset added to the linear predictor: an array parallel to the rows of `data`, or the name of a numeric column. */
49
+ offset?: readonly (number | null)[] | Float64Array | string;
50
+ /** Contrast per factor, as in {@link modelMatrix}. */
51
+ contrasts?: ModelMatrixOptions["contrasts"];
52
+ /** Levels per factor, as in {@link modelMatrix}. */
53
+ levels?: ModelMatrixOptions["levels"];
54
+ }
55
+ /**
56
+ * Result of {@link glm} with a formula: the fit of the model matrix, with the formula's terms.
57
+ *
58
+ * @category Generalized linear models
59
+ */
60
+ export interface GlmFormulaResult extends GlmResult {
61
+ /** The formula. */
62
+ formula: string;
63
+ /** The response's name (the first column of `cbind(a, b)`). */
64
+ response: string;
65
+ /** Names of the coefficients (the model matrix's column names). */
66
+ coefNames: string[];
67
+ /** The term of each coefficient (0 for the intercept). */
68
+ assign: number[];
69
+ /** Labels of the terms. */
70
+ termLabels: string[];
71
+ /** Degree of each term. */
72
+ order: number[];
73
+ /** The variables of the formula, the response first (both columns of `cbind(a, b)`). */
74
+ variables: string[];
75
+ /** R's factors attribute of the terms (one array per variable, one code per term). */
76
+ factors: number[][];
77
+ }
37
78
  /**
38
79
  * The data and settings of a fit, kept for the refits of {@link glmConfint} and {@link glmAnova}.
39
80
  *
@@ -170,9 +211,31 @@ export declare function refit(model: GlmModel, cols: number[], warnings: Warning
170
211
  offset: number[];
171
212
  };
172
213
  /**
173
- * Fit a generalized linear model by iteratively reweighted least squares. Equivalent to R's
174
- * `glm(y ~ x, family = ...)`. Or `y ~ x - 1` without intercept; the predictors are given as a matrix instead of a
175
- * formula. Rows with a missing value (NaN) in `x`, `y`, the weights or the offset are dropped. Every family and link
214
+ * Fit a generalized linear model by iteratively reweighted least squares, from a formula and a data frame. Equivalent
215
+ * to R's `glm(formula, family, data, weights, offset)`.
216
+ * The model matrix is that of {@link lm} with a formula (factors, interactions, contrasts, levels). The response
217
+ * is numeric; for the binomial families also `cbind(successes, failures)` with two column names, proportions with
218
+ * the numbers of trials as `weights`, a boolean column (FALSE 0, TRUE 1) or strings (the first level is failure,
219
+ * the others success). The weights and the offset are arrays or column names. Rows with a missing value in a
220
+ * variable of the formula, the weights or the offset are dropped (`model.rows` lists those used). The result is the
221
+ * matrix form's with the formula's terms, and the methods of {@link glm} apply to it.
222
+ *
223
+ * @param formula A formula such as `"y ~ x1 * f"` or `"cbind(s, f) ~ dose"`.
224
+ * @param data The data frame: an object of columns.
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * const data = { y: [0, 0, 1, 0, 1, 1, 1, 0], dose: [1, 2, 3, 4, 5, 6, 7, 8], g: ["a", "b", "a", "b", "a", "b", "a", "b"] };
229
+ * const fit = glm("y ~ dose + g", data, { family: "binomial" });
230
+ * fit.coefNames; // ["(Intercept)", "dose", "gb"]
231
+ * ```
232
+ *
233
+ * @category Generalized linear models
234
+ */
235
+ export declare function glm(formula: string, data: DataFrame, options?: GlmFormulaOptions): GlmFormulaResult;
236
+ /**
237
+ * Fit a generalized linear model by iteratively reweighted least squares, the predictors given as a matrix: R's
238
+ * `glm(y ~ x, family = ...)`, or `y ~ x - 1` without intercept. Rows with a missing value (NaN) in `x`, `y`, the weights or the offset are dropped. Every family and link
176
239
  * of R's `stats` is available; R's warnings are returned in `warnings`. See {@link glmSummary}, {@link glmResiduals},
177
240
  * {@link glmPredict}, {@link glmConfint} and {@link glmAnova} for the methods.
178
241
  *
@@ -186,8 +249,7 @@ export declare function refit(model: GlmModel, cols: number[], warnings: Warning
186
249
  * fit.coefficients; // [-4.2491, 1.214]
187
250
  * glmSummary(fit).pValue; // [0.20976, 0.18341]
188
251
  * ```
189
- *
190
- * @category Generalized linear models
252
+
191
253
  */
192
254
  export declare function glm(x: MatrixInput | Sample, y: Sample | MatrixInput, options?: GlmOptions): GlmResult;
193
255
  /**
@@ -17,11 +17,17 @@ import { optionalArgs } from "../internal/optionalArgs.js";
17
17
  import { ldexp, ldexpWide, scaleToUnit } from "../internal/summary.js";
18
18
  import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
19
19
  import { checkDot, checkedDot } from "../linalg/dot.js";
20
- import { setInputRowCount } from "./inputRows.js";
20
+ import { dataRowCount, setInputRowCount } from "./inputRows.js";
21
+ import { setFitOptions } from "./fitOptions.js";
22
+ import { parseFormula } from "./formula.js";
23
+ import { design } from "./modelMatrix.js";
24
+ import { isLogicalColumn, rowValues } from "./glmerStructure.js";
21
25
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
22
26
  import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
23
27
  import { optionsIn } from "../internal/optionalArgs.js";
24
- const GLM_KEYS = ["family", "link", "weights", "offset", "start", "epsilon", "maxit", "intercept"];
28
+ const GLM_KEYS = /* @__PURE__ */ new Set([
29
+ "weights", "offset", "contrasts", "levels", "family", "link", "start", "epsilon", "maxit", "intercept",
30
+ ]);
25
31
  const GLM_FAMILY_KEYS = ["family", "link", "variance"];
26
32
  const GLM_FAMILY_LINK_KEYS = ["power"];
27
33
  const GLM_SUMMARY_KEYS = ["dispersion"];
@@ -374,31 +380,17 @@ export function refit(model, cols, warnings, control = {}) {
374
380
  finalWarnings(fit, fam, warnings, cols.length === 0);
375
381
  return { fit, fam, y: prep.y, w: prep.weights, size: prep.size, offset };
376
382
  }
377
- /**
378
- * Fit a generalized linear model by iteratively reweighted least squares. Equivalent to R's
379
- * `glm(y ~ x, family = ...)`. Or `y ~ x - 1` without intercept; the predictors are given as a matrix instead of a
380
- * formula. Rows with a missing value (NaN) in `x`, `y`, the weights or the offset are dropped. Every family and link
381
- * of R's `stats` is available; R's warnings are returned in `warnings`. See {@link glmSummary}, {@link glmResiduals},
382
- * {@link glmPredict}, {@link glmConfint} and {@link glmAnova} for the methods.
383
- *
384
- * @param x Predictors: a matrix (array of rows, one column per predictor; rows of length 0 for a model with the
385
- * intercept only) or a vector (one predictor).
386
- * @param y Response: a vector, or for the binomial families rows of (successes, failures).
387
- *
388
- * @example
389
- * ```ts
390
- * const fit = glm([1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 1], { family: "binomial" });
391
- * fit.coefficients; // [-4.2491, 1.214]
392
- * glmSummary(fit).pValue; // [0.20976, 0.18341]
393
- * ```
394
- *
395
- * @category Generalized linear models
396
- */
397
383
  export function glm(x, y, options = {}) {
398
384
  checkOptions(options, GLM_KEYS, "glm"); // generated: option-keys.mjs
399
385
  checkOptions(nestedOptions(options, "family"), GLM_FAMILY_KEYS, "glm", "family"); // generated: option-keys.mjs
400
386
  checkOptions(nestedOptions(options, "family.link"), GLM_FAMILY_LINK_KEYS, "glm", "family.link"); // generated: option-keys.mjs
401
387
  checkOptions(nestedOptions(options, "link"), GLM_FAMILY_LINK_KEYS, "glm", "link"); // generated: option-keys.mjs
388
+ if (typeof x === "string")
389
+ return glmFormula(x, y, options);
390
+ const r = glmMatrix(x, y, options);
391
+ return reported("glm", setInputRowCount(r, y.length));
392
+ }
393
+ function glmMatrix(x, y, options, part) {
402
394
  const intercept = options.intercept ?? true;
403
395
  const xr = toRows(x);
404
396
  // the shape of all the rows given, before the rows with a missing value are dropped (#463)
@@ -436,7 +428,7 @@ export function glm(x, y, options = {}) {
436
428
  if (offset.some((v) => !Number.isFinite(v)))
437
429
  throw new RangeError("the offset must be finite");
438
430
  const nx = xr.length > 0 ? xr[0].length : 0;
439
- const columnNames = [...(intercept ? ["(Intercept)"] : []), ...Array.from({ length: nx }, (_, j) => `x${j + 1}`)];
431
+ const columnNames = part?.columnNames ?? [...(intercept ? ["(Intercept)"] : []), ...Array.from({ length: nx }, (_, j) => `x${j + 1}`)];
440
432
  const p = columnNames.length;
441
433
  const familySpec = typeof options.family === "object" ? { ...options.family } : { family: options.family ?? "gaussian" };
442
434
  if (options.link !== undefined)
@@ -454,7 +446,7 @@ export function glm(x, y, options = {}) {
454
446
  // R loops over 1:maxit, so a fractional maxit runs (and reports) its integer part
455
447
  maxit: Math.floor(options.maxit ?? 25),
456
448
  start: options.start === undefined ? undefined : Array.from(options.start),
457
- rows: keep.flatMap((k, i) => (k ? [i] : [])),
449
+ rows: part?.rows ?? keep.flatMap((k, i) => (k ? [i] : [])),
458
450
  };
459
451
  if (!(model.epsilon > 0 && model.epsilon < Infinity))
460
452
  throw new RangeError("value of 'epsilon' must be > 0 and finite");
@@ -464,22 +456,108 @@ export function glm(x, y, options = {}) {
464
456
  // (exact; src/internal/summary.ts), so that the deviance stays in range; see scaledView
465
457
  const k = !yIsMatrix && scalesWithResponse(familySpec) ? scaleToUnit([yGiven]).k : 0;
466
458
  if (k === 0)
467
- return reported("glm", setInputRowCount(fitModel(model), nAll));
459
+ return fitModel(model, part?.warnings);
468
460
  const down = (v) => ldexp(v, -k);
469
461
  const scaled = fitModel({
470
462
  ...model,
471
463
  yGiven: yGiven.map(down),
472
464
  offset: offset.map(down),
473
465
  start: model.start?.map(down),
466
+ }, part?.warnings);
467
+ return unscaledResult(scaled, k, { ...model, yScale: k });
468
+ }
469
+ /** glm with a formula: the model matrix and the response from the data, then the matrix form */
470
+ function glmFormula(formula, data, options) {
471
+ if (typeof data !== "object" || data === null)
472
+ throw new TypeError("data must be an object of columns");
473
+ const parsed = parseFormula(formula, false, false, true);
474
+ if (parsed.response === undefined)
475
+ throw new TypeError("the formula has no response");
476
+ const nAll = dataRowCount(data, [parsed.response]) ?? 0;
477
+ // the rows with a missing weight or offset are dropped with the others: the data restricted to the other rows first
478
+ // (the same model frame, as the levels of factors are formed from the rows kept)
479
+ const weightsAll = options.weights === undefined ? undefined : rowValues(options.weights, data, nAll, "weights");
480
+ const offsetAll = options.offset === undefined ? undefined : rowValues(options.offset, data, nAll, "offset");
481
+ let kept;
482
+ let frameData = data;
483
+ if (weightsAll !== undefined || offsetAll !== undefined) {
484
+ const rows = [];
485
+ for (let i = 0; i < nAll; i++)
486
+ if (!Number.isNaN(weightsAll?.[i] ?? 0) && !Number.isNaN(offsetAll?.[i] ?? 0))
487
+ rows.push(i);
488
+ if (rows.length < nAll) {
489
+ kept = rows;
490
+ frameData = Object.fromEntries(Object.entries(data).map(([key, col]) => [key, col.length === nAll ? (col instanceof Float64Array ? Float64Array.from(rows, (i) => col[i]) : rows.map((i) => col[i])) : col]));
491
+ }
492
+ }
493
+ const { contrasts, levels } = options;
494
+ const d = design(parsed, frameData, {
495
+ ...(contrasts === undefined ? {} : { contrasts }),
496
+ ...(levels === undefined ? {} : { levels }),
497
+ dropUnusedLevels: true,
498
+ anyResponse: true,
474
499
  });
475
- return reported("glm", setInputRowCount(unscaledResult(scaled, k, { ...model, yScale: k }), nAll));
500
+ const rows = kept === undefined ? d.frame.rows : d.frame.rows.map((i) => kept[i]);
501
+ const familyName = typeof options.family === "object" ? options.family.family : (options.family ?? "gaussian");
502
+ const binomial = familyName === "binomial" || familyName === "quasibinomial";
503
+ const vars = d.frame.variables;
504
+ const numeric = (index, name) => {
505
+ const v = vars[index];
506
+ if (v.kind === "numeric")
507
+ return v.values;
508
+ // a logical column (levels FALSE and TRUE) is 0/1; a factor (strings) is 0 for its first level, 1 for the others,
509
+ // for the binomial families only (as R's binomial()$initialize)
510
+ if (isLogicalColumn(frameData, name) && levels?.[name] === undefined)
511
+ return v.codes.map((c) => (v.levels[c] === "TRUE" ? 1 : 0));
512
+ if (binomial && parsed.responseColumns === undefined)
513
+ return v.codes.map((c) => (c === 0 ? 0 : 1));
514
+ throw new TypeError(binomial ? "response must be numeric or factor" : "response must be numeric");
515
+ };
516
+ let y;
517
+ if (parsed.responseColumns !== undefined) {
518
+ const [a, b] = parsed.responseColumns;
519
+ const sv = numeric(0, a);
520
+ const fv = numeric(1, b);
521
+ y = sv.map((v, i) => [v, fv[i]]);
522
+ }
523
+ else
524
+ y = numeric(0, parsed.response);
525
+ // the model matrix without its column of ones: the matrix form adds it back
526
+ const intercept = d.terms.intercept;
527
+ const x = d.x.map((r) => (intercept ? r.slice(1) : r));
528
+ const { contrasts: _c, levels: _l, weights: _w, offset: _o, ...rest } = options;
529
+ const matrixOptions = { ...rest, intercept };
530
+ if (weightsAll !== undefined)
531
+ matrixOptions.weights = rows.map((i) => weightsAll[i]);
532
+ if (offsetAll !== undefined)
533
+ matrixOptions.offset = rows.map((i) => offsetAll[i]);
534
+ const fit = glmMatrix(x, y, matrixOptions, { columnNames: d.colNames, rows, warnings: d.warnings });
535
+ const out = {
536
+ ...fit,
537
+ formula,
538
+ response: parsed.response,
539
+ coefNames: d.colNames,
540
+ assign: d.assign,
541
+ termLabels: d.terms.termLabels,
542
+ order: d.terms.order,
543
+ variables: d.terms.variables,
544
+ factors: d.terms.factors,
545
+ };
546
+ setFitOptions(out, options);
547
+ const scaled = fit.scaled;
548
+ if (scaled !== undefined)
549
+ Object.defineProperty(out, "scaled", { value: scaled, enumerable: false });
550
+ withUsedRows(USED_ROWS.get(fit), out);
551
+ return reported("glm", setInputRowCount(out, nAll));
476
552
  }
477
553
  /** The fit of a model (the part of glm after its checks) */
478
- function fitModel(model) {
554
+ function fitModel(model, earlier = []) {
479
555
  const { x: X, offset, intercept } = model;
480
556
  const n = X.length;
481
557
  const p = model.columnNames.length;
482
558
  const warnings = new Warnings();
559
+ for (const m of earlier)
560
+ warnings.add(m);
483
561
  const all = Array.from({ length: p }, (_, j) => j);
484
562
  const { fit, fam, y: yy, w, size } = refit(model, all, warnings);
485
563
  // null deviance: the constant weighted mean (with an intercept) or the inverse link of the offset
@@ -32,6 +32,11 @@ export interface GlmerStructure extends MixedModelStructure {
32
32
  /** nAGQ (truncated to an integer). */
33
33
  nAGQ: number;
34
34
  }
35
+ export type Column = readonly (number | null)[] | Float64Array;
36
+ /** A weights or offset argument as numbers over all rows of the data (NaN for missing) */
37
+ export declare function rowValues(given: Column | string, data: DataFrame, nAll: number, what: "weights" | "offset"): number[];
38
+ /** Whether a column of the data holds booleans (a logical response is 0/1, not a factor) */
39
+ export declare const isLogicalColumn: (data: DataFrame, name: string) => boolean;
35
40
  /**
36
41
  * The structure of a generalised linear mixed model `response ~ fixed part + (lhs | group) + ...` with lme4's checks,
37
42
  * errors and warnings (oracle/glmer-behaviour.md, stage 2a). The response may be `cbind(successes, failures)` (two
@@ -11,7 +11,7 @@ import { glmerFamily } from "./glmerFamily.js";
11
11
  import { parseFormula } from "./formula.js";
12
12
  import { mixedModelStructure } from "./mixedStructure.js";
13
13
  /** A weights or offset argument as numbers over all rows of the data (NaN for missing) */
14
- function rowValues(given, data, nAll, what) {
14
+ export function rowValues(given, data, nAll, what) {
15
15
  let col;
16
16
  if (typeof given === "string") {
17
17
  col = Object.hasOwn(data, given) ? data[given] : undefined;
@@ -34,7 +34,7 @@ function rowValues(given, data, nAll, what) {
34
34
  return values;
35
35
  }
36
36
  /** Whether a column of the data holds booleans (a logical response is 0/1, not a factor) */
37
- const isLogicalColumn = (data, name) => {
37
+ export const isLogicalColumn = (data, name) => {
38
38
  const col = Object.hasOwn(data, name) ? data[name] : undefined;
39
39
  return Array.isArray(col) && col.some((v) => typeof v === "boolean");
40
40
  };
package/dist/models/lm.js CHANGED
@@ -26,6 +26,7 @@ import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
26
26
  import { checkDot, checkedDot } from "../linalg/dot.js";
27
27
  import { reported } from "../internal/warnings.js";
28
28
  import { dataRowCount, setInputRowCount } from "./inputRows.js";
29
+ import { setFitOptions } from "./fitOptions.js";
29
30
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
30
31
  import { checkOptions } from "../internal/checkOptions.js";
31
32
  const LM_KEYS = ["weights", "contrasts", "levels", "intercept"];
@@ -79,7 +80,8 @@ export function lm(x, y, options = {}) {
79
80
  checkOptions(options, LM_KEYS, "lm"); // generated: option-keys.mjs
80
81
  if (typeof x === "string") {
81
82
  const d = design(parseFormula(x), y, { ...options, dropUnusedLevels: true });
82
- return reported("lm", setInputRowCount(lmFormulaFit(x, d, false), dataRowCount(y, d.terms.variables)));
83
+ const fit = setFitOptions(lmFormulaFit(x, d, false), options);
84
+ return reported("lm", setInputRowCount(fit, dataRowCount(y, d.terms.variables)));
83
85
  }
84
86
  return lmMatrix(x, y, options);
85
87
  }
@@ -0,0 +1,250 @@
1
+ import { type LmFormulaResult } from "./lm.js";
2
+ import { type GlmFormulaResult } from "./glm.js";
3
+ import { type DataFrame } from "./modelFrame.js";
4
+ /**
5
+ * A formula fit that the stepwise functions take: the result of {@link lm} or {@link glm} with a formula.
6
+ *
7
+ * @category Model selection
8
+ */
9
+ export type StepModel = LmFormulaResult | GlmFormulaResult;
10
+ /**
11
+ * Options of {@link extractAIC}.
12
+ *
13
+ * @category Model selection
14
+ */
15
+ export interface ExtractAicOptions {
16
+ /** The weight of the equivalent degrees of freedom: 2 (default) for AIC, `Math.log(n)` for BIC. */
17
+ k?: number;
18
+ /** lm only: a known residual variance; when positive the criterion is Mallows' Cp. Default 0. glm ignores it. */
19
+ scale?: number;
20
+ }
21
+ /**
22
+ * Options of {@link drop1} and {@link add1}.
23
+ *
24
+ * @category Model selection
25
+ */
26
+ export interface AddDropOptions extends ExtractAicOptions {
27
+ /**
28
+ * The terms to consider, as a one-sided formula such as `"~ x1 + x2 + f"`. drop1: default the terms that can be
29
+ * dropped respecting marginality; add1: required, the largest model (the terms that can be added respecting
30
+ * marginality are taken from it).
31
+ */
32
+ scope?: string;
33
+ /**
34
+ * A test column: `"F"` (lm; glm with an estimated dispersion), `"Chisq"` or `"LRT"` (the likelihood-ratio test of
35
+ * glm; for lm the change of RSS scaled by the residual variance), or `"none"` (default).
36
+ */
37
+ test?: "none" | "F" | "Chisq" | "LRT";
38
+ }
39
+ /**
40
+ * Result of {@link drop1} and {@link add1}: R's table, one row for the current model (`"<none>"`) and one per term.
41
+ *
42
+ * @category Model selection
43
+ */
44
+ export interface AddDropTable {
45
+ /** `"<none>"` and the terms. */
46
+ term: string[];
47
+ /** Degrees of freedom of each term (the change of rank; NaN for `<none>`). */
48
+ df: number[];
49
+ /** lm: the change of the residual sum of squares (R's `Sum of Sq`; NaN for `<none>`). Absent for glm. */
50
+ sumOfSq?: number[];
51
+ /** lm: the residual sum of squares of each model (R's `RSS`); glm: its deviance (R's `Deviance`). */
52
+ deviance: number[];
53
+ /** The criterion of each model (AIC, or Cp with `scale > 0`). */
54
+ aic: number[];
55
+ /** `"AIC"` or `"Cp"`: the name of the criterion's column in R. */
56
+ criterion: "AIC" | "Cp";
57
+ /** The statistic of the test (R's `F value`, `LRT` or `scaled dev.`; NaN for `<none>`), when a test was asked for. */
58
+ statistic?: number[];
59
+ /** The p-values of the test (R's `Pr(>F)` or `Pr(>Chi)`; NaN for `<none>`). */
60
+ pValue?: number[];
61
+ /** The test, when one was asked for: `"F"` or `"Chisq"`. */
62
+ test?: "F" | "Chisq";
63
+ /** R's name of the statistic's column: `"F value"`, `"LRT"` (binomial, poisson) or `"scaled dev."` (the others). */
64
+ statisticName?: string;
65
+ /** R's warnings, each once. */
66
+ warnings: string[];
67
+ }
68
+ /**
69
+ * Options of {@link step} and {@link stepAIC}.
70
+ *
71
+ * @category Model selection
72
+ */
73
+ export interface StepOptions {
74
+ /**
75
+ * The range of models: a one-sided formula for the largest (`"~ x1 + x2 + f"`), or `{ lower, upper }` (either may be
76
+ * left out: lower default no terms, upper default the start model). Without a scope only terms of the start
77
+ * model can be dropped.
78
+ */
79
+ scope?: string | {
80
+ /** The smallest model, a one-sided formula (default no terms): its terms are never dropped. */
81
+ lower?: string;
82
+ /** The largest model, a one-sided formula (default the start model): terms are added from it. */
83
+ upper?: string;
84
+ };
85
+ /** `"both"` (default), `"backward"` or `"forward"`. */
86
+ direction?: "both" | "backward" | "forward";
87
+ /** The weight of the equivalent degrees of freedom: 2 (default) for AIC, `Math.log(n)` for BIC. */
88
+ k?: number;
89
+ /** lm only: a known residual variance; when positive the criterion is Mallows' Cp. Default 0. */
90
+ scale?: number;
91
+ /** The largest number of moves. Default 1000. */
92
+ steps?: number;
93
+ }
94
+ /**
95
+ * One model of the search: its formula and criterion, and the table of moves that was examined from it (sorted by the
96
+ * criterion, `"<none>"` the current model, `"- term"` a drop, `"+ term"` an add), as R prints them.
97
+ *
98
+ * @category Model selection
99
+ */
100
+ export interface StepVisit {
101
+ /** The model's formula. */
102
+ formula: string;
103
+ /** The labels of its terms. */
104
+ termLabels: string[];
105
+ /** Its criterion (R's `extractAIC`). */
106
+ aic: number;
107
+ /** The table examined from it; absent when an aliased term was removed without a table, or the steps ran out. */
108
+ table?: {
109
+ /** `"<none>"`, `"- term"` and `"+ term"`, sorted by the criterion. */
110
+ move: string[];
111
+ /** Degrees of freedom of each move (NaN for `<none>`). */
112
+ df: number[];
113
+ /** lm: the change of the residual sum of squares (NaN for `<none>`). Absent for glm. */
114
+ sumOfSq?: number[];
115
+ /** lm: residual sum of squares; glm: deviance (of the model after the move). */
116
+ deviance: number[];
117
+ /** The criterion after the move. */
118
+ aic: number[];
119
+ };
120
+ }
121
+ /**
122
+ * Result of {@link step} and {@link stepAIC}.
123
+ *
124
+ * @category Model selection
125
+ */
126
+ export interface StepResult<F extends StepModel = StepModel> {
127
+ /** The selected model: the result of `lm` or `glm` with its formula. */
128
+ fit: F;
129
+ /**
130
+ * The path (R's `$anova`): one row for the start (step `""`, df and deviance NaN) and one per move. `df` is the change
131
+ * of the residual degrees of freedom (step: −1 for an added term) or its size (stepAIC: positive); `deviance` the
132
+ * change of the residual deviance (positive); `residDf` = nobs − edf; `aic` the criterion.
133
+ */
134
+ anova: {
135
+ /** `""` for the start, `"- term"` or `"+ term"` for each move. */
136
+ step: string[];
137
+ /** The change of the residual degrees of freedom (step) or its size (stepAIC); NaN for the start. */
138
+ df: number[];
139
+ /** The change of the residual deviance (positive); NaN for the start. */
140
+ deviance: number[];
141
+ /** nobs − edf of each model. */
142
+ residDf: number[];
143
+ /** The residual deviance of each model (lm: the RSS). */
144
+ residDeviance: number[];
145
+ /** The criterion of each model (R's `AIC` or `Cp` column). */
146
+ aic: number[];
147
+ };
148
+ /** `"AIC"` or `"Cp"`: the name of the criterion's column in R. */
149
+ criterion: "AIC" | "Cp";
150
+ /** Each model visited, the start first, with the table examined from it (R's printed trace). */
151
+ visits: StepVisit[];
152
+ /** R's warnings, each once (those of the refits, of add1's combined fit, of a perfect fit). */
153
+ warnings: string[];
154
+ }
155
+ /**
156
+ * The criterion of a fit for model selection: `[edf, criterion]`. Equivalent to R's `extractAIC()`. lm: n log(RSS / n) + k edf, or with `scale > 0`
157
+ * Mallows' Cp = RSS / scale − n + k edf; glm: AIC + (k − 2) edf. n counts the rows used (weight-0 rows included) and
158
+ * edf = n − the residual degrees of freedom, so that with weight-0 rows edf exceeds the rank by their number, as in R.
159
+ *
160
+ * @param fit A fit of {@link lm} or {@link glm} with a formula.
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8], x: [1, 2, 3, 4, 5, 6] };
165
+ * extractAIC(lm("y ~ x", data)); // [2, -19.211]
166
+ * ```
167
+ *
168
+ * @category Model selection
169
+ */
170
+ export declare function extractAIC(fit: StepModel, options?: ExtractAicOptions): [number, number];
171
+ /**
172
+ * The models with one term dropped, for lm and glm. Equivalent to R's `drop1()`. With the change of the residual sum of squares or
173
+ * the deviance, the criterion of {@link extractAIC} (edf the rank) and optionally a test. As in R, each model is the
174
+ * fit's model matrix without the columns of the term, on the rows of `fit` (not a refit of a formula). By default
175
+ * only the terms not contained in another term of the model are dropped (marginality).
176
+ *
177
+ * @param fit A fit of {@link lm} or {@link glm} with a formula.
178
+ * @param data The data frame the fit was made from.
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
183
+ * drop1(lm("y ~ x + z", data), data, { test: "F" }).term; // ["<none>", "x", "z"]
184
+ * ```
185
+ *
186
+ * @category Model selection
187
+ */
188
+ export declare function drop1(fit: StepModel, data: DataFrame, options?: AddDropOptions): AddDropTable;
189
+ /**
190
+ * The models with one term added, for lm and glm. Equivalent to R's `add1()`. With the change of the residual sum of squares or the
191
+ * deviance, the criterion of {@link extractAIC} (edf the rank) and optionally a test. The terms are those of `scope`
192
+ * that can be added respecting marginality. Every model is refitted on the rows complete in the variables of the
193
+ * model and of all the terms; when these are fewer than the fit's rows the current model is refitted on them too,
194
+ * with R's warning "using the m/n rows from a combined fit".
195
+ *
196
+ * @param fit A fit of {@link lm} or {@link glm} with a formula.
197
+ * @param data The data frame the fit was made from.
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
202
+ * add1(lm("y ~ 1", data), data, { scope: "~ x + z" }).term; // ["<none>", "x", "z"]
203
+ * ```
204
+ *
205
+ * @category Model selection
206
+ */
207
+ export declare function add1(fit: StepModel, data: DataFrame, options?: AddDropOptions): AddDropTable;
208
+ /**
209
+ * Stepwise selection of the terms of a linear or generalized linear model by AIC. Equivalent to R's `step()`. From the start model,
210
+ * each step examines the models with one term dropped (respecting marginality, keeping the lower scope) and, with an
211
+ * upper scope, one term added, and moves to the one with the smallest criterion of {@link extractAIC} when it is
212
+ * strictly below the current model's; it stops when no move improves it, or after `steps` moves. `k = Math.log(n)`
213
+ * gives BIC. Terms whose columns are all aliased are removed first. The result holds the selected fit, the path
214
+ * (R's `$anova`) and every table examined (R's printed trace).
215
+ *
216
+ * As in R, the models are refitted on their own rows: when a move changes the number of rows used (a variable with
217
+ * missing values dropped or added) the search stops with an error, and the table of adds is computed on the rows
218
+ * complete in all the candidates' variables (with a warning when those are fewer).
219
+ *
220
+ * @param fit The start model: a fit of {@link lm} or {@link glm} with a formula.
221
+ * @param data The data frame the fit was made from.
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
226
+ * const s = step(lm("y ~ x + z", data), data);
227
+ * s.fit.formula; // "y ~ x"
228
+ * s.anova.step; // ["", "- z"]
229
+ * ```
230
+ *
231
+ * @category Model selection
232
+ */
233
+ export declare function step<F extends StepModel>(fit: F, data: DataFrame, options?: StepOptions): StepResult<F>;
234
+ /**
235
+ * Stepwise selection by AIC. Equivalent to `MASS::stepAIC()` in R. The same search as {@link step}; the only difference R shows is the
236
+ * path's `df`, which stepAIC gives as the size of the term moved (positive) where step gives the change of the
237
+ * residual degrees of freedom.
238
+ *
239
+ * @param fit The start model: a fit of {@link lm} or {@link glm} with a formula.
240
+ * @param data The data frame the fit was made from.
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
245
+ * stepAIC(lm("y ~ 1", data), data, { scope: "~ x + z" }).anova.df; // [NaN, 1]
246
+ * ```
247
+ *
248
+ * @category Model selection
249
+ */
250
+ export declare function stepAIC<F extends StepModel>(fit: F, data: DataFrame, options?: StepOptions): StepResult<F>;