@numero-uno-jpn/rstats 0.14.0 → 0.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 +27 -0
- package/README.ja.md +5 -5
- package/README.md +5 -5
- package/dist/chunks/{chunk-XCAMWVNO.js → chunk-4EOKNOXP.js} +1 -1
- package/dist/chunks/{chunk-7PSGKKOP.js → chunk-4XGKAHD3.js} +2 -2
- package/dist/chunks/{chunk-7CPM3M6Q.js → chunk-7GEYDIQC.js} +2 -2
- package/dist/chunks/{chunk-A76XBA3D.js → chunk-7XHAE2LG.js} +1 -1
- package/dist/chunks/{chunk-ZUESNU7W.js → chunk-A3XZUJCP.js} +2 -2
- package/dist/chunks/{chunk-FBDZ6B2G.js → chunk-AEFWSUZ2.js} +2 -2
- package/dist/chunks/{chunk-IBJ7RI44.js → chunk-CJ5ETQCK.js} +2 -2
- package/dist/chunks/{chunk-IGSR4GIF.js → chunk-CMPDE3SZ.js} +2 -2
- package/dist/chunks/chunk-GZTLODPK.js +3 -0
- package/dist/chunks/{chunk-SZ357HRC.js → chunk-HNLKOICT.js} +1 -1
- package/dist/chunks/{chunk-WM33ADZV.js → chunk-HS7KIFMR.js} +2 -2
- package/dist/chunks/{chunk-6JRESWVF.js → chunk-LU5FHU2O.js} +2 -2
- package/dist/chunks/{chunk-SD7ML5PE.js → chunk-LVXAWWUX.js} +2 -2
- package/dist/chunks/{chunk-NTETWLP3.js → chunk-LWUTCYTZ.js} +1 -1
- package/dist/chunks/{chunk-DCGBYO44.js → chunk-NYGWVZOC.js} +2 -2
- package/dist/chunks/{chunk-7T74KLE5.js → chunk-PRDF6IU6.js} +2 -2
- package/dist/chunks/{chunk-ACE64PMM.js → chunk-QQIWOGHR.js} +2 -2
- package/dist/chunks/{chunk-YTV3RFCA.js → chunk-VAPGDPHM.js} +1 -1
- package/dist/chunks/{chunk-DWNGNTS6.js → chunk-VSKWQMSG.js} +2 -2
- package/dist/chunks/{chunk-RZIWVCHO.js → chunk-WEWXYHPR.js} +2 -2
- package/dist/chunks/{chunk-Q4JF4QHS.js → chunk-XMTYTJT6.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/glm.js +4 -2
- package/dist/models/glmFamily.js +16 -4
- package/dist/models/lmer.d.ts +28 -5
- package/dist/models/lmer.js +129 -20
- package/dist/models/lmerAnova.d.ts +8 -3
- package/dist/models/lmerAnova.js +10 -4
- package/dist/models/lmerHypotheses.d.ts +4 -3
- package/dist/models/lmerHypotheses.js +9 -7
- package/dist/models/lmerTest.d.ts +13 -7
- package/dist/models/lmerTest.js +16 -11
- package/dist/models/mixedStructure.js +30 -14
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +13 -13
- package/dist/special.js +2 -2
- package/dist/tests.js +7 -7
- package/package.json +1 -1
- package/dist/chunks/chunk-YQLEXH2Y.js +0 -3
package/dist/models/lmer.js
CHANGED
|
@@ -39,6 +39,21 @@
|
|
|
39
39
|
// of all the elements has a direction of negative curvature that moves it (then θ is moved a little along it).
|
|
40
40
|
// lme4's own optimiser (and its convergence warnings) are not reproduced: the result is the exact minimiser, which
|
|
41
41
|
// lme4 approaches to its tolerances.
|
|
42
|
+
//
|
|
43
|
+
// The criterion can have several local minima (crossed terms without a fixed intercept, for example, where one term
|
|
44
|
+
// can take the place of the missing intercept). So the local minimum θ* reached from the initial θ is compared with
|
|
45
|
+
// the boundary points of whole terms (oracle/report-0.14.0-behaviour.md, section 1): for each term whose block is not
|
|
46
|
+
// entirely 0 in θ*, the local minimum started at θ* with that term removed (its whole block set to 0) and held at 0.
|
|
47
|
+
// If the lowest of these is lower than θ*'s criterion by more than 1e-8 max(1, |criterion|), the minimisation starts
|
|
48
|
+
// again from it with every element free, and the comparison is repeated; otherwise θ* is the estimate (at most 50
|
|
49
|
+
// restarts). Only whole terms are removed, one at a time.
|
|
50
|
+
//
|
|
51
|
+
// The penalised least-squares problem is linear in y: y − X β₀ for any β₀ gives the same criterion, residuals,
|
|
52
|
+
// random effects and derivatives, and β̂ − β₀. So the fit works with y − X β₀, β₀ the least-squares coefficients of y
|
|
53
|
+
// on X, and adds β₀ back to the fixed effects: with a response of large mean, the rounding error of the fixed effects
|
|
54
|
+
// from the normal equations would otherwise be large next to the residuals, and the criterion noisy. If y − X β₀ is
|
|
55
|
+
// 0 (to 1e-12 max |y|), the criterion is −∞ for every θ and there is no estimate: an error.
|
|
56
|
+
import { qr, qrCoef } from "../linalg/qr.js";
|
|
42
57
|
import { profiledDeviance } from "./mixedDeviance.js";
|
|
43
58
|
import { mixedModelStructure } from "./mixedStructure.js";
|
|
44
59
|
/** Initial trust-region radius, relative to max(1, max |θ|) */
|
|
@@ -62,6 +77,13 @@ const GRADIENT_TOLERANCE = 1e-9;
|
|
|
62
77
|
const MAX_ITERATIONS = 500;
|
|
63
78
|
/** The Hessian is used again after a Newton step whose actual reduction is within this ratio of the predicted one */
|
|
64
79
|
const HESSIAN_REUSE_RATIO = 0.75;
|
|
80
|
+
/** A restart from a boundary point must lower the criterion by more than this times max(1, |criterion|) ... */
|
|
81
|
+
const RESTART_THRESHOLD = 1e-8;
|
|
82
|
+
/** ... and there are at most this many restarts */
|
|
83
|
+
const MAX_RESTARTS = 50;
|
|
84
|
+
/** The response is fitted exactly by the fixed effects when its least-squares residuals are below this × max |y| */
|
|
85
|
+
const EXACT_FIT = 1e-12;
|
|
86
|
+
const EXACT_FIT_ERROR = "lmer: the response is fitted exactly by the fixed effects (a constant response, for example), so the residual variance is 0";
|
|
65
87
|
const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
|
|
66
88
|
/** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
|
|
67
89
|
function symmetricEigen(a0) {
|
|
@@ -185,11 +207,14 @@ const sparseCriterion = (s, theta, reml) => {
|
|
|
185
207
|
const r = profiledDeviance(s, theta, reml, { gradient: true });
|
|
186
208
|
return { f: r.deviance, g: r.gradient };
|
|
187
209
|
};
|
|
188
|
-
/**
|
|
189
|
-
|
|
210
|
+
/**
|
|
211
|
+
* A local minimiser of the criterion over θ, subject to the lower bounds (see the header), started at `start`, with
|
|
212
|
+
* the elements in `held` kept at exactly 0 throughout (never free, never released); with its criterion
|
|
213
|
+
*/
|
|
214
|
+
function localMinimum(s, reml, criterion, start, held = new Set()) {
|
|
190
215
|
const diagonal = s.lower.map((b) => b === 0);
|
|
191
216
|
const evaluate = (theta) => criterion(s, theta, reml);
|
|
192
|
-
let theta =
|
|
217
|
+
let theta = start.map((v, j) => (held.has(j) ? 0 : v));
|
|
193
218
|
let { f, g } = evaluate(theta);
|
|
194
219
|
/** Diagonal elements held at exactly 0 */
|
|
195
220
|
const fixed = new Set();
|
|
@@ -269,7 +294,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
269
294
|
const leaveAlongNegativeCurvature = () => {
|
|
270
295
|
if (fixed.size === 0)
|
|
271
296
|
return false;
|
|
272
|
-
const set = theta.map((_, j) => j);
|
|
297
|
+
const set = theta.map((_, j) => j).filter((j) => !held.has(j));
|
|
273
298
|
const eig = symmetricEigen(hessian(set));
|
|
274
299
|
const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
|
|
275
300
|
const k = eig.values.indexOf(Math.min(...eig.values));
|
|
@@ -289,7 +314,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
289
314
|
return true;
|
|
290
315
|
};
|
|
291
316
|
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
|
|
292
|
-
const free = theta.map((_, j) => j).filter((j) => !fixed.has(j));
|
|
317
|
+
const free = theta.map((_, j) => j).filter((j) => !fixed.has(j) && !held.has(j));
|
|
293
318
|
if (free.length > 0 && !iterate(free))
|
|
294
319
|
continue;
|
|
295
320
|
// converged on the free elements. Diagonal elements that reached 0 (to rounding) are held at exactly 0
|
|
@@ -320,7 +345,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
320
345
|
for (const j of column)
|
|
321
346
|
theta[j] = -theta[j];
|
|
322
347
|
}
|
|
323
|
-
return theta.map((v) => (v === 0 ? 0 : v)); // no -0
|
|
348
|
+
return { theta: theta.map((v) => (v === 0 ? 0 : v)), f }; // no -0
|
|
324
349
|
}
|
|
325
350
|
radius = Math.max(radius, INITIAL_RADIUS * BOUNDARY_CANDIDATE * scaleOf());
|
|
326
351
|
previousNewton = Infinity;
|
|
@@ -328,6 +353,70 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
328
353
|
}
|
|
329
354
|
throw new Error(OPTIMISATION_FAILED);
|
|
330
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* The estimate of θ: the local minimum reached from the initial θ, then compared with the local minima reached from
|
|
358
|
+
* its boundary points with one whole term removed (see the header); a clearly better one is the start of a new local
|
|
359
|
+
* minimisation, until none is.
|
|
360
|
+
*/
|
|
361
|
+
function minimiseCriterion(s, reml, criterion) {
|
|
362
|
+
/** The θ indices of each term's block (its whole lower triangle) */
|
|
363
|
+
const blocks = s.terms.map((t) => {
|
|
364
|
+
const nc = t.columns.length;
|
|
365
|
+
return Array.from({ length: (nc * (nc + 1)) / 2 }, (_, i) => t.thetaOffset + i);
|
|
366
|
+
});
|
|
367
|
+
let best = localMinimum(s, reml, criterion, s.theta);
|
|
368
|
+
for (let round = 0; round < MAX_RESTARTS; round++) {
|
|
369
|
+
let candidate;
|
|
370
|
+
for (const block of blocks) {
|
|
371
|
+
if (block.every((j) => best.theta[j] === 0))
|
|
372
|
+
continue;
|
|
373
|
+
const removed = localMinimum(s, reml, criterion, best.theta, new Set(block));
|
|
374
|
+
if (candidate === undefined || removed.f < candidate.f)
|
|
375
|
+
candidate = removed;
|
|
376
|
+
}
|
|
377
|
+
if (candidate === undefined || !(candidate.f < best.f - RESTART_THRESHOLD * Math.max(1, Math.abs(best.f))))
|
|
378
|
+
return best.theta;
|
|
379
|
+
best = localMinimum(s, reml, criterion, candidate.theta);
|
|
380
|
+
}
|
|
381
|
+
throw new Error(OPTIMISATION_FAILED);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* The option checks of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section 3):
|
|
385
|
+
* `options` must be an object when given (not null, not an array); its own keys, in order, may be neither among those
|
|
386
|
+
* of R that are not supported (the first gives an Error) nor unknown (a TypeError listing all of them). A key whose
|
|
387
|
+
* value is `undefined` counts as given. Returns the options as an object (`{}` when not given).
|
|
388
|
+
*/
|
|
389
|
+
export function checkOptions(fn, options, accepted, unsupported) {
|
|
390
|
+
if (options === undefined)
|
|
391
|
+
return {};
|
|
392
|
+
if (typeof options !== "object" || options === null || Array.isArray(options))
|
|
393
|
+
throw new TypeError("options must be an object");
|
|
394
|
+
const keys = Object.keys(options);
|
|
395
|
+
const notSupported = keys.find((k) => unsupported.includes(k));
|
|
396
|
+
if (notSupported !== undefined)
|
|
397
|
+
throw new Error(`${fn}: argument '${notSupported}' is not supported`);
|
|
398
|
+
const unknown = keys.filter((k) => !accepted.includes(k));
|
|
399
|
+
if (unknown.length > 0)
|
|
400
|
+
throw new TypeError(`unused argument${unknown.length === 1 ? "" : "s"} (${unknown.join(", ")})`);
|
|
401
|
+
return options;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* A logical option as R's conditions take it (internal): `undefined` gives the default, a boolean itself, a number
|
|
405
|
+
* other than NaN `false` for 0 and `true` otherwise; `null` and anything else are TypeErrors.
|
|
406
|
+
*/
|
|
407
|
+
export function logicalOption(value, defaultValue) {
|
|
408
|
+
if (value === undefined)
|
|
409
|
+
return defaultValue;
|
|
410
|
+
if (typeof value === "boolean")
|
|
411
|
+
return value;
|
|
412
|
+
if (typeof value === "number" && !Number.isNaN(value))
|
|
413
|
+
return value !== 0;
|
|
414
|
+
if (value === null)
|
|
415
|
+
throw new TypeError("argument is of length zero");
|
|
416
|
+
throw new TypeError("argument is not interpretable as logical");
|
|
417
|
+
}
|
|
418
|
+
const LMER_KEYS = ["REML", "contrasts", "levels"];
|
|
419
|
+
const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action", "control", "start", "verbose", "devFunOnly"];
|
|
331
420
|
/**
|
|
332
421
|
* Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
|
|
333
422
|
* quantities of its methods: `fixef()`, `coef(summary())` (without p-values), `vcov()`, `sigma()`, `VarCorr()`,
|
|
@@ -345,7 +434,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
345
434
|
*
|
|
346
435
|
* @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
|
|
347
436
|
* @param data The data frame: an object of columns.
|
|
348
|
-
* @param options `REML`, and `contrasts` and `levels` as in {@link lm}.
|
|
437
|
+
* @param options `REML`, and `contrasts` and `levels` as in {@link lm} (see {@link LmerOptions} for the keys accepted).
|
|
349
438
|
*
|
|
350
439
|
* @example
|
|
351
440
|
* ```ts
|
|
@@ -364,7 +453,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
364
453
|
*
|
|
365
454
|
* @category Mixed models
|
|
366
455
|
*/
|
|
367
|
-
export function lmer(formula, data, options
|
|
456
|
+
export function lmer(formula, data, options) {
|
|
368
457
|
return lmerWithCriterion(formula, data, options, sparseCriterion);
|
|
369
458
|
}
|
|
370
459
|
/**
|
|
@@ -387,17 +476,28 @@ export function lmerInternals(fit) {
|
|
|
387
476
|
* test of the sparse computation fits with the dense reference implementation through it.
|
|
388
477
|
*/
|
|
389
478
|
export function lmerWithCriterion(formula, data, options, criterion) {
|
|
390
|
-
const
|
|
479
|
+
const given = checkOptions("lmer", options, LMER_KEYS, LMER_UNSUPPORTED);
|
|
480
|
+
const reml = logicalOption(given.REML, true);
|
|
481
|
+
options = { ...given, REML: reml };
|
|
391
482
|
const modelOptions = {};
|
|
392
483
|
if (options.contrasts !== undefined)
|
|
393
484
|
modelOptions.contrasts = options.contrasts;
|
|
394
485
|
if (options.levels !== undefined)
|
|
395
486
|
modelOptions.levels = options.levels;
|
|
396
|
-
const
|
|
487
|
+
const original = mixedModelStructure(formula, data, modelOptions);
|
|
488
|
+
const n = original.y.length;
|
|
489
|
+
const p = original.xColNames.length;
|
|
490
|
+
// β₀, the least-squares coefficients of y on X, and the residuals y − X β₀ (see the header)
|
|
491
|
+
const beta0 = p === 0 ? [] : qrCoef(qr(original.x), original.y);
|
|
492
|
+
const yc = original.y.map((y, i) => y - original.x[i].reduce((sum, v, k) => sum + v * beta0[k], 0));
|
|
493
|
+
// a response in the column space of X: the criterion is −∞ for every θ (no estimate)
|
|
494
|
+
const maxAbs = (v) => v.reduce((m, x) => Math.max(m, Math.abs(x)), 0);
|
|
495
|
+
if (maxAbs(yc) <= EXACT_FIT * maxAbs(original.y))
|
|
496
|
+
throw new Error(EXACT_FIT_ERROR);
|
|
497
|
+
const s = { ...original, y: yc };
|
|
397
498
|
const theta = minimiseCriterion(s, reml, criterion);
|
|
398
499
|
const r = profiledDeviance(s, theta, reml, { rxInverse: true });
|
|
399
|
-
const
|
|
400
|
-
const p = s.xColNames.length;
|
|
500
|
+
const fixef = r.beta.map((b, k) => b + beta0[k]);
|
|
401
501
|
const twoPi = 2 * Math.PI;
|
|
402
502
|
const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n));
|
|
403
503
|
const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)));
|
|
@@ -405,7 +505,8 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
405
505
|
const sigma = Math.sqrt(sigma2);
|
|
406
506
|
const vcov = r.rxInverse.map((row) => row.map((v) => sigma2 * v));
|
|
407
507
|
const stdError = vcov.map((row, i) => Math.sqrt(row[i]));
|
|
408
|
-
|
|
508
|
+
// (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
|
|
509
|
+
const tValue = fixef.map((b, i) => b / stdError[i]);
|
|
409
510
|
// the blocks T_k and the variance components
|
|
410
511
|
const varCorr = s.terms.map((term) => {
|
|
411
512
|
const nc = term.columns.length;
|
|
@@ -416,6 +517,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
416
517
|
t[i][j] = theta[k++];
|
|
417
518
|
const cov = t.map((ti) => t.map((tj) => sigma2 * ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
|
|
418
519
|
const sd = cov.map((row, i) => Math.sqrt(row[i]));
|
|
520
|
+
// (a column with variance 0 has the correlations 0/0 = NaN with the others, as lme4's VarCorr: not a bug)
|
|
419
521
|
const corr = cov.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sd[i] * sd[j]))));
|
|
420
522
|
return { group: s.groups[term.group].name, columns: [...term.columns], sd, corr };
|
|
421
523
|
});
|
|
@@ -431,15 +533,22 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
431
533
|
})),
|
|
432
534
|
};
|
|
433
535
|
});
|
|
434
|
-
|
|
536
|
+
// the residuals from y − X β₀ (the more accurate), the fitted values with the whole fixed effects
|
|
537
|
+
const fitted = s.x.map((xi) => xi.reduce((sum, v, k) => sum + v * fixef[k], 0));
|
|
538
|
+
const residuals = s.x.map((xi, i) => yc[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
|
|
435
539
|
s.z.forEach((col, j) => {
|
|
436
540
|
const bj = r.b[j];
|
|
437
|
-
if (bj !== 0)
|
|
438
|
-
col.rows.forEach((i, k) =>
|
|
541
|
+
if (bj !== 0) {
|
|
542
|
+
col.rows.forEach((i, k) => {
|
|
543
|
+
fitted[i] += col.values[k] * bj;
|
|
544
|
+
residuals[i] -= col.values[k] * bj;
|
|
545
|
+
});
|
|
546
|
+
}
|
|
439
547
|
});
|
|
440
|
-
const residuals = s.y.map((y, i) => y - fitted[i]);
|
|
441
548
|
const logLik = -(reml ? REMLcrit : deviance) / 2;
|
|
442
549
|
const df = p + theta.length + 1;
|
|
550
|
+
// (an absolute threshold on θ's diagonal elements, as lme4's isSingular with its default tolerance 1e-4; it is not
|
|
551
|
+
// meant to match the minimiser's relative boundary test)
|
|
443
552
|
const singular = theta.some((v, j) => s.lower[j] === 0 && v < 1e-4);
|
|
444
553
|
const messages = [...s.messages];
|
|
445
554
|
if (singular)
|
|
@@ -451,8 +560,8 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
451
560
|
rows: [...s.rows],
|
|
452
561
|
theta,
|
|
453
562
|
fixefNames: [...s.xColNames],
|
|
454
|
-
fixef
|
|
455
|
-
coefTable: { estimate: [...
|
|
563
|
+
fixef,
|
|
564
|
+
coefTable: { estimate: [...fixef], stdError, tValue },
|
|
456
565
|
vcov,
|
|
457
566
|
sigma,
|
|
458
567
|
varCorr,
|
|
@@ -469,6 +578,6 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
469
578
|
messages,
|
|
470
579
|
warnings: [...s.warnings],
|
|
471
580
|
};
|
|
472
|
-
internalsByFit.set(result, { structure: s, data, options
|
|
581
|
+
internalsByFit.set(result, { structure: s, beta0, data, options, reml, criterion, theta: [...theta] });
|
|
473
582
|
return result;
|
|
474
583
|
}
|
|
@@ -3,7 +3,8 @@ import { type LmerResult } from "./lmer.js";
|
|
|
3
3
|
import { type HypothesisType, type LmerHypotheses } from "./lmerHypotheses.js";
|
|
4
4
|
import { type LmerFRow, type LmerSatterthwaite } from "./lmerTest.js";
|
|
5
5
|
/**
|
|
6
|
-
* Options of {@link lmerAnova} for one fit.
|
|
6
|
+
* Options of {@link lmerAnova} for one fit. R's `ddf` gives the Error `lmerAnova: argument 'ddf' is not supported`,
|
|
7
|
+
* any other key the TypeError `unused argument (<key>)`.
|
|
7
8
|
*
|
|
8
9
|
* @category Mixed models
|
|
9
10
|
*/
|
|
@@ -39,12 +40,16 @@ export interface LmerAnovaTable {
|
|
|
39
40
|
warnings: string[];
|
|
40
41
|
}
|
|
41
42
|
/**
|
|
42
|
-
* Options of {@link lmerAnova} for several fits.
|
|
43
|
+
* Options of {@link lmerAnova} for several fits. R's `modelNames` and `model.names` give the Error
|
|
44
|
+
* `lmerAnova: argument '<key>' is not supported`, any other key the TypeError `unused argument (<key>)`.
|
|
43
45
|
*
|
|
44
46
|
* @category Mixed models
|
|
45
47
|
*/
|
|
46
48
|
export interface LmerCompareOptions {
|
|
47
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* Refit the REML fits by maximum likelihood before comparing them (default `true`). As in R's conditions, a number
|
|
51
|
+
* is `false` for 0 and `true` otherwise; `null` and other values are TypeErrors.
|
|
52
|
+
*/
|
|
48
53
|
refit?: boolean;
|
|
49
54
|
/** The names of the models, in the order given (default `"MODEL1"`, `"MODEL2"`, ...). */
|
|
50
55
|
names?: readonly string[];
|
package/dist/models/lmerAnova.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// fits by maximum likelihood with lmer's own minimiser (the exact ML optimum).
|
|
8
8
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
9
9
|
import { Warnings } from "./glmFamily.js";
|
|
10
|
-
import { lmerInternals, lmerWithCriterion } from "./lmer.js";
|
|
10
|
+
import { checkOptions, lmerInternals, lmerWithCriterion, logicalOption } from "./lmer.js";
|
|
11
11
|
import { fixedEffectsDescription, lmerHypotheses } from "./lmerHypotheses.js";
|
|
12
12
|
import { fTestOf, lmerSatterthwaite } from "./lmerTest.js";
|
|
13
13
|
const TYPES = { I: "I", II: "II", III: "III", 1: "I", 2: "II", 3: "III" };
|
|
@@ -74,6 +74,7 @@ function compareFits(fits, options) {
|
|
|
74
74
|
if (fits.length < 2)
|
|
75
75
|
throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
|
|
76
76
|
const internals = fits.map(lmerInternals);
|
|
77
|
+
// (only the number of observations is compared, as lme4 does; the fits must also share the data object below)
|
|
77
78
|
if (fits.some((f) => f.nObs !== fits[0].nObs))
|
|
78
79
|
throw new Error("models were not all fitted to the same size of dataset");
|
|
79
80
|
if (internals.some((i) => i.data !== internals[0].data))
|
|
@@ -90,7 +91,7 @@ function compareFits(fits, options) {
|
|
|
90
91
|
else
|
|
91
92
|
warnings.add("failed to find model names, assigning generic names");
|
|
92
93
|
}
|
|
93
|
-
const refit = options.refit
|
|
94
|
+
const refit = logicalOption(options.refit, true);
|
|
94
95
|
let logLik;
|
|
95
96
|
if (refit) {
|
|
96
97
|
if (fits.some((f) => f.REML))
|
|
@@ -129,6 +130,11 @@ function compareFits(fits, options) {
|
|
|
129
130
|
warnings: warnings.list,
|
|
130
131
|
};
|
|
131
132
|
}
|
|
132
|
-
export function lmerAnova(fit, options
|
|
133
|
-
|
|
133
|
+
export function lmerAnova(fit, options) {
|
|
134
|
+
if (Array.isArray(fit)) {
|
|
135
|
+
const checked = checkOptions("lmerAnova", options, ["refit", "names"], ["modelNames", "model.names"]);
|
|
136
|
+
// (the logical value is checked with the options, before the fits)
|
|
137
|
+
return compareFits(fit, { ...checked, refit: logicalOption(checked.refit, true) });
|
|
138
|
+
}
|
|
139
|
+
return anovaOfFit(fit, checkOptions("lmerAnova", options, ["type"], ["ddf"]));
|
|
134
140
|
}
|
|
@@ -60,9 +60,10 @@ export interface LmerHypotheses {
|
|
|
60
60
|
messages: string[];
|
|
61
61
|
}
|
|
62
62
|
/**
|
|
63
|
-
* The fixed-effects design of an lmer fit, from lmer's inputs: the formula
|
|
64
|
-
* the
|
|
65
|
-
*
|
|
63
|
+
* The fixed-effects design of an lmer fit, from lmer's inputs: the formula without its random-effects terms (whose
|
|
64
|
+
* order of the variables names the terms and the interaction columns) coded on the model frame of the whole formula
|
|
65
|
+
* (rows with a missing value in any of its variables dropped, unused levels dropped), the contrasts given, and the
|
|
66
|
+
* aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
|
|
66
67
|
*/
|
|
67
68
|
export declare function fixedEffectsDescription(formula: string, data: DataFrame, options?: FixedEffectsDescriptionOptions): FixedEffectsDescription;
|
|
68
69
|
/**
|
|
@@ -21,9 +21,10 @@ import { parseFormula, splitBarTerms, termsOf } from "./formula.js";
|
|
|
21
21
|
import { design } from "./modelMatrix.js";
|
|
22
22
|
const ONE = { type: "num", value: 1, text: "1" };
|
|
23
23
|
/**
|
|
24
|
-
* The fixed-effects design of an lmer fit, from lmer's inputs: the formula
|
|
25
|
-
* the
|
|
26
|
-
*
|
|
24
|
+
* The fixed-effects design of an lmer fit, from lmer's inputs: the formula without its random-effects terms (whose
|
|
25
|
+
* order of the variables names the terms and the interaction columns) coded on the model frame of the whole formula
|
|
26
|
+
* (rows with a missing value in any of its variables dropped, unused levels dropped), the contrasts given, and the
|
|
27
|
+
* aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
|
|
27
28
|
*/
|
|
28
29
|
export function fixedEffectsDescription(formula, data, options = {}) {
|
|
29
30
|
const parsed = parseFormula(formula, false, true);
|
|
@@ -33,10 +34,11 @@ export function fixedEffectsDescription(formula, data, options = {}) {
|
|
|
33
34
|
throw new TypeError("data must be an object of columns");
|
|
34
35
|
const { fixed } = splitBarTerms(parsed.rhs);
|
|
35
36
|
const fixedRhs = fixed ?? ONE;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const
|
|
37
|
+
// as lmer (src/models/mixedStructure.ts): the formula without the random-effects terms, on the model frame of the
|
|
38
|
+
// whole formula
|
|
39
|
+
const extraVariables = termsOf(parsed, Object.keys(data), fixedRhs).variables;
|
|
40
|
+
const contrastOptions = options.contrasts === undefined ? {} : { contrasts: options.contrasts };
|
|
41
|
+
const d = design({ response: parsed.response, rhs: fixedRhs }, data, { ...(options.levels === undefined ? {} : { levels: options.levels }), dropUnusedLevels: true, ...contrastOptions, extraVariables }, fixedRhs);
|
|
40
42
|
const { terms, frame } = d;
|
|
41
43
|
let keep = d.colNames.map((_, j) => j);
|
|
42
44
|
if (keep.length > 0) {
|
|
@@ -25,10 +25,11 @@ export declare function hessianWarnings(values: readonly number[]): string[];
|
|
|
25
25
|
*/
|
|
26
26
|
export declare function lmerSatterthwaite(fit: LmerResult): LmerSatterthwaite;
|
|
27
27
|
/**
|
|
28
|
-
* The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there)
|
|
29
|
-
*
|
|
28
|
+
* The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there), `beta0` added to the
|
|
29
|
+
* fixed effects (those of a fit's structure, whose response is y − X β₀). Internal: the test evaluates them at lme4's
|
|
30
|
+
* optimum too, to compare with lmerTest's numerical derivatives at the same point.
|
|
30
31
|
*/
|
|
31
|
-
export declare function satterthwaiteAt(structure: MixedModelStructure, theta: readonly number[], reml: boolean): LmerSatterthwaite;
|
|
32
|
+
export declare function satterthwaiteAt(structure: MixedModelStructure, theta: readonly number[], reml: boolean, beta0?: readonly number[]): LmerSatterthwaite;
|
|
32
33
|
/** The one-dimensional test of a contrast l (internal) */
|
|
33
34
|
export interface TRow {
|
|
34
35
|
estimate: number;
|
|
@@ -57,7 +58,8 @@ export declare function lmerFTest(fit: LmerResult, L: readonly (readonly number[
|
|
|
57
58
|
/** {@link lmerFTest} with the Satterthwaite quantities given (internal) */
|
|
58
59
|
export declare function fTestOf(s: LmerSatterthwaite, L: readonly (readonly number[])[], rhs: readonly number[] | undefined, warnings: Warnings): LmerFRow | undefined;
|
|
59
60
|
/**
|
|
60
|
-
* Options of {@link lmerSummary}.
|
|
61
|
+
* Options of {@link lmerSummary}. Any other key is the TypeError `unused argument (<key>)` (R's lmerTest ignores
|
|
62
|
+
* unknown arguments with a warning).
|
|
61
63
|
*
|
|
62
64
|
* @category Mixed models
|
|
63
65
|
*/
|
|
@@ -124,16 +126,20 @@ export interface LmerSummary {
|
|
|
124
126
|
*/
|
|
125
127
|
export declare function lmerSummary(fit: LmerResult, options?: LmerSummaryOptions): LmerSummary;
|
|
126
128
|
/**
|
|
127
|
-
* Options of {@link lmerContest}.
|
|
129
|
+
* Options of {@link lmerContest}. R's `collect`, `checkEstimability`, `check_estimability` and `ddf` give the Error
|
|
130
|
+
* `lmerContest: argument '<key>' is not supported`, any other key the TypeError `unused argument (<key>)`.
|
|
128
131
|
*
|
|
129
132
|
* @category Mixed models
|
|
130
133
|
*/
|
|
131
134
|
export interface LmerContestOptions {
|
|
132
135
|
/** The right-hand side of the hypothesis L β = rhs: one value, or one per row of L (default 0). */
|
|
133
136
|
rhs?: number | readonly number[];
|
|
134
|
-
/**
|
|
137
|
+
/**
|
|
138
|
+
* Test the rows jointly with one F-test (default `true`), or each row with its own t-test (`false`). As in R's
|
|
139
|
+
* conditions, a number is `false` for 0 and `true` otherwise; `null` and other values are TypeErrors.
|
|
140
|
+
*/
|
|
135
141
|
joint?: boolean;
|
|
136
|
-
/** With `joint: false`, whether to add the confidence intervals (default `true`). */
|
|
142
|
+
/** With `joint: false`, whether to add the confidence intervals (default `true`; a logical value as `joint`). */
|
|
137
143
|
confint?: boolean;
|
|
138
144
|
/** The confidence level of the intervals (default 0.95). */
|
|
139
145
|
level?: number;
|
package/dist/models/lmerTest.js
CHANGED
|
@@ -17,7 +17,7 @@ import { pt1, qt1 } from "../distributions/t.js";
|
|
|
17
17
|
import { eigen } from "../linalg/eigen.js";
|
|
18
18
|
import { ginv } from "../linalg/kappa.js";
|
|
19
19
|
import { Warnings } from "./glmFamily.js";
|
|
20
|
-
import { lmerInternals } from "./lmer.js";
|
|
20
|
+
import { checkOptions, lmerInternals, logicalOption } from "./lmer.js";
|
|
21
21
|
import { varparDerivatives } from "./mixedDerivatives.js";
|
|
22
22
|
/** Eigenvalues of the Hessian within this of 0 (or below) are left out of its inverse and warned about */
|
|
23
23
|
const HESSIAN_TOLERANCE = 1e-8;
|
|
@@ -57,15 +57,16 @@ export function lmerSatterthwaite(fit) {
|
|
|
57
57
|
if (cached !== undefined)
|
|
58
58
|
return cached;
|
|
59
59
|
const internals = lmerInternals(fit);
|
|
60
|
-
const result = satterthwaiteAt(internals.structure, internals.theta, internals.reml);
|
|
60
|
+
const result = satterthwaiteAt(internals.structure, internals.theta, internals.reml, internals.beta0);
|
|
61
61
|
satterthwaiteByFit.set(fit, result);
|
|
62
62
|
return result;
|
|
63
63
|
}
|
|
64
64
|
/**
|
|
65
|
-
* The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there)
|
|
66
|
-
*
|
|
65
|
+
* The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there), `beta0` added to the
|
|
66
|
+
* fixed effects (those of a fit's structure, whose response is y − X β₀). Internal: the test evaluates them at lme4's
|
|
67
|
+
* optimum too, to compare with lmerTest's numerical derivatives at the same point.
|
|
67
68
|
*/
|
|
68
|
-
export function satterthwaiteAt(structure, theta, reml) {
|
|
69
|
+
export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
|
|
69
70
|
const d = varparDerivatives(structure, theta, reml);
|
|
70
71
|
const m = d.varpar.length;
|
|
71
72
|
const e = eigen(d.hessian, { symmetric: true });
|
|
@@ -86,7 +87,7 @@ export function satterthwaiteAt(structure, theta, reml) {
|
|
|
86
87
|
hessian: d.hessian,
|
|
87
88
|
hessianEigenvalues: values,
|
|
88
89
|
vcovVarpar,
|
|
89
|
-
beta: d.beta,
|
|
90
|
+
beta: d.beta.map((b, k) => b + (beta0[k] ?? 0)),
|
|
90
91
|
sigma: d.varpar[m - 1],
|
|
91
92
|
vcov: d.vcov,
|
|
92
93
|
jacobian: d.jacobian,
|
|
@@ -131,6 +132,7 @@ function jointDenDF(nu) {
|
|
|
131
132
|
return nu.reduce((a, b) => a + b, 0) / nu.length;
|
|
132
133
|
if (nu.some((v) => v <= 2))
|
|
133
134
|
return 2;
|
|
135
|
+
// (as lmerTest: with every ν > 2 each term ν/(ν − 2) exceeds 1, so e > nu.length and the result is positive)
|
|
134
136
|
const e = nu.reduce((sum, v) => sum + v / (v - 2), 0);
|
|
135
137
|
return (2 * e) / (e - nu.length);
|
|
136
138
|
}
|
|
@@ -216,8 +218,8 @@ export function fTestOf(s, L, rhs, warnings) {
|
|
|
216
218
|
*
|
|
217
219
|
* @category Mixed models
|
|
218
220
|
*/
|
|
219
|
-
export function lmerSummary(fit, options
|
|
220
|
-
const ddf = options.ddf ?? "Satterthwaite";
|
|
221
|
+
export function lmerSummary(fit, options) {
|
|
222
|
+
const ddf = checkOptions("lmerSummary", options, ["ddf"], []).ddf ?? "Satterthwaite";
|
|
221
223
|
if (ddf !== "Satterthwaite" && ddf !== "lme4")
|
|
222
224
|
throw new RangeError(`ddf must be "Satterthwaite" or "lme4", not ${JSON.stringify(ddf)}`);
|
|
223
225
|
const internals = lmerInternals(fit);
|
|
@@ -241,6 +243,8 @@ export function lmerSummary(fit, options = {}) {
|
|
|
241
243
|
warnings: [...s.warnings],
|
|
242
244
|
};
|
|
243
245
|
}
|
|
246
|
+
const CONTEST_KEYS = ["rhs", "joint", "confint", "level"];
|
|
247
|
+
const CONTEST_UNSUPPORTED = ["collect", "checkEstimability", "check_estimability", "ddf"];
|
|
244
248
|
/** The rows of a contrast argument: a vector is one row; each row must have one value per fixed effect */
|
|
245
249
|
function contrastRows(L, p) {
|
|
246
250
|
if (!Array.isArray(L))
|
|
@@ -254,12 +258,13 @@ function contrastRows(L, p) {
|
|
|
254
258
|
}
|
|
255
259
|
return rows;
|
|
256
260
|
}
|
|
257
|
-
export function lmerContest(fit, L, options
|
|
261
|
+
export function lmerContest(fit, L, options) {
|
|
262
|
+
options = checkOptions("lmerContest", options, CONTEST_KEYS, CONTEST_UNSUPPORTED);
|
|
263
|
+
const joint = logicalOption(options.joint, true);
|
|
264
|
+
const confint = logicalOption(options.confint, true);
|
|
258
265
|
const internals = lmerInternals(fit);
|
|
259
266
|
const p = internals.structure.xColNames.length;
|
|
260
267
|
const rows = contrastRows(L, p);
|
|
261
|
-
const joint = options.joint ?? true;
|
|
262
|
-
const confint = options.confint ?? true;
|
|
263
268
|
const level = options.level ?? 0.95;
|
|
264
269
|
if (typeof level !== "number" || !(level >= 0 && level <= 1))
|
|
265
270
|
throw new RangeError("level must be a number between 0 and 1");
|
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
//
|
|
5
5
|
// Written for rStats.js (no ported code) from oracle/lmer-behaviour.md (stage 1a) and the notation of D. Bates,
|
|
6
6
|
// M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models Using lme4", Journal of Statistical
|
|
7
|
-
// Software 67(1). The fixed-effects part is
|
|
8
|
-
//
|
|
7
|
+
// Software 67(1). The fixed-effects part is the formula without the random-effects terms, coded as lm codes it
|
|
8
|
+
// (src/models/modelMatrix.ts; the order of its own variables names the interaction columns: `y ~ (z | g) + x * z` has
|
|
9
|
+
// `x:z`), on the model frame of the whole formula; each random-effects term's left-hand side is a model matrix with
|
|
10
|
+
// treatment contrasts (a term without columns is an error); its grouping expression is expanded as a right-hand side
|
|
9
11
|
// into grouping factors (`a/b` gives `b:a` and `a`); `||` splits a term into one term per column group. The terms are
|
|
10
12
|
// then ordered by their number of levels (decreasing, when not already non-increasing; ties reversed). Z is
|
|
11
13
|
// level-major within each term, and Λ_θ is block diagonal with one lower-triangular block per level of each term,
|
|
@@ -92,19 +94,21 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
92
94
|
const { fixed, bars } = splitBarTerms(parsed.rhs);
|
|
93
95
|
if (typeof data !== "object" || data === null)
|
|
94
96
|
throw new TypeError("data must be an object of columns");
|
|
95
|
-
// the fixed-effects part
|
|
96
|
-
//
|
|
97
|
+
// the fixed-effects part: the formula without the random-effects terms, `response ~ fixed part`, as lm codes it (the
|
|
98
|
+
// order of its variables names the interaction columns); its model frame has the variables of the whole formula too,
|
|
99
|
+
// so that every model matrix below uses the same rows
|
|
97
100
|
const frameOptions = {
|
|
98
101
|
...(options.levels === undefined ? {} : { levels: options.levels }),
|
|
99
102
|
dropUnusedLevels: true,
|
|
100
103
|
};
|
|
101
104
|
// (if nothing is left of the right-hand side, the fixed part is `1`)
|
|
102
105
|
const fixedRhs = fixed ?? { type: "num", value: 1, text: "1" };
|
|
106
|
+
const fixedFormula = { response: parsed.response, rhs: fixedRhs };
|
|
107
|
+
// the variables of the whole formula (in the model frame, those of the fixed part come first, in its order)
|
|
108
|
+
const allVariables = termsOf(parsed, Object.keys(data), fixedRhs).variables;
|
|
103
109
|
// (a contrast is for a variable of the fixed-effects part: a grouping variable alone counts as absent)
|
|
104
|
-
const contrastOptions = options.contrasts === undefined
|
|
105
|
-
|
|
106
|
-
: { contrasts: options.contrasts, contrastVariables: termsOf({ response: parsed.response, rhs: fixedRhs }, Object.keys(data)).variables };
|
|
107
|
-
const fixedDesign = design(parsed, data, { ...frameOptions, ...contrastOptions }, fixedRhs);
|
|
110
|
+
const contrastOptions = options.contrasts === undefined ? {} : { contrasts: options.contrasts };
|
|
111
|
+
const fixedDesign = design(fixedFormula, data, { ...frameOptions, ...contrastOptions, extraVariables: allVariables }, fixedRhs);
|
|
108
112
|
const { frame } = fixedDesign;
|
|
109
113
|
const n = frame.rows.length;
|
|
110
114
|
if (n === 0)
|
|
@@ -112,24 +116,28 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
112
116
|
// (the model frame's errors, above, come before this check)
|
|
113
117
|
if (bars.length === 0)
|
|
114
118
|
throw new Error("No random effects terms specified in formula");
|
|
115
|
-
const variables = fixedDesign.terms.variables;
|
|
119
|
+
const variables = [...fixedDesign.terms.variables, ...allVariables.filter((v) => !fixedDesign.terms.variables.includes(v))];
|
|
116
120
|
// (lhs || group) split into one term per term of lhs, then each term expanded by its grouping factors
|
|
117
121
|
const expanded = [];
|
|
118
|
-
|
|
122
|
+
/** The first bar term (in the formula's order) without columns */
|
|
123
|
+
let noColumns;
|
|
124
|
+
bars.forEach((bar, barIndex) => {
|
|
119
125
|
let lhsList = [bar.lhs];
|
|
120
126
|
if (bar.double) {
|
|
121
127
|
const lhsTerms = termsOf(parsed, Object.keys(data), bar.lhs);
|
|
122
128
|
lhsList = lhsTerms.intercept ? [{ type: "num", value: 1, text: "1" }] : [];
|
|
123
129
|
for (const t of lhsTerms.terms) {
|
|
124
|
-
const term = t.map((v) => ({ type: "var", name: variables[v] })).reduce((l, r) => ({ type: "binary", op: ":", left: l, right: r }));
|
|
130
|
+
const term = t.map((v) => ({ type: "var", name: lhsTerms.variables[v] })).reduce((l, r) => ({ type: "binary", op: ":", left: l, right: r }));
|
|
125
131
|
lhsList.push({ type: "binary", op: "+", left: { type: "num", value: 0, text: "0" }, right: term });
|
|
126
132
|
}
|
|
133
|
+
if (lhsList.length === 0)
|
|
134
|
+
noColumns ??= barIndex;
|
|
127
135
|
}
|
|
128
136
|
const factors = groupingFactorsOf(bar.group);
|
|
129
137
|
for (const lhs of lhsList)
|
|
130
138
|
for (const groupVariables of factors)
|
|
131
|
-
expanded.push({ lhs, groupVariables });
|
|
132
|
-
}
|
|
139
|
+
expanded.push({ lhs, groupVariables, bar: barIndex });
|
|
140
|
+
});
|
|
133
141
|
// the grouping factors (levels present, ordered by the levels of the first variable, then the second, ...)
|
|
134
142
|
const factorCache = new Map();
|
|
135
143
|
const factorOf = (vs) => {
|
|
@@ -187,6 +195,8 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
187
195
|
// the left-hand side: treatment contrasts whatever the options say
|
|
188
196
|
const lhsDesign = design(parsed, data, frameOptions, t.lhs);
|
|
189
197
|
const nc = lhsDesign.colNames.length;
|
|
198
|
+
if (nc === 0 && (noColumns === undefined || t.bar < noColumns))
|
|
199
|
+
noColumns = t.bar;
|
|
190
200
|
const nLevels = t.factor.levels.length;
|
|
191
201
|
terms.push({
|
|
192
202
|
label: `${deparseFormula(t.lhs)} | ${t.name}`,
|
|
@@ -200,7 +210,11 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
200
210
|
zOffset += nLevels * nc;
|
|
201
211
|
thetaOffset += (nc * (nc + 1)) / 2;
|
|
202
212
|
}
|
|
203
|
-
// checks
|
|
213
|
+
// checks: a term without columns (its bar term as written), then the grouping factors and the numbers of effects
|
|
214
|
+
if (noColumns !== undefined) {
|
|
215
|
+
const bar = bars[noColumns];
|
|
216
|
+
throw new Error(`lmer: the random-effects term '${deparseFormula(bar.lhs)} ${bar.double ? "||" : "|"} ${deparseFormula(bar.group)}' has no columns`);
|
|
217
|
+
}
|
|
204
218
|
if (groups.some((g) => g.levels.length < 2))
|
|
205
219
|
throw new RangeError("grouping factors must have > 1 sampled level");
|
|
206
220
|
const tooMany = groups.filter((g) => g.levels.length >= n).map((g) => g.name);
|
|
@@ -286,6 +300,8 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
286
300
|
sds.push(sd);
|
|
287
301
|
}
|
|
288
302
|
const limit = Math.log(1000);
|
|
303
|
+
// (a constant column other than 0/1 has sd 0, so log(0) = -Infinity and the warning is given: lme4's check includes
|
|
304
|
+
// such columns too, so this is intended)
|
|
289
305
|
const badScale = sds.some((a, i) => Math.abs(Math.log(a)) > limit || sds.some((b, k) => k !== i && Math.abs(Math.log(a / b)) > limit));
|
|
290
306
|
if (badScale) {
|
|
291
307
|
warnings.push("Some predictor variables are on very different scales: consider rescaling. \nYou may also use (g)lmerControl(autoscale = TRUE) to improve numerical stability.");
|