@numero-uno-jpn/rstats 1.13.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.
- package/CHANGELOG.md +13 -0
- package/README.ja.md +7 -7
- package/README.md +7 -7
- package/dist/causal.js +2 -2
- package/dist/chunks/{chunk-LS55YUPZ.js → chunk-3K47QLCY.js} +2 -2
- package/dist/chunks/{chunk-XRB552MP.js → chunk-4EH3O466.js} +2 -2
- package/dist/chunks/{chunk-OWD2GUXJ.js → chunk-5BCXHJPF.js} +2 -2
- package/dist/chunks/{chunk-CKQOWTX7.js → chunk-5JKKIVYL.js} +2 -2
- package/dist/chunks/{chunk-JTARV4D3.js → chunk-5Q5YVM7S.js} +2 -2
- package/dist/chunks/{chunk-CCYGRSQW.js → chunk-6SZLUVSL.js} +2 -2
- package/dist/chunks/{chunk-C7NEFIAH.js → chunk-AGA7JCRF.js} +2 -2
- package/dist/chunks/{chunk-2SOBG73L.js → chunk-AILN2NGE.js} +2 -2
- package/dist/chunks/{chunk-CBAEKGP7.js → chunk-APOF7BLH.js} +2 -2
- package/dist/chunks/chunk-CIBAGTO2.js +4 -0
- package/dist/chunks/{chunk-UMLJFZJ5.js → chunk-FD375XBW.js} +2 -2
- package/dist/chunks/{chunk-CSZCDPF3.js → chunk-FV4ZQPRI.js} +2 -2
- package/dist/chunks/{chunk-5Y425VAJ.js → chunk-GBNGGBU3.js} +2 -2
- package/dist/chunks/{chunk-AH6IVJRF.js → chunk-HF4TT233.js} +1 -1
- package/dist/chunks/{chunk-7V6FRF32.js → chunk-HSVVCFEN.js} +2 -2
- package/dist/chunks/{chunk-RGEW3YLB.js → chunk-IMSXMJ43.js} +2 -2
- package/dist/chunks/{chunk-NRBTDLVW.js → chunk-JAXYZJV7.js} +2 -2
- package/dist/chunks/{chunk-3T4TVNXS.js → chunk-JGZSGGMD.js} +2 -2
- package/dist/chunks/{chunk-IIKFLH2E.js → chunk-KQGH6SEW.js} +2 -2
- package/dist/chunks/chunk-L7HJGM52.js +2 -0
- package/dist/chunks/{chunk-XRBNTYQW.js → chunk-M3HFLMXL.js} +2 -2
- package/dist/chunks/{chunk-DQ2MIFRQ.js → chunk-MKCPS5QQ.js} +2 -2
- package/dist/chunks/{chunk-P2UT6OCU.js → chunk-NULJXDAR.js} +2 -2
- package/dist/chunks/{chunk-2N7PIFPJ.js → chunk-OBTCIG5D.js} +2 -2
- package/dist/chunks/{chunk-CAOEREY3.js → chunk-OO22LZ7Q.js} +2 -2
- package/dist/chunks/chunk-P4TKSL4W.js +2 -0
- package/dist/chunks/{chunk-P6HSXCGZ.js → chunk-PZRABNMZ.js} +2 -2
- package/dist/chunks/{chunk-JJGRQ22M.js → chunk-R74QJUYU.js} +2 -2
- package/dist/chunks/{chunk-EWJS4VYF.js → chunk-RHNGF7R7.js} +2 -2
- package/dist/chunks/{chunk-7ZKPFHAO.js → chunk-RV4JZHTE.js} +2 -2
- package/dist/chunks/{chunk-GRXOLZ6J.js → chunk-SMA62635.js} +2 -2
- package/dist/chunks/{chunk-24UIPUSE.js → chunk-SNQABDAT.js} +1 -1
- package/dist/chunks/{chunk-OVJU5WCL.js → chunk-U5UOVXKD.js} +2 -2
- package/dist/chunks/{chunk-2BXB6DRK.js → chunk-UFJFVNC6.js} +1 -1
- package/dist/chunks/{chunk-Y4UWFH4Q.js → chunk-VHBIWPB4.js} +2 -2
- package/dist/chunks/{chunk-NWWY2WMF.js → chunk-VHMFOILD.js} +2 -2
- package/dist/chunks/{chunk-ST6I33C6.js → chunk-VO3E4Q6H.js} +1 -1
- package/dist/chunks/{chunk-KOF2HBUV.js → chunk-WL3JGBLZ.js} +2 -2
- package/dist/chunks/{chunk-TQ4P6W3P.js → chunk-XVRRYHLM.js} +2 -2
- package/dist/chunks/{chunk-CEY7FHMZ.js → chunk-YYLBBEWZ.js} +2 -2
- package/dist/chunks/{chunk-M3LK23YR.js → chunk-ZDUVFNFH.js} +1 -1
- package/dist/chunks/{chunk-TTBKW2KL.js → chunk-ZUTVNRML.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/regression.d.ts +1 -0
- package/dist/entries/regression.js +2 -0
- package/dist/entries/tests.d.ts +2 -1
- package/dist/entries/tests.js +1 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -5
- package/dist/models/fitOptions.d.ts +4 -0
- package/dist/models/fitOptions.js +14 -0
- package/dist/models/glm.d.ts +67 -5
- package/dist/models/glm.js +105 -27
- package/dist/models/glmerStructure.d.ts +5 -0
- package/dist/models/glmerStructure.js +2 -2
- package/dist/models/lm.js +3 -1
- package/dist/models/multinom.d.ts +250 -0
- package/dist/models/multinom.js +520 -0
- package/dist/models/step.d.ts +250 -0
- package/dist/models/step.js +592 -0
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -3
- package/dist/rstats.js +17 -17
- package/dist/special.js +2 -2
- package/dist/tests.js +14 -14
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-DZLOU6HK.js +0 -2
- package/dist/chunks/chunk-GQ4HYF4L.js +0 -3
- package/dist/chunks/chunk-QWXSJEDI.js +0 -2
- package/dist/chunks/chunk-VO65CBCV.js +0 -2
package/dist/models/glm.d.ts
CHANGED
|
@@ -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
|
|
174
|
-
* `glm(
|
|
175
|
-
*
|
|
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
|
/**
|
package/dist/models/glm.js
CHANGED
|
@@ -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 =
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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 FormulaNode } from "./formula.js";
|
|
2
|
+
import { type DesignContrast } from "./modelMatrix.js";
|
|
3
|
+
import type { DataFrame } from "./modelFrame.js";
|
|
4
|
+
import type { Sample } from "../htest/types.js";
|
|
5
|
+
/**
|
|
6
|
+
* Options for {@link multinom}.
|
|
7
|
+
*
|
|
8
|
+
* @category Regression
|
|
9
|
+
*/
|
|
10
|
+
export interface MultinomOptions {
|
|
11
|
+
/** Case weights, one per row of `data` (non-negative; need not be integers), or the name of a column of `data`. */
|
|
12
|
+
weights?: Sample | string;
|
|
13
|
+
/** Weight decay: `decay` times the sum of squares of all coefficients (intercepts included) is added to −log L, as
|
|
14
|
+
* nnet's `decay`. Default 0. */
|
|
15
|
+
decay?: number;
|
|
16
|
+
/** The order of the levels of factors (the response's first level is the reference category). */
|
|
17
|
+
levels?: Record<string, readonly string[]>;
|
|
18
|
+
/** A contrast per factor predictor (default `"contr.treatment"`). */
|
|
19
|
+
contrasts?: Record<string, "contr.treatment" | "contr.sum" | "contr.helmert">;
|
|
20
|
+
/** Maximum number of Newton iterations. Default 100. */
|
|
21
|
+
maxit?: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The data of a {@link multinom} fit kept for its methods.
|
|
25
|
+
*
|
|
26
|
+
* @category Regression
|
|
27
|
+
*/
|
|
28
|
+
export interface MultinomModel {
|
|
29
|
+
/** The formula. */
|
|
30
|
+
formula: string;
|
|
31
|
+
/** Parsed right-hand side; internal. @internal */
|
|
32
|
+
rhs: FormulaNode;
|
|
33
|
+
/** Predictor variables in model-matrix order. */
|
|
34
|
+
predictorVariables: string[];
|
|
35
|
+
/** Levels of the factor predictors. */
|
|
36
|
+
factorLevels: Record<string, readonly string[]>;
|
|
37
|
+
/** Contrasts used; internal. @internal */
|
|
38
|
+
contrasts: Record<string, DesignContrast>;
|
|
39
|
+
/** The model matrix (with its intercept column). */
|
|
40
|
+
x: number[][];
|
|
41
|
+
/** The response as level indices (0 is the reference). */
|
|
42
|
+
y: number[];
|
|
43
|
+
/** Case weights of the rows used. */
|
|
44
|
+
weights: number[];
|
|
45
|
+
/** 0-based rows of `data` used (rows with missing values are dropped). */
|
|
46
|
+
rows: number[];
|
|
47
|
+
/** The fit in its internal units; internal. @internal */
|
|
48
|
+
internal: {
|
|
49
|
+
centre: number[];
|
|
50
|
+
exps: number[];
|
|
51
|
+
kept: number[];
|
|
52
|
+
intercept: number;
|
|
53
|
+
scaledCoef: number[][];
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Result of {@link multinom}.
|
|
58
|
+
*
|
|
59
|
+
* @category Regression
|
|
60
|
+
*/
|
|
61
|
+
export interface MultinomResult {
|
|
62
|
+
/** The response's levels; the first is the reference category (R's `lev`). */
|
|
63
|
+
levels: string[];
|
|
64
|
+
/** Columns of the model matrix: `"(Intercept)"`, then the predictors' columns. */
|
|
65
|
+
columnNames: string[];
|
|
66
|
+
/** Coefficients, one row per non-reference level (R's `coef()`: rows `levels[1]`, ...). */
|
|
67
|
+
coefficients: number[][];
|
|
68
|
+
/** Standard errors, the same shape (from the inverse of the Hessian of −log L). */
|
|
69
|
+
se: number[][];
|
|
70
|
+
/** Variance matrix of the coefficients in R's order (`B:(Intercept)`, `B:x1`, ..., `C:(Intercept)`, ...). */
|
|
71
|
+
vcov: number[][];
|
|
72
|
+
/** Hessian of −log L in the same order (R's `Hessian` with `Hess = TRUE`; without the decay term, as R). */
|
|
73
|
+
hessian: number[][];
|
|
74
|
+
/** Names of the rows and columns of `vcov` and `hessian` (`"B:x1"`, ...). */
|
|
75
|
+
parameterNames: string[];
|
|
76
|
+
/** The minimised objective: −log L plus the decay penalty (R's `value`). */
|
|
77
|
+
value: number;
|
|
78
|
+
/** Twice `value` (R's `deviance`, which includes the penalty). */
|
|
79
|
+
deviance: number;
|
|
80
|
+
/** The log-likelihood as R reports it: −`value`. */
|
|
81
|
+
logLik: number;
|
|
82
|
+
/** Number of coefficients estimated, (K − 1) p less the aliased columns (R's `edf`). */
|
|
83
|
+
edf: number;
|
|
84
|
+
/** `deviance` + 2 `edf` (R's `AIC`). */
|
|
85
|
+
aic: number;
|
|
86
|
+
/** Fitted probabilities, one row per observation used, one column per level. */
|
|
87
|
+
fittedValues: number[][];
|
|
88
|
+
/** Number of observations used. */
|
|
89
|
+
n: number;
|
|
90
|
+
/** The decay used. */
|
|
91
|
+
decay: number;
|
|
92
|
+
/** Whether Newton's method met its tolerance on the score. */
|
|
93
|
+
converged: boolean;
|
|
94
|
+
/** Newton iterations. */
|
|
95
|
+
iter: number;
|
|
96
|
+
/** The data kept for the methods. */
|
|
97
|
+
model: MultinomModel;
|
|
98
|
+
/** R's warnings, each once. */
|
|
99
|
+
warnings: string[];
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Multinomial logistic regression: baseline-category logits for a response with two or more levels, the first level
|
|
103
|
+
* the reference. Equivalent to `nnet::multinom()` in R. The call followed is
|
|
104
|
+
* `multinom(y ~ ..., data, weights, decay, Hess = TRUE)`.
|
|
105
|
+
*
|
|
106
|
+
* The coefficients maximise the (weighted) log-likelihood less `decay` times the sum of squares of all coefficients,
|
|
107
|
+
* by Newton's method to machine precision; R's BFGS stops earlier (by default about 1e-5 from the maximum). The
|
|
108
|
+
* standard errors come from the Hessian of −log L (without the decay term, as R). A numeric response is made a factor;
|
|
109
|
+
* an unused level is dropped with R's warning; rows with missing values are dropped.
|
|
110
|
+
* @category Regression
|
|
111
|
+
* @example
|
|
112
|
+
* ```ts
|
|
113
|
+
* const data = { y: ["a", "b", "c", "b", "a", "c", "c", "a", "b", "a"], x: [1, 2, 3, 1.5, 2.2, 2.8, 1.9, 1.2, 3.1, 2.5] };
|
|
114
|
+
* const fit = multinom("y ~ x", data);
|
|
115
|
+
* fit.coefficients; // [[-2.503002448686904, 1.1313364602572131], [-4.9150873979421785, 2.1386561772142767]] (rows b, c)
|
|
116
|
+
* fit.deviance; // 18.97233634263671
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
export declare function multinom(formula: string, data: DataFrame, options?: MultinomOptions): MultinomResult;
|
|
120
|
+
/**
|
|
121
|
+
* Result of {@link multinomSummary}.
|
|
122
|
+
*
|
|
123
|
+
* @category Regression
|
|
124
|
+
*/
|
|
125
|
+
export interface MultinomSummaryResult {
|
|
126
|
+
/** Coefficients (rows the non-reference levels). */
|
|
127
|
+
coefficients: number[][];
|
|
128
|
+
/** Standard errors. */
|
|
129
|
+
se: number[][];
|
|
130
|
+
/** Wald z statistics, coefficient / standard error (R's `Wald.ratios`). */
|
|
131
|
+
zValue: number[][];
|
|
132
|
+
/** Two-sided p-values 2 (1 − Φ(|z|)). */
|
|
133
|
+
pValue: number[][];
|
|
134
|
+
/** exp(coefficients): the odds ratios against the reference level. */
|
|
135
|
+
oddsRatios: number[][];
|
|
136
|
+
/** Deviance of the fit (R's). */
|
|
137
|
+
deviance: number;
|
|
138
|
+
/** AIC of the fit (R's). */
|
|
139
|
+
aic: number;
|
|
140
|
+
/** Log-likelihood of the fit (R's). */
|
|
141
|
+
logLik: number;
|
|
142
|
+
/** The log-likelihood of the intercept-only model on the same rows and weights. */
|
|
143
|
+
nullLogLik: number;
|
|
144
|
+
/** McFadden's pseudo R²: 1 − logLik / nullLogLik. */
|
|
145
|
+
mcFadden: number;
|
|
146
|
+
/** Cox and Snell's: 1 − exp(2 (nullLogLik − logLik) / n). */
|
|
147
|
+
coxSnell: number;
|
|
148
|
+
/** Nagelkerke's: Cox and Snell's / (1 − exp(2 nullLogLik / n)). */
|
|
149
|
+
nagelkerke: number;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Summary of a multinomial logistic regression: Wald tests of the coefficients, odds ratios and pseudo R². Equivalent
|
|
153
|
+
* to `nnet::summary.multinom()` in R. The call followed is `summary(fit, Wald.ratios = TRUE)`, with the p-values, odds
|
|
154
|
+
* ratios and pseudo R² as ReactiveStat computes them (the null model `multinom(y ~ 1)` on the same rows, n the number
|
|
155
|
+
* of rows).
|
|
156
|
+
* @category Regression
|
|
157
|
+
*/
|
|
158
|
+
export declare function multinomSummary(fit: MultinomResult): MultinomSummaryResult;
|
|
159
|
+
/**
|
|
160
|
+
* Result of {@link multinomVcov}.
|
|
161
|
+
*
|
|
162
|
+
* @category Regression
|
|
163
|
+
*/
|
|
164
|
+
export interface MultinomVcovResult {
|
|
165
|
+
/** The variance matrix (array of rows). */
|
|
166
|
+
vcov: number[][];
|
|
167
|
+
/** Row and column names, `"B:(Intercept)"`, `"B:x1"`, ... */
|
|
168
|
+
names: string[];
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Variance matrix of the coefficients of a multinomial logistic regression. Equivalent to `nnet::vcov.multinom()` in R.
|
|
172
|
+
* @category Regression
|
|
173
|
+
*/
|
|
174
|
+
export declare function multinomVcov(fit: MultinomResult): MultinomVcovResult;
|
|
175
|
+
/**
|
|
176
|
+
* Options for {@link multinomConfint}.
|
|
177
|
+
*
|
|
178
|
+
* @category Regression
|
|
179
|
+
*/
|
|
180
|
+
export interface MultinomConfintOptions {
|
|
181
|
+
/** Confidence level. Default 0.95. */
|
|
182
|
+
level?: number;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Result of {@link multinomConfint}: limits with the shape of the coefficients.
|
|
186
|
+
*
|
|
187
|
+
* @category Regression
|
|
188
|
+
*/
|
|
189
|
+
export interface MultinomConfintResult {
|
|
190
|
+
/** Lower limits (rows the non-reference levels). */
|
|
191
|
+
lower: number[][];
|
|
192
|
+
/** Upper limits. */
|
|
193
|
+
upper: number[][];
|
|
194
|
+
/** The confidence level. */
|
|
195
|
+
level: number;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Wald confidence intervals of the coefficients of a multinomial logistic regression. Equivalent to
|
|
199
|
+
* `nnet::confint.multinom()` in R. The limits are coefficient ± qnorm((1 + level) / 2) se.
|
|
200
|
+
* @category Regression
|
|
201
|
+
*/
|
|
202
|
+
export declare function multinomConfint(fit: MultinomResult, options?: MultinomConfintOptions): MultinomConfintResult;
|
|
203
|
+
/**
|
|
204
|
+
* Options for {@link multinomPredict}.
|
|
205
|
+
*
|
|
206
|
+
* @category Regression
|
|
207
|
+
*/
|
|
208
|
+
export interface MultinomPredictOptions {
|
|
209
|
+
/** New values of the predictors (default: the rows of the fit). */
|
|
210
|
+
newdata?: DataFrame;
|
|
211
|
+
/** `"class"` (default): the most probable level; `"probs"`: the probabilities. */
|
|
212
|
+
type?: "class" | "probs";
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Predictions of a multinomial logistic regression: probabilities of the levels, or the most probable level. Equivalent
|
|
216
|
+
* to `nnet::predict.multinom()` in R.
|
|
217
|
+
*
|
|
218
|
+
* Ties are broken as R's `max.col`: probabilities within 1e-5 (relative) of the row's largest are tied, and the k-th
|
|
219
|
+
* tied level replaces the choice when k u < 1, u a uniform of {@link runif} (one per tie after the first), so the
|
|
220
|
+
* classes are R's after the same `setSeed`.
|
|
221
|
+
* @category Regression
|
|
222
|
+
*/
|
|
223
|
+
export declare function multinomPredict(fit: MultinomResult, options?: MultinomPredictOptions): string[] | number[][];
|
|
224
|
+
/**
|
|
225
|
+
* Result of {@link multinomAnova}: one row per model, in increasing order of the number of coefficients.
|
|
226
|
+
*
|
|
227
|
+
* @category Regression
|
|
228
|
+
*/
|
|
229
|
+
export interface MultinomAnovaResult {
|
|
230
|
+
/** The right-hand sides of the formulas (`"1"` for the intercept-only model). */
|
|
231
|
+
model: string[];
|
|
232
|
+
/** Residual degrees of freedom, n (K − 1) − edf. */
|
|
233
|
+
residDf: number[];
|
|
234
|
+
/** Deviances. */
|
|
235
|
+
residDev: number[];
|
|
236
|
+
/** `"1 vs 2"`, ... (`""` for the first). */
|
|
237
|
+
test: string[];
|
|
238
|
+
/** Degrees of freedom of each test (NaN for the first). */
|
|
239
|
+
df: number[];
|
|
240
|
+
/** Likelihood-ratio statistics, the differences of deviances (NaN for the first). */
|
|
241
|
+
lrStat: number[];
|
|
242
|
+
/** Upper chi-squared p-values (NaN for the first). */
|
|
243
|
+
pValue: number[];
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Likelihood-ratio tests of nested multinomial logistic regressions. Equivalent to `nnet::anova.multinom()` in R. The
|
|
247
|
+
* models are ordered by their residual degrees of freedom (largest first), whatever the order given.
|
|
248
|
+
* @category Regression
|
|
249
|
+
*/
|
|
250
|
+
export declare function multinomAnova(...fits: MultinomResult[]): MultinomAnovaResult;
|