@numero-uno-jpn/rstats 0.17.0 → 1.0.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 +77 -0
- package/README.ja.md +18 -10
- package/README.md +20 -10
- package/dist/chunks/{chunk-Z37NELOS.js → chunk-3W5NFFAA.js} +1 -1
- package/dist/chunks/{chunk-2C33MXSW.js → chunk-4F2IALD4.js} +2 -2
- package/dist/chunks/{chunk-H3WVPZDL.js → chunk-4OLDGML4.js} +2 -2
- package/dist/chunks/{chunk-WM7VFXTV.js → chunk-63OPBEYO.js} +1 -1
- package/dist/chunks/{chunk-TNMJPQPV.js → chunk-6XJBCRBV.js} +2 -2
- package/dist/chunks/{chunk-RFE7MVP7.js → chunk-BQSIBJVX.js} +2 -2
- package/dist/chunks/{chunk-C7V2FH6L.js → chunk-BWKHYRM6.js} +1 -1
- package/dist/chunks/{chunk-SE7V2KLO.js → chunk-CKV4JWW2.js} +1 -1
- package/dist/chunks/{chunk-CZI7KUO3.js → chunk-DCAWMF4K.js} +2 -2
- package/dist/chunks/{chunk-5AYHCITP.js → chunk-F7YGX7PN.js} +2 -2
- package/dist/chunks/chunk-H7I32ZZE.js +2 -0
- package/dist/chunks/chunk-IEOD5GWC.js +3 -0
- package/dist/chunks/{chunk-XLSFJTTK.js → chunk-KICBQGFN.js} +2 -2
- package/dist/chunks/chunk-LROMWFAK.js +2 -0
- package/dist/chunks/{chunk-DXI5N2ET.js → chunk-NSWENS3S.js} +1 -1
- package/dist/chunks/chunk-O2SQMGE3.js +2 -0
- package/dist/chunks/{chunk-FY3FVOBM.js → chunk-QQX46TCI.js} +2 -2
- package/dist/chunks/{chunk-ZFQWB222.js → chunk-QZK3CCBA.js} +2 -2
- package/dist/chunks/{chunk-6JJQL6HL.js → chunk-UJ66VQIG.js} +2 -2
- package/dist/chunks/{chunk-ONY5CISH.js → chunk-UKNDX4BA.js} +2 -2
- package/dist/chunks/chunk-WIBKS73G.js +2 -0
- package/dist/chunks/{chunk-4WE3OO62.js → chunk-WQWZ7FND.js} +2 -2
- package/dist/chunks/{chunk-LHUIJQHY.js → chunk-WWVMVZUL.js} +2 -2
- package/dist/chunks/{chunk-LV3W2F7N.js → chunk-YG5S5AVP.js} +2 -2
- package/dist/chunks/{chunk-34S5SQY6.js → chunk-YHNMBYSW.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +6 -0
- package/dist/entries/mixed.js +6 -1
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +5 -4
- package/dist/models/formula.d.ts +5 -2
- package/dist/models/formula.js +31 -8
- package/dist/models/glmer.d.ts +255 -0
- package/dist/models/glmer.js +635 -0
- package/dist/models/glmerAnova.d.ts +81 -0
- package/dist/models/glmerAnova.js +139 -0
- package/dist/models/glmerDeviance.d.ts +98 -0
- package/dist/models/glmerDeviance.js +576 -0
- package/dist/models/glmerFamily.d.ts +57 -0
- package/dist/models/glmerFamily.js +236 -0
- package/dist/models/glmerGradient.d.ts +46 -0
- package/dist/models/glmerGradient.js +301 -0
- package/dist/models/glmerStructure.d.ts +45 -0
- package/dist/models/glmerStructure.js +168 -0
- package/dist/models/glmerSummary.d.ts +102 -0
- package/dist/models/glmerSummary.js +94 -0
- package/dist/models/lmer.d.ts +16 -0
- package/dist/models/lmer.js +55 -306
- package/dist/models/lmerAnova.d.ts +49 -0
- package/dist/models/lmerAnova.js +91 -40
- package/dist/models/lmerTest.d.ts +8 -1
- package/dist/models/lmerTest.js +21 -8
- package/dist/models/mixedDeviance.d.ts +28 -2
- package/dist/models/mixedDeviance.js +84 -56
- package/dist/models/mixedMinimiser.d.ts +83 -0
- package/dist/models/mixedMinimiser.js +438 -0
- package/dist/models/mixedPredict.d.ts +121 -0
- package/dist/models/mixedPredict.js +530 -0
- package/dist/models/mixedStructure.d.ts +62 -3
- package/dist/models/mixedStructure.js +74 -29
- package/dist/models/modelMatrix.d.ts +8 -1
- package/dist/models/modelMatrix.js +49 -37
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +11 -11
- package/dist/special.js +2 -2
- package/dist/tests.js +13 -14
- package/llms.txt +10 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-M4ITG7YR.js +0 -2
- package/dist/chunks/chunk-NSYZTS26.js +0 -2
- package/dist/chunks/chunk-THIGHOKK.js +0 -2
- package/dist/chunks/chunk-WMDYDTVQ.js +0 -2
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The structure of a generalised linear mixed model (lme4's glmer): the structure of the mixed model (with glmer's
|
|
2
|
+
// checks, src/models/mixedStructure.ts), the family and its link, the prior weights and the offset, and the response
|
|
3
|
+
// as the family reads it, with the starting means. Nothing is fitted here.
|
|
4
|
+
//
|
|
5
|
+
// Written for rStats.js (no ported code) from oracle/glmer-behaviour.md ("The model structure: what differs from
|
|
6
|
+
// lmer", "The response", "Prior weights and offset", "The structure and its checks") and its section "rStats.js's
|
|
7
|
+
// choices" (G1 to G5), with the two messages of nAGQ > 1 ("Adaptive Gauss-Hermite quadrature", "When it is allowed").
|
|
8
|
+
import { Warnings, withWarnings } from "../internal/warnings.js";
|
|
9
|
+
import { prepareResponse } from "./glmFamily.js";
|
|
10
|
+
import { glmerFamily } from "./glmerFamily.js";
|
|
11
|
+
import { parseFormula } from "./formula.js";
|
|
12
|
+
import { mixedModelStructure } from "./mixedStructure.js";
|
|
13
|
+
/** A weights or offset argument as numbers over all rows of the data (NaN for missing) */
|
|
14
|
+
function rowValues(given, data, nAll, what) {
|
|
15
|
+
let col;
|
|
16
|
+
if (typeof given === "string") {
|
|
17
|
+
col = Object.hasOwn(data, given) ? data[given] : undefined;
|
|
18
|
+
if (col === undefined)
|
|
19
|
+
throw new RangeError(`object '${given}' not found`);
|
|
20
|
+
}
|
|
21
|
+
else
|
|
22
|
+
col = given;
|
|
23
|
+
if (!Array.isArray(col) && !(col instanceof Float64Array))
|
|
24
|
+
throw new TypeError(`${what} must be an array of numbers or the name of a column`);
|
|
25
|
+
const values = Array.from(col, (x) => {
|
|
26
|
+
if (x === null)
|
|
27
|
+
return NaN;
|
|
28
|
+
if (typeof x !== "number")
|
|
29
|
+
throw new TypeError(`the ${what} must be numeric`);
|
|
30
|
+
return x;
|
|
31
|
+
});
|
|
32
|
+
if (values.length !== nAll)
|
|
33
|
+
throw new RangeError(`variable lengths differ (found for '(${what})')`);
|
|
34
|
+
return values;
|
|
35
|
+
}
|
|
36
|
+
/** Whether a column of the data holds booleans (a logical response is 0/1, not a factor) */
|
|
37
|
+
const isLogicalColumn = (data, name) => {
|
|
38
|
+
const col = Object.hasOwn(data, name) ? data[name] : undefined;
|
|
39
|
+
return Array.isArray(col) && col.some((v) => typeof v === "boolean");
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The structure of a generalised linear mixed model `response ~ fixed part + (lhs | group) + ...` with lme4's checks,
|
|
43
|
+
* errors and warnings (oracle/glmer-behaviour.md, stage 2a). The response may be `cbind(successes, failures)` (two
|
|
44
|
+
* column names, binomial only) and, for binomial, strings (a factor: the first level is failure). Internal: not
|
|
45
|
+
* exported from the package.
|
|
46
|
+
*
|
|
47
|
+
* @param formula A formula such as `"y ~ x + (1 | g)"` or `"cbind(s, f) ~ period + (1 | herd)"`.
|
|
48
|
+
* @param data The data frame: an object of columns.
|
|
49
|
+
* @param options The family and link, prior weights, offset, nAGQ, contrasts and level order of factors.
|
|
50
|
+
*/
|
|
51
|
+
export function glmerStructure(formula, data, options = {}) {
|
|
52
|
+
// the family first of all (quasi families; gaussian with the identity link, G3)
|
|
53
|
+
const family = glmerFamily(options.family, options.link);
|
|
54
|
+
// nAGQ: an integer from 0 to 100, truncated first as R's as.integer (rule 9: −0.5 is 0); negative after that an
|
|
55
|
+
// error here (G5; R uses 0)
|
|
56
|
+
const nAGQgiven = options.nAGQ ?? 1;
|
|
57
|
+
if (typeof nAGQgiven !== "number" || Number.isNaN(nAGQgiven))
|
|
58
|
+
throw new TypeError("nAGQ must be a number");
|
|
59
|
+
// (+ 0: −0 becomes 0)
|
|
60
|
+
const nAGQ = Math.trunc(nAGQgiven) + 0;
|
|
61
|
+
if (nAGQ < 0)
|
|
62
|
+
throw new RangeError("nAGQ must be non-negative");
|
|
63
|
+
if (nAGQ > 100)
|
|
64
|
+
throw new RangeError("nAGQ <= 100L is not TRUE");
|
|
65
|
+
if (typeof data !== "object" || data === null)
|
|
66
|
+
throw new TypeError("data must be an object of columns");
|
|
67
|
+
// the rows with a missing weight or offset are dropped with the others: the data restricted to the other rows
|
|
68
|
+
// first (the same model frame, as the levels of factors are formed from the rows kept)
|
|
69
|
+
const parsed = parseFormula(formula, false, true, true);
|
|
70
|
+
const firstColumn = parsed.response !== undefined && Object.hasOwn(data, parsed.response) ? data[parsed.response] : Object.values(data)[0];
|
|
71
|
+
const nAll = firstColumn?.length ?? 0;
|
|
72
|
+
const weightsAll = options.weights === undefined ? undefined : rowValues(options.weights, data, nAll, "weights");
|
|
73
|
+
const offsetAll = options.offset === undefined ? undefined : rowValues(options.offset, data, nAll, "offset");
|
|
74
|
+
let kept;
|
|
75
|
+
let frameData = data;
|
|
76
|
+
if (weightsAll !== undefined || offsetAll !== undefined) {
|
|
77
|
+
kept = [];
|
|
78
|
+
for (let i = 0; i < nAll; i++)
|
|
79
|
+
if (!Number.isNaN(weightsAll?.[i] ?? 0) && !Number.isNaN(offsetAll?.[i] ?? 0))
|
|
80
|
+
kept.push(i);
|
|
81
|
+
if (kept.length < nAll) {
|
|
82
|
+
const rows = kept;
|
|
83
|
+
frameData = Object.fromEntries(Object.entries(data).map(([k, col]) => [k, col.length === nAll ? (col instanceof Float64Array ? Float64Array.from(rows, (i) => col[i]) : rows.map((i) => col[i])) : col]));
|
|
84
|
+
}
|
|
85
|
+
else
|
|
86
|
+
kept = undefined;
|
|
87
|
+
}
|
|
88
|
+
const { levels, contrasts } = options;
|
|
89
|
+
const s = mixedModelStructure(formula, frameData, { ...(levels === undefined ? {} : { levels }), ...(contrasts === undefined ? {} : { contrasts }) }, true);
|
|
90
|
+
const rows = kept === undefined ? s.rows : s.rows.map((i) => kept[i]);
|
|
91
|
+
const n = rows.length;
|
|
92
|
+
// nAGQ > 1: exactly one term with one column, with R's two messages from its two checks (terms in lmer's order):
|
|
93
|
+
// several grouping factors or a first term with several columns, then several terms of one factor
|
|
94
|
+
if (nAGQ > 1) {
|
|
95
|
+
if (s.groups.length > 1 || s.terms[0].columns.length > 1) {
|
|
96
|
+
throw new RangeError("nAGQ > 1 is only available for models with a single, scalar random-effects term");
|
|
97
|
+
}
|
|
98
|
+
if (s.terms.length > 1)
|
|
99
|
+
throw new RangeError("AGQ only defined for a single scalar random-effects term");
|
|
100
|
+
}
|
|
101
|
+
// the response, as lme4 reads it before the family's initialize
|
|
102
|
+
const response = s.response;
|
|
103
|
+
const twoColumns = parsed.responseColumns !== undefined;
|
|
104
|
+
if (twoColumns && family.family !== "binomial")
|
|
105
|
+
throw new TypeError("can't handle matrix-valued responses: consider using refit()");
|
|
106
|
+
const numeric = (v, name, message) => {
|
|
107
|
+
if (v.kind === "numeric")
|
|
108
|
+
return v.values;
|
|
109
|
+
// a logical column (levels FALSE and TRUE) is 0/1; a factor is accepted by binomial only (not in cbind)
|
|
110
|
+
if (isLogicalColumn(frameData, name) && options.levels?.[name] === undefined)
|
|
111
|
+
return v.codes.map((c) => (v.levels[c] === "TRUE" ? 1 : 0));
|
|
112
|
+
throw new TypeError(message);
|
|
113
|
+
};
|
|
114
|
+
let yGiven;
|
|
115
|
+
if (twoColumns) {
|
|
116
|
+
const [a, b] = parsed.responseColumns;
|
|
117
|
+
const sv = numeric(response[0], a, "response must be numeric or factor");
|
|
118
|
+
const fv = numeric(response[1], b, "response must be numeric or factor");
|
|
119
|
+
yGiven = sv.map((v, i) => [v, fv[i]]);
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
const v = response[0];
|
|
123
|
+
const name = parsed.response;
|
|
124
|
+
if (family.family === "binomial" && v.kind === "factor" && !(isLogicalColumn(frameData, name) && options.levels?.[name] === undefined)) {
|
|
125
|
+
// a factor, or strings (G2): 0 for the first level, 1 for the others
|
|
126
|
+
yGiven = v.codes.map((c) => (c === 0 ? 0 : 1));
|
|
127
|
+
}
|
|
128
|
+
else
|
|
129
|
+
yGiven = numeric(v, name, family.family === "binomial" ? "response must be numeric or factor" : "response must be numeric");
|
|
130
|
+
}
|
|
131
|
+
const flat = twoColumns ? yGiven.flat() : yGiven;
|
|
132
|
+
if (flat.some((v) => !Number.isFinite(v)))
|
|
133
|
+
throw new RangeError("NA/NaN/Inf in 'y'");
|
|
134
|
+
const offset = offsetAll === undefined ? new Array(n).fill(0) : rows.map((i) => offsetAll[i]);
|
|
135
|
+
// (an infinite offset or weight: not described for lme4; errors here, as glm's)
|
|
136
|
+
if (offset.some((v) => !Number.isFinite(v)))
|
|
137
|
+
throw new RangeError("the offset must be finite");
|
|
138
|
+
const prior = weightsAll === undefined ? new Array(n).fill(1) : rows.map((i) => weightsAll[i]);
|
|
139
|
+
if (prior.some((v) => v < 0))
|
|
140
|
+
throw new RangeError("all(weights >= 0) is not TRUE");
|
|
141
|
+
if (prior.some((v) => !Number.isFinite(v)))
|
|
142
|
+
throw new RangeError("non-finite weights not allowed");
|
|
143
|
+
// the family's checks and starting means (glm's, with their messages and warnings)
|
|
144
|
+
const warnings = new Warnings();
|
|
145
|
+
for (const w of s.warnings)
|
|
146
|
+
warnings.add(w);
|
|
147
|
+
const prepared = withWarnings(warnings, () => prepareResponse(family.glm, yGiven, prior, false, warnings));
|
|
148
|
+
let { mustart } = prepared;
|
|
149
|
+
if (family.family === "Gamma") {
|
|
150
|
+
// lme4 replaces Gamma's starting means by their (unweighted) mean
|
|
151
|
+
const mean = mustart.reduce((sum, v) => sum + v, 0) / mustart.length;
|
|
152
|
+
mustart = mustart.map(() => mean);
|
|
153
|
+
}
|
|
154
|
+
if (new Set(prepared.y).size < 2)
|
|
155
|
+
throw new RangeError("Response is constant");
|
|
156
|
+
return {
|
|
157
|
+
...s,
|
|
158
|
+
rows,
|
|
159
|
+
y: prepared.y,
|
|
160
|
+
family,
|
|
161
|
+
weights: prepared.weights,
|
|
162
|
+
offset,
|
|
163
|
+
size: family.family === "binomial" ? prepared.size : undefined,
|
|
164
|
+
mustart,
|
|
165
|
+
nAGQ,
|
|
166
|
+
warnings: warnings.list,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { GlmLinkName } from "./glmFamily.js";
|
|
2
|
+
import type { GlmerFamilyName } from "./glmerFamily.js";
|
|
3
|
+
import { type GlmerResult } from "./glmer.js";
|
|
4
|
+
import { type LmerVarCorr } from "./lmer.js";
|
|
5
|
+
/**
|
|
6
|
+
* Options of {@link glmerSummary}: there is none yet. R's `correlation`, `use.hessian` and `useHessian` give the
|
|
7
|
+
* Error `glmerSummary: argument '<key>' is not supported`, any other key a RangeError.
|
|
8
|
+
*
|
|
9
|
+
* @category Mixed models
|
|
10
|
+
*/
|
|
11
|
+
export interface GlmerSummaryOptions {
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Result of {@link glmerSummary}: lme4's `summary()` of a glmer fit.
|
|
15
|
+
*
|
|
16
|
+
* @category Mixed models
|
|
17
|
+
*/
|
|
18
|
+
export interface GlmerSummary {
|
|
19
|
+
/** The family (R's `Family:` line). */
|
|
20
|
+
family: GlmerFamilyName;
|
|
21
|
+
/** The link. */
|
|
22
|
+
link: GlmLinkName;
|
|
23
|
+
/** The fit's nAGQ (R's title: Laplace approximation for 1, adaptive Gauss-Hermite quadrature otherwise). */
|
|
24
|
+
nAGQ: number;
|
|
25
|
+
/** Names of the fixed effects (R's row names). */
|
|
26
|
+
names: string[];
|
|
27
|
+
/** Estimates (R's `Estimate`). */
|
|
28
|
+
estimate: number[];
|
|
29
|
+
/** Standard errors (R's `Std. Error`, from the fit's `vcov`). */
|
|
30
|
+
stdError: number[];
|
|
31
|
+
/** Estimates over standard errors (R's third column). */
|
|
32
|
+
statistic: number[];
|
|
33
|
+
/** The third column's name: `"z value"` for binomial and poisson, `"t value"` for the families with a dispersion. */
|
|
34
|
+
statisticName: "z value" | "t value";
|
|
35
|
+
/**
|
|
36
|
+
* Two-sided p-values from the normal distribution, 2 pnorm(−|statistic|) (R's `Pr(>|z|)`), for every family: lme4
|
|
37
|
+
* uses no t distribution for the families with a dispersion either.
|
|
38
|
+
*/
|
|
39
|
+
pValue: number[];
|
|
40
|
+
/** The correlation of the fixed effects (R's `cov2cor(vcov(fit))`; array of rows, 1 on the diagonal). */
|
|
41
|
+
correlation: number[][];
|
|
42
|
+
/** The variance components (R's `VarCorr()`, not scaled by sigma; no residual row). */
|
|
43
|
+
varCorr: LmerVarCorr[];
|
|
44
|
+
/** The number of levels of each grouping factor (R's `ngrps()`), in the order of the fit's `ranef`. */
|
|
45
|
+
nGroups: {
|
|
46
|
+
group: string;
|
|
47
|
+
levels: number;
|
|
48
|
+
}[];
|
|
49
|
+
/** Number of observations (R's `Number of obs`). */
|
|
50
|
+
nObs: number;
|
|
51
|
+
/** The log-likelihood (the fit's). */
|
|
52
|
+
logLik: number;
|
|
53
|
+
/** Akaike's information criterion. */
|
|
54
|
+
AIC: number;
|
|
55
|
+
/** Schwarz's Bayesian information criterion. */
|
|
56
|
+
BIC: number;
|
|
57
|
+
/** Degrees of freedom of the log-likelihood (the fit's `df`). */
|
|
58
|
+
df: number;
|
|
59
|
+
/** −2 logLik (R's `-2*log(L)`; the fit's `deviance` is R's `deviance()`, another quantity). */
|
|
60
|
+
minus2LogLik: number;
|
|
61
|
+
/** nObs − df (R's `df.resid`). */
|
|
62
|
+
dfResidual: number;
|
|
63
|
+
/** Minimum, quartiles, median and maximum of the Pearson residuals divided by sigma (R's `Scaled residuals`). */
|
|
64
|
+
residualQuantiles: number[];
|
|
65
|
+
/** R's `sigma()` (1 for binomial and poisson). */
|
|
66
|
+
sigma: number;
|
|
67
|
+
/** R's messages (a rank-deficient fixed-effects matrix, a singular fit). */
|
|
68
|
+
messages: string[];
|
|
69
|
+
/** R's warnings (the fallback of vcov to R_X, if the fit gave it). */
|
|
70
|
+
warnings: string[];
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The summary of a generalized linear mixed model fitted by {@link glmer}: the coefficient table with p-values, the
|
|
74
|
+
* correlation of the fixed effects, the quantiles of the scaled residuals, the information criteria, the variance
|
|
75
|
+
* components and the numbers of groups. Equivalent to `lme4::summary()` in R.
|
|
76
|
+
*
|
|
77
|
+
* The p-values are from the normal distribution for every family, as lme4's (whose third column is named `t value`
|
|
78
|
+
* for the families with a dispersion, although its p-values are normal ones). The values are those of the fit at the
|
|
79
|
+
* exact optimum (see {@link glmer}), so they typically differ from lme4's in the 4th to 6th significant digit. For
|
|
80
|
+
* `nAGQ > 1`, `logLik`, `AIC`, `BIC` and `minus2LogLik` are those of the log-likelihood, as the fit's.
|
|
81
|
+
*
|
|
82
|
+
* @param fit A result of {@link glmer} (the object it returned, not a copy).
|
|
83
|
+
* @param options None yet (see {@link GlmerSummaryOptions}).
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* // R: summary(lme4::glmer(y ~ x + (1 | g), data, family = poisson))
|
|
88
|
+
* const fit = glmer("y ~ x + (1 | g)", {
|
|
89
|
+
* y: [2, 3, 6, 7, 8, 1, 0, 3, 2, 5, 4, 6, 9, 8, 13, 0, 2, 1, 4, 3],
|
|
90
|
+
* x: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
|
|
91
|
+
* g: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d"],
|
|
92
|
+
* }, { family: "poisson" });
|
|
93
|
+
* const s = glmerSummary(fit);
|
|
94
|
+
* s.statisticName; // "z value"
|
|
95
|
+
* s.pValue; // [0.5482, 6.226e-5]
|
|
96
|
+
* s.minus2LogLik; // 78.785
|
|
97
|
+
* s.dfResidual; // 17
|
|
98
|
+
* ```
|
|
99
|
+
*
|
|
100
|
+
* @category Mixed models
|
|
101
|
+
*/
|
|
102
|
+
export declare function glmerSummary(fit: GlmerResult, options?: GlmerSummaryOptions): GlmerSummary;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// The summary of a generalized linear mixed model fitted by glmer (src/models/glmer.ts): lme4's summary() of a glmer
|
|
2
|
+
// fit, as numbers (the coefficient table with the normal p-values, the correlation of the fixed effects, the scaled
|
|
3
|
+
// residuals' quantiles, the information criteria, the variance components and the numbers of groups).
|
|
4
|
+
//
|
|
5
|
+
// Written for rStats.js (no ported code) from oracle/glmer-behaviour.md ("glmerSummary (stage 3)" and "rStats.js's
|
|
6
|
+
// choices"). Everything comes from the fit's fields except the quantiles of the scaled residuals and the correlation.
|
|
7
|
+
import { pnorm } from "../distributions/normal.js";
|
|
8
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
9
|
+
import { reported } from "../internal/warnings.js";
|
|
10
|
+
import { glmerInternals, VCOV_FALLBACK } from "./glmer.js";
|
|
11
|
+
import { checkLmerOptions } from "./lmer.js";
|
|
12
|
+
/** R's type-7 quantile of sorted values at probability prob */
|
|
13
|
+
function quantile7(sorted, prob) {
|
|
14
|
+
const n = sorted.length;
|
|
15
|
+
if (n === 0)
|
|
16
|
+
return NaN;
|
|
17
|
+
const h = (n - 1) * prob;
|
|
18
|
+
const lo = Math.floor(h);
|
|
19
|
+
const a = sorted[lo];
|
|
20
|
+
return lo + 1 < n ? a + (h - lo) * (sorted[lo + 1] - a) : a;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The summary of a generalized linear mixed model fitted by {@link glmer}: the coefficient table with p-values, the
|
|
24
|
+
* correlation of the fixed effects, the quantiles of the scaled residuals, the information criteria, the variance
|
|
25
|
+
* components and the numbers of groups. Equivalent to `lme4::summary()` in R.
|
|
26
|
+
*
|
|
27
|
+
* The p-values are from the normal distribution for every family, as lme4's (whose third column is named `t value`
|
|
28
|
+
* for the families with a dispersion, although its p-values are normal ones). The values are those of the fit at the
|
|
29
|
+
* exact optimum (see {@link glmer}), so they typically differ from lme4's in the 4th to 6th significant digit. For
|
|
30
|
+
* `nAGQ > 1`, `logLik`, `AIC`, `BIC` and `minus2LogLik` are those of the log-likelihood, as the fit's.
|
|
31
|
+
*
|
|
32
|
+
* @param fit A result of {@link glmer} (the object it returned, not a copy).
|
|
33
|
+
* @param options None yet (see {@link GlmerSummaryOptions}).
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* // R: summary(lme4::glmer(y ~ x + (1 | g), data, family = poisson))
|
|
38
|
+
* const fit = glmer("y ~ x + (1 | g)", {
|
|
39
|
+
* y: [2, 3, 6, 7, 8, 1, 0, 3, 2, 5, 4, 6, 9, 8, 13, 0, 2, 1, 4, 3],
|
|
40
|
+
* x: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
|
|
41
|
+
* g: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d"],
|
|
42
|
+
* }, { family: "poisson" });
|
|
43
|
+
* const s = glmerSummary(fit);
|
|
44
|
+
* s.statisticName; // "z value"
|
|
45
|
+
* s.pValue; // [0.5482, 6.226e-5]
|
|
46
|
+
* s.minus2LogLik; // 78.785
|
|
47
|
+
* s.dfResidual; // 17
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* @category Mixed models
|
|
51
|
+
*/
|
|
52
|
+
export function glmerSummary(fit, options) {
|
|
53
|
+
checkLmerOptions("glmerSummary", options, ["correlation", "use.hessian", "useHessian"]);
|
|
54
|
+
// (written by hand: option-keys.mjs generates no check for an options type without keys)
|
|
55
|
+
checkOptions(options, [], "glmerSummary");
|
|
56
|
+
glmerInternals(fit);
|
|
57
|
+
const { estimate, stdError, zValue } = fit.coefTable;
|
|
58
|
+
const v = fit.vcov;
|
|
59
|
+
const correlation = v.map((row, i) =>
|
|
60
|
+
// (R's cov2cor sets the diagonal to 1; a variance of 0 gives NaN off the diagonal, as R's 0/0; divided by each
|
|
61
|
+
// standard deviation in turn, as cov2cor multiplies by each 1/sd, since the product of two variances overflows
|
|
62
|
+
// or underflows for predictors of scale 1e120 or 1e-120)
|
|
63
|
+
row.map((c, j) => (i === j ? 1 : v[i][i] === 0 || v[j][j] === 0 ? NaN : c / Math.sqrt(v[i][i]) / Math.sqrt(v[j][j]))));
|
|
64
|
+
const scaled = fit.pearsonResiduals.map((r) => r / fit.sigma).sort((a, b) => a - b);
|
|
65
|
+
const dispersionFamily = fit.family !== "binomial" && fit.family !== "poisson";
|
|
66
|
+
return reported("glmerSummary", {
|
|
67
|
+
family: fit.family,
|
|
68
|
+
link: fit.link,
|
|
69
|
+
nAGQ: fit.nAGQ,
|
|
70
|
+
names: [...fit.fixefNames],
|
|
71
|
+
estimate: [...estimate],
|
|
72
|
+
stdError: [...stdError],
|
|
73
|
+
statistic: [...zValue],
|
|
74
|
+
// (lme4 names the column after whether the family has a dispersion)
|
|
75
|
+
statisticName: dispersionFamily ? "t value" : "z value",
|
|
76
|
+
// (normal p-values for every family, as lme4's, also where it names the statistic t)
|
|
77
|
+
pValue: zValue.map((z) => (Number.isNaN(z) ? NaN : 2 * pnorm(-Math.abs(z)))),
|
|
78
|
+
correlation,
|
|
79
|
+
varCorr: fit.varCorr.map((t) => ({ group: t.group, columns: [...t.columns], sd: [...t.sd], corr: t.corr.map((row) => [...row]) })),
|
|
80
|
+
nGroups: fit.ranef.map((g) => ({ group: g.group, levels: g.levels.length })),
|
|
81
|
+
nObs: fit.nObs,
|
|
82
|
+
logLik: fit.logLik,
|
|
83
|
+
AIC: fit.AIC,
|
|
84
|
+
BIC: fit.BIC,
|
|
85
|
+
df: fit.df,
|
|
86
|
+
minus2LogLik: -2 * fit.logLik,
|
|
87
|
+
dfResidual: fit.nObs - fit.df,
|
|
88
|
+
residualQuantiles: [0, 0.25, 0.5, 0.75, 1].map((q) => quantile7(scaled, q)),
|
|
89
|
+
sigma: fit.sigma,
|
|
90
|
+
messages: [...fit.messages],
|
|
91
|
+
// (R's summary computes vcov again, so its fallback warning is given again; the fit's other warnings are not)
|
|
92
|
+
warnings: fit.warnings.includes(VCOV_FALLBACK) ? [VCOV_FALLBACK] : [],
|
|
93
|
+
}, fit);
|
|
94
|
+
}
|
package/dist/models/lmer.d.ts
CHANGED
|
@@ -124,6 +124,11 @@ export interface LmerResult {
|
|
|
124
124
|
/** R's warnings (predictors on very different scales). */
|
|
125
125
|
warnings: string[];
|
|
126
126
|
}
|
|
127
|
+
/**
|
|
128
|
+
* The columns of the blocks T_k as lists of θ indices, the diagonal element first: changing the sign of a column
|
|
129
|
+
* leaves the criterion unchanged (Λ_θ → Λ_θ D with D = diag(±1) per level, matched by u → D u)
|
|
130
|
+
*/
|
|
131
|
+
export declare function columnsOfTheta(s: MixedModelStructure): number[][];
|
|
127
132
|
/**
|
|
128
133
|
* The criterion (REML criterion or ML deviance) and its gradient with respect to θ at `theta`. Internal: the fit uses
|
|
129
134
|
* the sparse {@link profiledDeviance}; the regression test injects the dense reference implementation.
|
|
@@ -229,12 +234,23 @@ export interface LmerInternals {
|
|
|
229
234
|
criterion: MixedCriterion;
|
|
230
235
|
/** The estimate θ̂ (a copy, unaffected by changes to the result's `theta`) */
|
|
231
236
|
theta: number[];
|
|
237
|
+
/** The fixed effects β̂ (a copy; prediction) */
|
|
238
|
+
fixef: number[];
|
|
239
|
+
/** The random effects b̂ = Λ_θ̂ û, in the order of the columns of Z (a copy; prediction) */
|
|
240
|
+
b: number[];
|
|
241
|
+
/** The residual standard deviation σ̂ (prediction) */
|
|
242
|
+
sigma: number;
|
|
232
243
|
}
|
|
233
244
|
/**
|
|
234
245
|
* The internals of a fit (see {@link LmerInternals}). Internal. Throws a TypeError for an object that is not a result
|
|
235
246
|
* returned by {@link lmer}.
|
|
236
247
|
*/
|
|
237
248
|
export declare function lmerInternals(fit: LmerResult): LmerInternals;
|
|
249
|
+
/**
|
|
250
|
+
* The exponent of 2 of each column of X whose largest |value| is beyond 2^±500, where the cross-products of X overflow
|
|
251
|
+
* or underflow; 0 for the other columns (internal: lmer's standard errors and lmerTest's quantities)
|
|
252
|
+
*/
|
|
253
|
+
export declare function extremeColumnExponents(x: readonly (readonly number[])[], p: number): number[];
|
|
238
254
|
/**
|
|
239
255
|
* {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
|
|
240
256
|
* test of the sparse computation fits with the dense reference implementation through it.
|