@numero-uno-jpn/rstats 0.11.0 → 0.12.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 +57 -0
- package/README.ja.md +44 -13
- package/README.md +43 -11
- package/dist/chunks/{chunk-VJ4BDBMU.js → chunk-3VMBBQLV.js} +2 -2
- package/dist/chunks/chunk-4OKAZJJG.js +3 -0
- package/dist/chunks/{chunk-EZAFN5CD.js → chunk-6BH65HGN.js} +1 -1
- package/dist/chunks/chunk-ATC4F4BX.js +2 -0
- package/dist/chunks/{chunk-JWBO5WVN.js → chunk-EDH53DXN.js} +2 -2
- package/dist/chunks/{chunk-Y5CNQ266.js → chunk-EZ2KD5NA.js} +2 -2
- package/dist/chunks/{chunk-Y5PYRAYP.js → chunk-GSPOO2G3.js} +2 -2
- package/dist/chunks/{chunk-F5EDJFEO.js → chunk-K7AZ65H7.js} +2 -2
- package/dist/chunks/{chunk-YSWGDOWK.js → chunk-LEIH4U5X.js} +2 -2
- package/dist/chunks/{chunk-EZWBRCJL.js → chunk-OX3SBG5X.js} +1 -1
- package/dist/chunks/chunk-SGZQDJRR.js +2 -0
- package/dist/chunks/{chunk-C5XTWMGB.js → chunk-UH2N3ZQW.js} +1 -1
- package/dist/chunks/chunk-UV2MZYDQ.js +2 -0
- package/dist/chunks/{chunk-TOGXTCZO.js → chunk-VQHEOBTM.js} +2 -2
- package/dist/chunks/chunk-WJQZZYOI.js +2 -0
- package/dist/chunks/chunk-WKEFHOFR.js +2 -0
- package/dist/chunks/{chunk-CGBNKHNZ.js → chunk-WXC25OPJ.js} +2 -2
- package/dist/chunks/{chunk-5WDJPHYY.js → chunk-XJQKSR52.js} +1 -1
- package/dist/data/grouping.d.ts +39 -15
- package/dist/data/grouping.js +21 -22
- package/dist/descriptive/basic.d.ts +130 -17
- package/dist/descriptive/basic.js +115 -14
- package/dist/descriptive/cov.d.ts +22 -12
- package/dist/descriptive/dataFrames.d.ts +39 -11
- package/dist/descriptive/dataFrames.js +14 -6
- package/dist/descriptive/factanal.d.ts +26 -6
- package/dist/descriptive/factanal.js +7 -3
- package/dist/descriptive/hist.d.ts +27 -6
- package/dist/descriptive/hist.js +9 -3
- package/dist/descriptive/missing.d.ts +13 -6
- package/dist/descriptive/missing.js +4 -2
- package/dist/descriptive/moments.d.ts +91 -13
- package/dist/descriptive/moments.js +66 -9
- package/dist/descriptive/omega.d.ts +28 -6
- package/dist/descriptive/omega.js +16 -4
- package/dist/descriptive/pivot.d.ts +22 -6
- package/dist/descriptive/pivot.js +7 -3
- package/dist/descriptive/quantile.d.ts +33 -5
- package/dist/descriptive/quantile.js +20 -2
- package/dist/descriptive/rank.d.ts +12 -2
- package/dist/descriptive/rank.js +2 -0
- package/dist/descriptive/table.d.ts +55 -7
- package/dist/descriptive/table.js +38 -4
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.d.ts +40 -5
- package/dist/distributions/arcsine.js +35 -4
- package/dist/distributions/beta.d.ts +12 -0
- package/dist/distributions/beta.js +12 -0
- package/dist/distributions/binomial.d.ts +18 -0
- package/dist/distributions/binomial.js +18 -0
- package/dist/distributions/bvnorm.d.ts +4 -1
- package/dist/distributions/bvnorm.js +4 -1
- package/dist/distributions/cauchy.d.ts +24 -0
- package/dist/distributions/cauchy.js +24 -0
- package/dist/distributions/chisq.d.ts +18 -0
- package/dist/distributions/chisq.js +18 -0
- package/dist/distributions/exponential.d.ts +29 -1
- package/dist/distributions/exponential.js +24 -0
- package/dist/distributions/f.d.ts +18 -0
- package/dist/distributions/f.js +18 -0
- package/dist/distributions/gamma.d.ts +20 -0
- package/dist/distributions/gamma.js +18 -0
- package/dist/distributions/geometric.d.ts +24 -0
- package/dist/distributions/geometric.js +24 -0
- package/dist/distributions/hypergeometric.d.ts +24 -0
- package/dist/distributions/hypergeometric.js +24 -0
- package/dist/distributions/invgamma.d.ts +32 -4
- package/dist/distributions/invgamma.js +27 -3
- package/dist/distributions/kumaraswamy.d.ts +31 -3
- package/dist/distributions/kumaraswamy.js +31 -3
- package/dist/distributions/laplace.d.ts +36 -4
- package/dist/distributions/laplace.js +31 -3
- package/dist/distributions/logistic.d.ts +29 -1
- package/dist/distributions/logistic.js +24 -0
- package/dist/distributions/lognormal.d.ts +29 -1
- package/dist/distributions/lognormal.js +24 -0
- package/dist/distributions/multinomial.d.ts +7 -1
- package/dist/distributions/multinomial.js +2 -0
- package/dist/distributions/negbinomial.d.ts +29 -1
- package/dist/distributions/negbinomial.js +24 -0
- package/dist/distributions/normal.d.ts +11 -1
- package/dist/distributions/normal.js +6 -0
- package/dist/distributions/pareto.d.ts +36 -4
- package/dist/distributions/pareto.js +31 -3
- package/dist/distributions/poisson.d.ts +18 -0
- package/dist/distributions/poisson.js +18 -0
- package/dist/distributions/signrank.d.ts +24 -0
- package/dist/distributions/signrank.js +24 -0
- package/dist/distributions/summary.d.ts +20 -2
- package/dist/distributions/summary.js +4 -0
- package/dist/distributions/t.d.ts +18 -0
- package/dist/distributions/t.js +18 -0
- package/dist/distributions/triangular.d.ts +36 -4
- package/dist/distributions/triangular.js +31 -3
- package/dist/distributions/tukey.d.ts +15 -1
- package/dist/distributions/tukey.js +10 -0
- package/dist/distributions/uniform.d.ts +29 -1
- package/dist/distributions/uniform.js +24 -0
- package/dist/distributions/weibull.d.ts +29 -1
- package/dist/distributions/weibull.js +24 -0
- package/dist/distributions/wilcox.d.ts +24 -0
- package/dist/distributions/wilcox.js +24 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +1 -1
- package/dist/entries/mixed.d.ts +1 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/numerics.d.ts +1 -1
- package/dist/entries/tests.js +1 -1
- package/dist/htest/agreement.d.ts +61 -23
- package/dist/htest/agreement.js +19 -9
- package/dist/htest/ansariTest.d.ts +8 -2
- package/dist/htest/aov.d.ts +43 -10
- package/dist/htest/aov.js +17 -3
- package/dist/htest/binomTest.d.ts +12 -2
- package/dist/htest/binomTest.js +2 -0
- package/dist/htest/brunnerMunzelTest.d.ts +9 -3
- package/dist/htest/brunnerMunzelTest.js +4 -2
- package/dist/htest/chisqTest.d.ts +19 -3
- package/dist/htest/cor.d.ts +20 -4
- package/dist/htest/effectSize.d.ts +70 -12
- package/dist/htest/effectSize.js +40 -7
- package/dist/htest/fisherTest.d.ts +9 -1
- package/dist/htest/fisherTest.js +2 -0
- package/dist/htest/groups.d.ts +5 -1
- package/dist/htest/ksTest.d.ts +20 -3
- package/dist/htest/leveneTest.d.ts +15 -4
- package/dist/htest/leveneTest.js +5 -2
- package/dist/htest/mantelhaenTest.d.ts +25 -3
- package/dist/htest/mantelhaenTest.js +15 -1
- package/dist/htest/mcnemarTest.d.ts +14 -4
- package/dist/htest/mcnemarTest.js +4 -2
- package/dist/htest/multipleComparisons.d.ts +173 -29
- package/dist/htest/multipleComparisons.js +123 -19
- package/dist/htest/normalityTests.d.ts +56 -9
- package/dist/htest/normalityTests.js +40 -6
- package/dist/htest/onewayTest.d.ts +32 -3
- package/dist/htest/onewayTest.js +10 -0
- package/dist/htest/pAdjust.d.ts +9 -1
- package/dist/htest/pAdjust.js +2 -0
- package/dist/htest/pairwise.d.ts +50 -5
- package/dist/htest/pairwise.js +25 -0
- package/dist/htest/poissonTest.d.ts +12 -2
- package/dist/htest/poissonTest.js +2 -0
- package/dist/htest/polycor.d.ts +29 -10
- package/dist/htest/power.d.ts +60 -6
- package/dist/htest/power.js +6 -0
- package/dist/htest/propTest.d.ts +13 -2
- package/dist/htest/propTest.js +2 -0
- package/dist/htest/pwr.d.ts +286 -36
- package/dist/htest/pwr.js +116 -15
- package/dist/htest/rankTests.d.ts +80 -12
- package/dist/htest/rankTests.js +11 -2
- package/dist/htest/tTest.d.ts +13 -3
- package/dist/htest/testFormula.js +6 -3
- package/dist/htest/trendTests.d.ts +29 -8
- package/dist/htest/trendTests.js +8 -4
- package/dist/htest/types.d.ts +14 -2
- package/dist/htest/varTest.d.ts +25 -8
- package/dist/htest/wilcoxTest.d.ts +10 -2
- package/dist/internal/dpq.d.ts +4 -0
- package/dist/internal/noncentral.d.ts +2 -0
- package/dist/internal/vectorize.d.ts +4 -0
- package/dist/linalg/basic.d.ts +39 -5
- package/dist/linalg/basic.js +15 -0
- package/dist/linalg/chol.d.ts +26 -5
- package/dist/linalg/chol.js +7 -0
- package/dist/linalg/eigen.d.ts +16 -7
- package/dist/linalg/eigen.js +6 -5
- package/dist/linalg/expm.d.ts +15 -5
- package/dist/linalg/expm.js +5 -3
- package/dist/linalg/kappa.d.ts +21 -1
- package/dist/linalg/kappa.js +16 -0
- package/dist/linalg/lu.d.ts +30 -6
- package/dist/linalg/lu.js +15 -3
- package/dist/linalg/matrix.d.ts +4 -0
- package/dist/linalg/norm.d.ts +16 -1
- package/dist/linalg/norm.js +9 -0
- package/dist/linalg/ops.d.ts +156 -35
- package/dist/linalg/ops.js +96 -15
- package/dist/linalg/qr.d.ts +87 -12
- package/dist/linalg/qr.js +31 -0
- package/dist/linalg/schur.d.ts +8 -2
- package/dist/linalg/schur.js +3 -1
- package/dist/linalg/solve.d.ts +42 -6
- package/dist/linalg/solve.js +22 -0
- package/dist/linalg/svd.d.ts +12 -2
- package/dist/linalg/svd.js +2 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +3 -0
- package/dist/models/anovaSequential.d.ts +26 -4
- package/dist/models/anovaSequential.js +3 -1
- package/dist/models/aovEz.d.ts +29 -6
- package/dist/models/aovEz.js +5 -2
- package/dist/models/aovStrata.d.ts +13 -3
- package/dist/models/aovStrata.js +5 -1
- package/dist/models/carAnova.d.ts +9 -3
- package/dist/models/carAnova.js +4 -2
- package/dist/models/coxph.d.ts +33 -7
- package/dist/models/coxph.js +8 -3
- package/dist/models/formula.d.ts +26 -1
- package/dist/models/formula.js +125 -9
- package/dist/models/glm.d.ts +128 -21
- package/dist/models/glm.js +71 -14
- package/dist/models/glmAnova.d.ts +30 -5
- package/dist/models/glmAnova.js +15 -2
- package/dist/models/glmConfint.d.ts +16 -2
- package/dist/models/glmConfint.js +9 -1
- package/dist/models/glmFamily.d.ts +27 -5
- package/dist/models/lm.d.ts +77 -19
- package/dist/models/lm.js +22 -4
- package/dist/models/lmer.d.ts +162 -0
- package/dist/models/lmer.js +457 -0
- package/dist/models/mauchly.d.ts +20 -5
- package/dist/models/mauchly.js +7 -3
- package/dist/models/mixedDeviance.d.ts +44 -0
- package/dist/models/mixedDeviance.js +872 -0
- package/dist/models/mixedStructure.d.ts +82 -0
- package/dist/models/mixedStructure.js +309 -0
- package/dist/models/modelFrame.d.ts +17 -2
- package/dist/models/modelFrame.js +36 -21
- package/dist/models/modelMatrix.d.ts +33 -8
- package/dist/models/modelMatrix.js +21 -5
- package/dist/models/survival.d.ts +41 -9
- package/dist/models/survival.js +10 -4
- package/dist/numerics/deriv.d.ts +21 -6
- package/dist/numerics/deriv.js +16 -5
- package/dist/numerics/integrate.d.ts +37 -7
- package/dist/numerics/integrate.js +8 -2
- package/dist/numerics/interp.d.ts +63 -12
- package/dist/numerics/interp.js +30 -6
- package/dist/numerics/ode.d.ts +15 -5
- package/dist/numerics/ode.js +5 -3
- package/dist/numerics.js +2 -2
- package/dist/optim/optim.d.ts +32 -8
- package/dist/optim/optim.js +8 -4
- package/dist/random/beta.d.ts +8 -0
- package/dist/random/beta.js +8 -0
- package/dist/random/binomial.d.ts +16 -0
- package/dist/random/binomial.js +16 -0
- package/dist/random/continuous.d.ts +51 -0
- package/dist/random/continuous.js +51 -0
- package/dist/random/extra.d.ts +66 -6
- package/dist/random/extra.js +66 -6
- package/dist/random/gamma.d.ts +33 -0
- package/dist/random/gamma.js +33 -0
- package/dist/random/hyper.d.ts +8 -0
- package/dist/random/hyper.js +8 -0
- package/dist/random/poisson.d.ts +25 -0
- package/dist/random/poisson.js +25 -0
- package/dist/random/r2dtable.d.ts +2 -0
- package/dist/random/r2dtable.js +2 -0
- package/dist/random/rank.d.ts +16 -0
- package/dist/random/rank.js +16 -0
- package/dist/random/rng.d.ts +49 -6
- package/dist/random/rng.js +29 -2
- package/dist/random/sample.d.ts +10 -2
- package/dist/random/sample.js +5 -1
- package/dist/random/streams.d.ts +13 -0
- package/dist/random/streams.js +13 -0
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +11 -3
- package/dist/special/besselIK.js +6 -2
- package/dist/special/besselJY.d.ts +6 -2
- package/dist/special/besselJY.js +6 -2
- package/dist/special/beta.d.ts +16 -2
- package/dist/special/beta.js +16 -2
- package/dist/special/choose.d.ts +13 -5
- package/dist/special/choose.js +13 -5
- package/dist/special/erf.d.ts +8 -3
- package/dist/special/erf.js +8 -3
- package/dist/special/extra.d.ts +30 -10
- package/dist/special/extra.js +25 -9
- package/dist/special/gamma.d.ts +18 -2
- package/dist/special/gamma.js +18 -2
- package/dist/special/log1p.d.ts +16 -7
- package/dist/special/log1p.js +16 -7
- package/dist/special/psigamma.d.ts +9 -3
- package/dist/special/psigamma.js +9 -3
- package/dist/special/rCompatible.d.ts +5 -1
- package/dist/special.js +2 -2
- package/dist/tests.js +12 -12
- package/llms.txt +13 -3
- package/package.json +5 -1
- package/dist/chunks/chunk-7GQMKH3Z.js +0 -2
- package/dist/chunks/chunk-AHHS6AC4.js +0 -3
- package/dist/chunks/chunk-ALM3VHFP.js +0 -2
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type DataFrame } from "./modelFrame.js";
|
|
2
|
+
import { type ModelMatrixOptions } from "./modelMatrix.js";
|
|
3
|
+
/** A random-effects term of a mixed model, after the expansion of its grouping expression and of `||`. */
|
|
4
|
+
export interface RandomEffectsTerm {
|
|
5
|
+
/** The term as R deparses it, such as `"1 | g"`, `"0 + x | b:a"`. */
|
|
6
|
+
label: string;
|
|
7
|
+
/** Index of the term's grouping factor in `groups`. */
|
|
8
|
+
group: number;
|
|
9
|
+
/** Names of the columns of the term's left-hand side model matrix, such as `"(Intercept)"`, `"x"`, `"flo"`. */
|
|
10
|
+
columns: string[];
|
|
11
|
+
/** The left-hand side model matrix (array of rows, the rows kept). */
|
|
12
|
+
matrix: number[][];
|
|
13
|
+
/** Number of levels of the grouping factor. */
|
|
14
|
+
nLevels: number;
|
|
15
|
+
/** First column of the term in Z (0-based). */
|
|
16
|
+
zOffset: number;
|
|
17
|
+
/** First parameter of the term in θ (0-based). */
|
|
18
|
+
thetaOffset: number;
|
|
19
|
+
}
|
|
20
|
+
/** A grouping factor of a mixed model. */
|
|
21
|
+
export interface GroupingFactor {
|
|
22
|
+
/** Its name: the variables joined by `:`, such as `"g"`, `"b:a"`. */
|
|
23
|
+
name: string;
|
|
24
|
+
/** The levels present in the rows kept, in level order. */
|
|
25
|
+
levels: string[];
|
|
26
|
+
/** The level index (0-based) of each row kept. */
|
|
27
|
+
codes: number[];
|
|
28
|
+
}
|
|
29
|
+
/** A sparse column: the rows (0-based, increasing) of its nonzero entries and their values. */
|
|
30
|
+
export interface SparseColumn {
|
|
31
|
+
rows: number[];
|
|
32
|
+
values: number[];
|
|
33
|
+
}
|
|
34
|
+
/** An entry of Λ_θ (0-based row and column), which holds θ[theta]. */
|
|
35
|
+
export interface CovarianceFactorEntry {
|
|
36
|
+
row: number;
|
|
37
|
+
col: number;
|
|
38
|
+
theta: number;
|
|
39
|
+
}
|
|
40
|
+
/** The structure of a linear mixed model (nothing fitted). */
|
|
41
|
+
export interface MixedModelStructure {
|
|
42
|
+
/** 0-based indices of the rows of the data kept (rows with a missing value in a variable of the formula dropped). */
|
|
43
|
+
rows: number[];
|
|
44
|
+
/** The response (rows kept). */
|
|
45
|
+
y: number[];
|
|
46
|
+
/** Names of the columns of X (aliased columns dropped). */
|
|
47
|
+
xColNames: string[];
|
|
48
|
+
/** The fixed-effects model matrix X (array of rows). */
|
|
49
|
+
x: number[][];
|
|
50
|
+
/** The random-effects terms, in their final order. */
|
|
51
|
+
terms: RandomEffectsTerm[];
|
|
52
|
+
/** The distinct grouping factors, in order of first use by the terms. */
|
|
53
|
+
groups: GroupingFactor[];
|
|
54
|
+
/** Number of columns of Z. */
|
|
55
|
+
q: number;
|
|
56
|
+
/** Z (n × q) by columns, nonzero entries only. */
|
|
57
|
+
z: SparseColumn[];
|
|
58
|
+
/** The label of the level of each column of Z. */
|
|
59
|
+
zColLevels: string[];
|
|
60
|
+
/** The initial θ: 1 for the diagonal elements of the blocks, 0 for the others. */
|
|
61
|
+
theta: number[];
|
|
62
|
+
/** Lower bounds of θ: 0 for the diagonal elements, -Infinity for the others. */
|
|
63
|
+
lower: number[];
|
|
64
|
+
/** The entries of Λ_θ (lower triangular, q × q), by column then row. */
|
|
65
|
+
lambda: CovarianceFactorEntry[];
|
|
66
|
+
/** R's messages (rank deficiency of X). */
|
|
67
|
+
messages: string[];
|
|
68
|
+
/** R's warnings (predictors on very different scales). */
|
|
69
|
+
warnings: string[];
|
|
70
|
+
}
|
|
71
|
+
/** Options of {@link mixedModelStructure}: those of the fixed-effects model matrix. */
|
|
72
|
+
export type MixedModelStructureOptions = ModelMatrixOptions;
|
|
73
|
+
/**
|
|
74
|
+
* The structure of a linear mixed model `response ~ fixed part + (lhs | group) + ...`: the model frame, X, Z, the
|
|
75
|
+
* layout of Λ_θ, the initial θ and its lower bounds, with lme4's checks, errors, messages and warnings
|
|
76
|
+
* (oracle/lmer-behaviour.md, stage 1a). Internal: not exported from the package.
|
|
77
|
+
*
|
|
78
|
+
* @param formula A formula such as `"y ~ x + (x | g)"`, `"y ~ (1 | a/b)"` or `"y ~ (x || g)"`.
|
|
79
|
+
* @param data The data frame: an object of columns.
|
|
80
|
+
* @param options The contrasts (fixed-effects part only) and the level order of factors.
|
|
81
|
+
*/
|
|
82
|
+
export declare function mixedModelStructure(formula: string, data: DataFrame, options?: MixedModelStructureOptions): MixedModelStructure;
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// The structure of a linear mixed model (lme4's lmer): the formula with its random-effects terms `(lhs | group)` and
|
|
2
|
+
// `(lhs || group)`, the model frame, the fixed-effects model matrix X, the random-effects model matrix Z, the layout
|
|
3
|
+
// of the relative covariance factor Λ_θ, the initial θ and its lower bounds. Nothing is fitted here.
|
|
4
|
+
//
|
|
5
|
+
// Written for rStats.js (no ported code) from oracle/lmer-behaviour.md (stage 1a) and the notation of D. Bates,
|
|
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 coded as in lm (src/models/modelMatrix.ts); each random-effects term's
|
|
8
|
+
// left-hand side is a model matrix with treatment contrasts; its grouping expression is expanded as a right-hand side
|
|
9
|
+
// into grouping factors (`a/b` gives `b:a` and `a`); `||` splits a term into one term per column group. The terms are
|
|
10
|
+
// then ordered by their number of levels (decreasing, when not already non-increasing; ties reversed). Z is
|
|
11
|
+
// level-major within each term, and Λ_θ is block diagonal with one lower-triangular block per level of each term,
|
|
12
|
+
// whose parameters are its lower triangle in column-major order. Aliased columns of X (pivoted QR of lm, tolerance
|
|
13
|
+
// 1e-7) are dropped with a message; predictors on very different scales give a warning.
|
|
14
|
+
import { formatR } from "../htest/core/simulate.js";
|
|
15
|
+
import { qr } from "../linalg/qr.js";
|
|
16
|
+
import { deparseFormula, expandRhs, parseFormula, splitBarTerms, termsOf } from "./formula.js";
|
|
17
|
+
import { presentLevels } from "./modelFrame.js";
|
|
18
|
+
import { design } from "./modelMatrix.js";
|
|
19
|
+
/** The grouping factors of a grouping expression: the variables of each, in the order of the name */
|
|
20
|
+
function groupingFactorsOf(group) {
|
|
21
|
+
const vars = [];
|
|
22
|
+
const collect = (n) => {
|
|
23
|
+
if (n.type === "var") {
|
|
24
|
+
if (!vars.includes(n.name))
|
|
25
|
+
vars.push(n.name);
|
|
26
|
+
}
|
|
27
|
+
else if (n.type === "binary") {
|
|
28
|
+
collect(n.left);
|
|
29
|
+
if (n.op !== "^")
|
|
30
|
+
collect(n.right);
|
|
31
|
+
}
|
|
32
|
+
else if (n.type === "unary" || n.type === "paren" || n.type === "Error")
|
|
33
|
+
collect(n.arg);
|
|
34
|
+
};
|
|
35
|
+
collect(group);
|
|
36
|
+
const { terms } = expandRhs(group, (name) => vars.indexOf(name), []);
|
|
37
|
+
if (terms.length === 0)
|
|
38
|
+
throw new SyntaxError(`invalid formula: no grouping factor in '${deparseFormula(group)}'`);
|
|
39
|
+
// sorted by degree (stably); the variables of a term in order of first appearance in the expression
|
|
40
|
+
let factors = terms
|
|
41
|
+
.map((t, i) => [t, i])
|
|
42
|
+
.sort((a, b) => a[0].length - b[0].length || a[1] - b[1])
|
|
43
|
+
.map(([t]) => t.map((v) => vars[v]));
|
|
44
|
+
let nested = false;
|
|
45
|
+
const findSlash = (n) => {
|
|
46
|
+
if (n.type === "binary") {
|
|
47
|
+
if (n.op === "/")
|
|
48
|
+
nested = true;
|
|
49
|
+
findSlash(n.left);
|
|
50
|
+
findSlash(n.right);
|
|
51
|
+
}
|
|
52
|
+
else if (n.type === "unary" || n.type === "paren" || n.type === "Error")
|
|
53
|
+
findSlash(n.arg);
|
|
54
|
+
};
|
|
55
|
+
findSlash(group);
|
|
56
|
+
if (nested)
|
|
57
|
+
factors = factors.map((f) => [...f].reverse()).reverse();
|
|
58
|
+
return factors;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A variable of the model frame as a grouping factor of the values present: numbers become levels sorted numerically,
|
|
62
|
+
* labelled as R's as.character; a boolean (whose frame variable keeps both levels) has only the values present
|
|
63
|
+
*/
|
|
64
|
+
function asFactor(v) {
|
|
65
|
+
if (v.kind === "factor")
|
|
66
|
+
return presentLevels(v);
|
|
67
|
+
const distinct = [...new Set(v.values)].sort((a, b) => a - b);
|
|
68
|
+
const levels = [];
|
|
69
|
+
const index = new Map();
|
|
70
|
+
for (const d of distinct) {
|
|
71
|
+
const label = formatR(d);
|
|
72
|
+
if (!index.has(label)) {
|
|
73
|
+
index.set(label, levels.length);
|
|
74
|
+
levels.push(label);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { levels, codes: v.values.map((x) => index.get(formatR(x))) };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The structure of a linear mixed model `response ~ fixed part + (lhs | group) + ...`: the model frame, X, Z, the
|
|
81
|
+
* layout of Λ_θ, the initial θ and its lower bounds, with lme4's checks, errors, messages and warnings
|
|
82
|
+
* (oracle/lmer-behaviour.md, stage 1a). Internal: not exported from the package.
|
|
83
|
+
*
|
|
84
|
+
* @param formula A formula such as `"y ~ x + (x | g)"`, `"y ~ (1 | a/b)"` or `"y ~ (x || g)"`.
|
|
85
|
+
* @param data The data frame: an object of columns.
|
|
86
|
+
* @param options The contrasts (fixed-effects part only) and the level order of factors.
|
|
87
|
+
*/
|
|
88
|
+
export function mixedModelStructure(formula, data, options = {}) {
|
|
89
|
+
const parsed = parseFormula(formula, false, true);
|
|
90
|
+
if (parsed.response === undefined)
|
|
91
|
+
throw new TypeError("the formula has no response");
|
|
92
|
+
const { fixed, bars } = splitBarTerms(parsed.rhs);
|
|
93
|
+
if (typeof data !== "object" || data === null)
|
|
94
|
+
throw new TypeError("data must be an object of columns");
|
|
95
|
+
// the fixed-effects part (its terms collect the variables of the whole formula, so that every model matrix below
|
|
96
|
+
// uses the same rows)
|
|
97
|
+
const frameOptions = {
|
|
98
|
+
...(options.levels === undefined ? {} : { levels: options.levels }),
|
|
99
|
+
dropUnusedLevels: true,
|
|
100
|
+
};
|
|
101
|
+
// (if nothing is left of the right-hand side, the fixed part is `1`)
|
|
102
|
+
const fixedRhs = fixed ?? { type: "num", value: 1, text: "1" };
|
|
103
|
+
// (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);
|
|
108
|
+
const { frame } = fixedDesign;
|
|
109
|
+
const n = frame.rows.length;
|
|
110
|
+
if (n === 0)
|
|
111
|
+
throw new RangeError("0 (non-NA) cases");
|
|
112
|
+
// (the model frame's errors, above, come before this check)
|
|
113
|
+
if (bars.length === 0)
|
|
114
|
+
throw new Error("No random effects terms specified in formula");
|
|
115
|
+
const variables = fixedDesign.terms.variables;
|
|
116
|
+
// (lhs || group) split into one term per term of lhs, then each term expanded by its grouping factors
|
|
117
|
+
const expanded = [];
|
|
118
|
+
for (const bar of bars) {
|
|
119
|
+
let lhsList = [bar.lhs];
|
|
120
|
+
if (bar.double) {
|
|
121
|
+
const lhsTerms = termsOf(parsed, Object.keys(data), bar.lhs);
|
|
122
|
+
lhsList = lhsTerms.intercept ? [{ type: "num", value: 1, text: "1" }] : [];
|
|
123
|
+
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 }));
|
|
125
|
+
lhsList.push({ type: "binary", op: "+", left: { type: "num", value: 0, text: "0" }, right: term });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const factors = groupingFactorsOf(bar.group);
|
|
129
|
+
for (const lhs of lhsList)
|
|
130
|
+
for (const groupVariables of factors)
|
|
131
|
+
expanded.push({ lhs, groupVariables });
|
|
132
|
+
}
|
|
133
|
+
// the grouping factors (levels present, ordered by the levels of the first variable, then the second, ...)
|
|
134
|
+
const factorCache = new Map();
|
|
135
|
+
const factorOf = (vs) => {
|
|
136
|
+
const name = vs.join(":");
|
|
137
|
+
const cached = factorCache.get(name);
|
|
138
|
+
if (cached !== undefined)
|
|
139
|
+
return cached;
|
|
140
|
+
const parts = vs.map((v) => asFactor(frame.variables[variables.indexOf(v)]));
|
|
141
|
+
let result;
|
|
142
|
+
if (parts.length === 1)
|
|
143
|
+
result = parts[0];
|
|
144
|
+
else {
|
|
145
|
+
const keys = new Map();
|
|
146
|
+
for (let i = 0; i < n; i++) {
|
|
147
|
+
const tuple = parts.map((p) => p.codes[i]);
|
|
148
|
+
keys.set(tuple.join(","), tuple);
|
|
149
|
+
}
|
|
150
|
+
const combos = [...keys.values()].sort((a, b) => {
|
|
151
|
+
for (let k = 0; k < a.length; k++)
|
|
152
|
+
if (a[k] !== b[k])
|
|
153
|
+
return a[k] - b[k];
|
|
154
|
+
return 0;
|
|
155
|
+
});
|
|
156
|
+
const index = new Map(combos.map((t, i) => [t.join(","), i]));
|
|
157
|
+
result = {
|
|
158
|
+
levels: combos.map((t) => t.map((c, k) => parts[k].levels[c]).join(":")),
|
|
159
|
+
codes: Array.from({ length: n }, (_, i) => index.get(parts.map((p) => p.codes[i]).join(","))),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
factorCache.set(name, result);
|
|
163
|
+
return result;
|
|
164
|
+
};
|
|
165
|
+
const withFactors = expanded.map((t) => ({ ...t, name: t.groupVariables.join(":"), factor: factorOf(t.groupVariables) }));
|
|
166
|
+
// order of the terms: kept if the numbers of levels never increase; otherwise sorted ascending (ties in order) and
|
|
167
|
+
// reversed
|
|
168
|
+
let ordered = withFactors;
|
|
169
|
+
if (withFactors.some((t, k) => k > 0 && t.factor.levels.length > withFactors[k - 1].factor.levels.length)) {
|
|
170
|
+
ordered = withFactors
|
|
171
|
+
.map((t, i) => [t, i])
|
|
172
|
+
.sort((a, b) => a[0].factor.levels.length - b[0].factor.levels.length || a[1] - b[1])
|
|
173
|
+
.map(([t]) => t)
|
|
174
|
+
.reverse();
|
|
175
|
+
}
|
|
176
|
+
// the distinct grouping factors in order of first use
|
|
177
|
+
const groups = [];
|
|
178
|
+
const terms = [];
|
|
179
|
+
let zOffset = 0;
|
|
180
|
+
let thetaOffset = 0;
|
|
181
|
+
for (const t of ordered) {
|
|
182
|
+
let g = groups.findIndex((x) => x.name === t.name);
|
|
183
|
+
if (g < 0) {
|
|
184
|
+
g = groups.length;
|
|
185
|
+
groups.push({ name: t.name, levels: t.factor.levels, codes: t.factor.codes });
|
|
186
|
+
}
|
|
187
|
+
// the left-hand side: treatment contrasts whatever the options say
|
|
188
|
+
const lhsDesign = design(parsed, data, frameOptions, t.lhs);
|
|
189
|
+
const nc = lhsDesign.colNames.length;
|
|
190
|
+
const nLevels = t.factor.levels.length;
|
|
191
|
+
terms.push({
|
|
192
|
+
label: `${deparseFormula(t.lhs)} | ${t.name}`,
|
|
193
|
+
group: g,
|
|
194
|
+
columns: lhsDesign.colNames,
|
|
195
|
+
matrix: lhsDesign.x,
|
|
196
|
+
nLevels,
|
|
197
|
+
zOffset,
|
|
198
|
+
thetaOffset,
|
|
199
|
+
});
|
|
200
|
+
zOffset += nLevels * nc;
|
|
201
|
+
thetaOffset += (nc * (nc + 1)) / 2;
|
|
202
|
+
}
|
|
203
|
+
// checks
|
|
204
|
+
if (groups.some((g) => g.levels.length < 2))
|
|
205
|
+
throw new RangeError("grouping factors must have > 1 sampled level");
|
|
206
|
+
const tooMany = groups.filter((g) => g.levels.length >= n).map((g) => g.name);
|
|
207
|
+
if (tooMany.length > 0) {
|
|
208
|
+
throw new RangeError(`number of levels of each grouping factor must be < number of observations (problems: ${tooMany.join(", ")})`);
|
|
209
|
+
}
|
|
210
|
+
for (const t of terms) {
|
|
211
|
+
const effects = t.nLevels * t.columns.length;
|
|
212
|
+
if (n <= effects) {
|
|
213
|
+
throw new RangeError(`number of observations (=${n}) <= number of random effects (=${effects}) for term (${t.label}); ` +
|
|
214
|
+
"the random-effects parameters and the residual variance (or scale parameter) are probably unidentifiable");
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
// Z (level-major within each term), and Λ_θ, θ and its bounds
|
|
218
|
+
const z = [];
|
|
219
|
+
const zColLevels = [];
|
|
220
|
+
const theta = [];
|
|
221
|
+
const lower = [];
|
|
222
|
+
const lambda = [];
|
|
223
|
+
for (const t of terms) {
|
|
224
|
+
const { levels, codes } = groups[t.group];
|
|
225
|
+
const nc = t.columns.length;
|
|
226
|
+
// the rows are visited once, in order, each appended to the columns of its level
|
|
227
|
+
const columns = Array.from({ length: levels.length * nc }, () => ({ rows: [], values: [] }));
|
|
228
|
+
for (let i = 0; i < n; i++) {
|
|
229
|
+
const row = t.matrix[i];
|
|
230
|
+
const base = codes[i] * nc;
|
|
231
|
+
for (let j = 0; j < nc; j++) {
|
|
232
|
+
const v = row[j];
|
|
233
|
+
if (v === 0)
|
|
234
|
+
continue;
|
|
235
|
+
const col = columns[base + j];
|
|
236
|
+
col.rows.push(i);
|
|
237
|
+
col.values.push(v);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
for (let l = 0; l < levels.length; l++) {
|
|
241
|
+
for (let j = 0; j < nc; j++) {
|
|
242
|
+
z.push(columns[l * nc + j]);
|
|
243
|
+
zColLevels.push(levels[l]);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// the lower triangle of the term's block in column-major order: its index in θ
|
|
247
|
+
const triangle = Array.from({ length: nc }, () => new Array(nc).fill(-1));
|
|
248
|
+
let k = t.thetaOffset;
|
|
249
|
+
for (let j = 0; j < nc; j++) {
|
|
250
|
+
for (let i = j; i < nc; i++) {
|
|
251
|
+
triangle[i][j] = k++;
|
|
252
|
+
theta.push(i === j ? 1 : 0);
|
|
253
|
+
lower.push(i === j ? 0 : -Infinity);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
for (let l = 0; l < t.nLevels; l++) {
|
|
257
|
+
const base = t.zOffset + l * nc;
|
|
258
|
+
for (let j = 0; j < nc; j++)
|
|
259
|
+
for (let i = j; i < nc; i++)
|
|
260
|
+
lambda.push({ row: base + i, col: base + j, theta: triangle[i][j] });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// aliased columns of X dropped
|
|
264
|
+
const messages = [];
|
|
265
|
+
let x = fixedDesign.x;
|
|
266
|
+
let xColNames = fixedDesign.colNames;
|
|
267
|
+
if (xColNames.length > 0) {
|
|
268
|
+
const decomposition = qr(x);
|
|
269
|
+
const aliased = new Set(decomposition.pivot.slice(decomposition.rank));
|
|
270
|
+
if (aliased.size > 0) {
|
|
271
|
+
const keep = xColNames.map((_, j) => j).filter((j) => !aliased.has(j));
|
|
272
|
+
x = x.map((row) => keep.map((j) => row[j]));
|
|
273
|
+
xColNames = keep.map((j) => xColNames[j]);
|
|
274
|
+
messages.push(`fixed-effect model matrix is rank deficient so dropping ${aliased.size} ${aliased.size === 1 ? "column / coefficient" : "columns / coefficients"}`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
// predictors on very different scales: the standard deviations of the columns that are not all 0 or 1
|
|
278
|
+
const warnings = [...fixedDesign.warnings];
|
|
279
|
+
const sds = [];
|
|
280
|
+
for (let j = 0; j < xColNames.length; j++) {
|
|
281
|
+
const col = x.map((row) => row[j]);
|
|
282
|
+
if (col.every((v) => v === 0 || v === 1))
|
|
283
|
+
continue;
|
|
284
|
+
const mean = col.reduce((s, v) => s + v, 0) / n;
|
|
285
|
+
const sd = Math.sqrt(col.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1));
|
|
286
|
+
sds.push(sd);
|
|
287
|
+
}
|
|
288
|
+
const limit = Math.log(1000);
|
|
289
|
+
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
|
+
if (badScale) {
|
|
291
|
+
warnings.push("Some predictor variables are on very different scales: consider rescaling. \nYou may also use (g)lmerControl(autoscale = TRUE) to improve numerical stability.");
|
|
292
|
+
}
|
|
293
|
+
return {
|
|
294
|
+
rows: frame.rows,
|
|
295
|
+
y: fixedDesign.y,
|
|
296
|
+
xColNames,
|
|
297
|
+
x,
|
|
298
|
+
terms,
|
|
299
|
+
groups,
|
|
300
|
+
q: z.length,
|
|
301
|
+
z,
|
|
302
|
+
zColLevels,
|
|
303
|
+
theta,
|
|
304
|
+
lower,
|
|
305
|
+
lambda,
|
|
306
|
+
messages,
|
|
307
|
+
warnings,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { Sample } from "../htest/types.js";
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* A data frame: an object of columns of equal length. `null` (and `NaN` in a numeric column) is a missing value.
|
|
4
|
+
*
|
|
5
|
+
* @category Data frames
|
|
6
|
+
*/
|
|
3
7
|
export type DataFrame = Record<string, readonly (number | string | boolean | null)[] | Float64Array>;
|
|
4
8
|
/** A variable of a model frame: numeric values, or a factor (level index per row). */
|
|
5
9
|
export type FrameVariable = {
|
|
@@ -25,11 +29,22 @@ export interface ModelFrameOptions {
|
|
|
25
29
|
levels?: Record<string, readonly string[]>;
|
|
26
30
|
/** Weights: an array parallel to the rows of the data, or the name of a numeric column. */
|
|
27
31
|
weights?: Sample | string;
|
|
28
|
-
/** Drop levels that have no row left. */
|
|
32
|
+
/** Drop the levels of the columns with `levels` given that have no row left (not those of boolean columns). */
|
|
29
33
|
dropUnusedLevels?: boolean;
|
|
30
34
|
}
|
|
31
35
|
/** Comparison of strings by code point (not by UTF-16 code unit) */
|
|
32
36
|
export declare function compareCodePoints(a: string, b: string): number;
|
|
37
|
+
/**
|
|
38
|
+
* A factor variable of a model frame with only the levels that occur in its rows (in level order), for functions
|
|
39
|
+
* that group the rows by it: a boolean column keeps both levels in the frame, but its groups are the values present.
|
|
40
|
+
*/
|
|
41
|
+
export declare function presentLevels(v: {
|
|
42
|
+
levels: readonly string[];
|
|
43
|
+
codes: readonly number[];
|
|
44
|
+
}): {
|
|
45
|
+
levels: string[];
|
|
46
|
+
codes: number[];
|
|
47
|
+
};
|
|
33
48
|
/**
|
|
34
49
|
* The model frame of the given variables: each variable taken from the data, the rows with a missing value in any
|
|
35
50
|
* of them (or in the weights) dropped.
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
// Model frames: the variables of a formula taken from a data frame, with the rows that have a missing value dropped
|
|
2
2
|
// and string and boolean columns turned into factors (R's model.frame with na.omit).
|
|
3
3
|
//
|
|
4
|
-
// Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Data and missing values").
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// (R
|
|
4
|
+
// Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Data and missing values"). A string
|
|
5
|
+
// column is a factor formed from the rows kept (R's factor() after na.omit): its levels are the distinct values of
|
|
6
|
+
// those rows sorted by code point, unless `levels` gives them; a boolean column always has the levels FALSE and TRUE
|
|
7
|
+
// (R keeps it logical, and model.matrix codes a logical with both levels); numeric columns stay numeric.
|
|
8
|
+
// `dropUnusedLevels` removes the levels of the columns with `levels` given that have no row left (R's
|
|
9
|
+
// drop.unused.levels = TRUE, used by lm and aov); it does not apply to boolean columns. Functions that group rows by
|
|
10
|
+
// a variable use the levels present (`presentLevels`).
|
|
8
11
|
/** Comparison of strings by code point (not by UTF-16 code unit) */
|
|
9
12
|
export function compareCodePoints(a, b) {
|
|
10
13
|
const ia = a[Symbol.iterator]();
|
|
@@ -49,7 +52,28 @@ function convert(name, col, levels) {
|
|
|
49
52
|
lev = [...new Set(labels.filter((x) => x !== null))].sort(compareCodePoints);
|
|
50
53
|
const pos = new Map(lev.map((l, i) => [l, i]));
|
|
51
54
|
const codes = labels.map((l) => (l === null ? -1 : (pos.get(l) ?? -1)));
|
|
52
|
-
|
|
55
|
+
const source = levels !== undefined ? "given" : kind === "boolean" ? "logical" : "values";
|
|
56
|
+
return { v: { kind: "factor", levels: lev, codes }, missing: codes.map((c) => c < 0), source };
|
|
57
|
+
}
|
|
58
|
+
/** A factor restricted to its levels that occur in `codes` (their order kept) */
|
|
59
|
+
function dropUnused(levels, codes) {
|
|
60
|
+
const used = levels.map(() => false);
|
|
61
|
+
for (const c of codes)
|
|
62
|
+
used[c] = true;
|
|
63
|
+
const map = new Map();
|
|
64
|
+
const kept = levels.filter((_, k) => {
|
|
65
|
+
if (used[k])
|
|
66
|
+
map.set(k, map.size);
|
|
67
|
+
return used[k];
|
|
68
|
+
});
|
|
69
|
+
return { levels: kept, codes: codes.map((c) => map.get(c)) };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* A factor variable of a model frame with only the levels that occur in its rows (in level order), for functions
|
|
73
|
+
* that group the rows by it: a boolean column keeps both levels in the frame, but its groups are the values present.
|
|
74
|
+
*/
|
|
75
|
+
export function presentLevels(v) {
|
|
76
|
+
return dropUnused(v.levels, v.codes);
|
|
53
77
|
}
|
|
54
78
|
/**
|
|
55
79
|
* The model frame of the given variables: each variable taken from the data, the rows with a missing value in any
|
|
@@ -102,24 +126,15 @@ export function modelFrame(data, names, options = {}) {
|
|
|
102
126
|
continue;
|
|
103
127
|
rows.push(i);
|
|
104
128
|
}
|
|
105
|
-
const variables = conv.map(({ v }) => {
|
|
129
|
+
const variables = conv.map(({ v, source }) => {
|
|
106
130
|
if (v.kind === "numeric")
|
|
107
131
|
return { kind: "numeric", values: rows.map((i) => v.values[i]) };
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const map = new Map();
|
|
115
|
-
levels = levels.filter((_, k) => {
|
|
116
|
-
if (used[k])
|
|
117
|
-
map.set(k, map.size);
|
|
118
|
-
return used[k];
|
|
119
|
-
});
|
|
120
|
-
codes = codes.map((c) => map.get(c));
|
|
121
|
-
}
|
|
122
|
-
return { kind: "factor", levels, codes };
|
|
132
|
+
const codes = rows.map((i) => v.codes[i]);
|
|
133
|
+
// a string column's levels are the values of the rows kept; given levels are dropped only on request; a boolean
|
|
134
|
+
// column keeps FALSE and TRUE
|
|
135
|
+
if (source === "values" || (source === "given" && options.dropUnusedLevels))
|
|
136
|
+
return { kind: "factor", ...dropUnused(v.levels, codes) };
|
|
137
|
+
return { kind: "factor", levels: v.levels, codes };
|
|
123
138
|
});
|
|
124
139
|
const out = { rows, variables };
|
|
125
140
|
if (weights !== undefined) {
|
|
@@ -1,16 +1,32 @@
|
|
|
1
1
|
import { type FormulaNode, type ParsedFormula, type Terms } from "./formula.js";
|
|
2
2
|
import { type DataFrame, type ModelFrame } from "./modelFrame.js";
|
|
3
3
|
import type { Sample } from "../htest/types.js";
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* A contrast of a factor: R's `contr.treatment`, `contr.sum` or `contr.helmert`.
|
|
6
|
+
*
|
|
7
|
+
* @category Linear models and ANOVA
|
|
8
|
+
*/
|
|
5
9
|
export type ContrastName = "contr.treatment" | "contr.sum" | "contr.helmert";
|
|
6
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* Options for {@link modelMatrix}.
|
|
12
|
+
*
|
|
13
|
+
* @category Linear models and ANOVA
|
|
14
|
+
*/
|
|
7
15
|
export interface ModelMatrixOptions {
|
|
8
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* A contrast per factor (default `"contr.treatment"`); a boolean variable takes it too. A name that is not a
|
|
18
|
+
* variable of the formula gives the warning `variable 'B' is absent, its contrast will be ignored`; a numeric
|
|
19
|
+
* variable (the response too) is an error.
|
|
20
|
+
*/
|
|
9
21
|
contrasts?: Record<string, ContrastName>;
|
|
10
22
|
/** The order of the levels of a factor (`{ A: ["c", "a", "b"] }`), as `factor(x, levels = ...)` in R. */
|
|
11
23
|
levels?: Record<string, readonly string[]>;
|
|
12
24
|
}
|
|
13
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Result of {@link modelMatrix}.
|
|
27
|
+
*
|
|
28
|
+
* @category Linear models and ANOVA
|
|
29
|
+
*/
|
|
14
30
|
export interface ModelMatrixResult {
|
|
15
31
|
/** Column names, such as `"(Intercept)"`, `"Ab"`, `"Ab:Bq"`, `"x"`. */
|
|
16
32
|
colNames: string[];
|
|
@@ -60,6 +76,12 @@ export interface DesignOptions extends ModelMatrixOptions {
|
|
|
60
76
|
intercept?: boolean;
|
|
61
77
|
/** More variables whose missing values drop rows (the rest of the formula, for the error model of aov) */
|
|
62
78
|
extraVariables?: readonly string[];
|
|
79
|
+
/**
|
|
80
|
+
* The variables a name of `contrasts` may refer to without the warning that it is absent (default: the variables
|
|
81
|
+
* of the whole formula, the response included; lmer passes those of the fixed-effects part, aov with Error() those
|
|
82
|
+
* of the formula without the Error() term)
|
|
83
|
+
*/
|
|
84
|
+
contrastVariables?: readonly string[];
|
|
63
85
|
}
|
|
64
86
|
/**
|
|
65
87
|
* The model matrix of a parsed formula on the data.
|
|
@@ -69,11 +91,12 @@ export interface DesignOptions extends ModelMatrixOptions {
|
|
|
69
91
|
export declare function design(parsed: ParsedFormula, data: DataFrame, options?: DesignOptions, rhs?: FormulaNode | undefined): Design;
|
|
70
92
|
/**
|
|
71
93
|
* The model matrix of a formula on a data frame, with the attributes of R's `terms()`. Equivalent to R's
|
|
72
|
-
* `model.matrix(formula, data)
|
|
94
|
+
* `model.matrix(formula, data)`. With `contrasts.arg`, together with `attr(terms(formula), ...)`.
|
|
73
95
|
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
96
|
+
* Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the formula are dropped first.
|
|
97
|
+
* Strings are factors of the values in the rows kept (sorted by code point), unless `levels` gives the levels, which
|
|
98
|
+
* are then all kept even without a row (their columns are 0); booleans are factors with always the two levels FALSE
|
|
99
|
+
* and TRUE; numbers are numeric.
|
|
77
100
|
*
|
|
78
101
|
* @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
|
|
79
102
|
* @param data The data frame: an object of columns.
|
|
@@ -84,5 +107,7 @@ export declare function design(parsed: ParsedFormula, data: DataFrame, options?:
|
|
|
84
107
|
* m.colNames; // ["(Intercept)", "Ab"]
|
|
85
108
|
* m.x; // [[1, 0], [1, 1], [1, 0], [1, 1]]
|
|
86
109
|
* ```
|
|
110
|
+
*
|
|
111
|
+
* @category Linear models and ANOVA
|
|
87
112
|
*/
|
|
88
113
|
export declare function modelMatrix(formula: string, data: DataFrame, options?: ModelMatrixOptions): ModelMatrixResult;
|
|
@@ -66,6 +66,16 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
66
66
|
const nr = frame.rows.length;
|
|
67
67
|
// the terms that get columns, and the code of each variable in them
|
|
68
68
|
const used = terms.terms.map((_, j) => j !== terms.responseTerm);
|
|
69
|
+
// the contrasts given: a warning for each name that is not a variable of the formula (in the order of the object),
|
|
70
|
+
// an error for a numeric variable
|
|
71
|
+
const contrastWarnings = [];
|
|
72
|
+
const present = options.contrastVariables ?? terms.variables;
|
|
73
|
+
for (const name of Object.keys(options.contrasts ?? {})) {
|
|
74
|
+
if (!present.includes(name))
|
|
75
|
+
contrastWarnings.push(`variable '${name}' is absent, its contrast will be ignored`);
|
|
76
|
+
else if (vars[terms.variables.indexOf(name)]?.kind === "numeric")
|
|
77
|
+
throw new TypeError("contrasts apply only to factors");
|
|
78
|
+
}
|
|
69
79
|
const codes = terms.terms.map((t, j) => t.map((v) => terms.factors[v][j]));
|
|
70
80
|
for (let j = 0; j < terms.terms.length; j++) {
|
|
71
81
|
if (!used[j])
|
|
@@ -125,7 +135,10 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
125
135
|
}
|
|
126
136
|
});
|
|
127
137
|
const x = Array.from({ length: nr }, (_, i) => columns.map((c) => c[i]));
|
|
128
|
-
|
|
138
|
+
// (the warnings of terms() come first, those of model.matrix() after: the absent contrasts, then the response's term)
|
|
139
|
+
const fromTerms = terms.warnings.filter((w) => !w.startsWith("problem with term"));
|
|
140
|
+
const warnings = [...fromTerms, ...contrastWarnings, ...terms.warnings.filter((w) => !fromTerms.includes(w))];
|
|
141
|
+
const out = { terms, frame, x, colNames, assign, warnings };
|
|
129
142
|
if (terms.response >= 0) {
|
|
130
143
|
const r = vars[terms.response];
|
|
131
144
|
if (r.kind !== "numeric")
|
|
@@ -136,11 +149,12 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
136
149
|
}
|
|
137
150
|
/**
|
|
138
151
|
* The model matrix of a formula on a data frame, with the attributes of R's `terms()`. Equivalent to R's
|
|
139
|
-
* `model.matrix(formula, data)
|
|
152
|
+
* `model.matrix(formula, data)`. With `contrasts.arg`, together with `attr(terms(formula), ...)`.
|
|
140
153
|
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
154
|
+
* Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the formula are dropped first.
|
|
155
|
+
* Strings are factors of the values in the rows kept (sorted by code point), unless `levels` gives the levels, which
|
|
156
|
+
* are then all kept even without a row (their columns are 0); booleans are factors with always the two levels FALSE
|
|
157
|
+
* and TRUE; numbers are numeric.
|
|
144
158
|
*
|
|
145
159
|
* @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
|
|
146
160
|
* @param data The data frame: an object of columns.
|
|
@@ -151,6 +165,8 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
151
165
|
* m.colNames; // ["(Intercept)", "Ab"]
|
|
152
166
|
* m.x; // [[1, 0], [1, 1], [1, 0], [1, 1]]
|
|
153
167
|
* ```
|
|
168
|
+
*
|
|
169
|
+
* @category Linear models and ANOVA
|
|
154
170
|
*/
|
|
155
171
|
export function modelMatrix(formula, data, options = {}) {
|
|
156
172
|
const d = design(parseFormula(formula), data, options);
|