@numero-uno-jpn/rstats 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.ja.md +8 -8
  3. package/README.md +8 -8
  4. package/dist/causal/mediate.d.ts +146 -0
  5. package/dist/causal/mediate.js +399 -0
  6. package/dist/causal/mediationProcedures.d.ts +231 -0
  7. package/dist/causal/mediationProcedures.js +240 -0
  8. package/dist/causal/moderation.d.ts +148 -0
  9. package/dist/causal/moderation.js +165 -0
  10. package/dist/causal.js +2 -2
  11. package/dist/chunks/{chunk-FD375XBW.js → chunk-23QCIPET.js} +2 -2
  12. package/dist/chunks/chunk-3UEYA6VG.js +2 -0
  13. package/dist/chunks/{chunk-SMA62635.js → chunk-3Y4DNK4O.js} +2 -2
  14. package/dist/chunks/{chunk-L7HJGM52.js → chunk-4BGGWQWS.js} +2 -2
  15. package/dist/chunks/chunk-5UFVACSV.js +2 -0
  16. package/dist/chunks/{chunk-5BCXHJPF.js → chunk-5W2OZAHQ.js} +2 -2
  17. package/dist/chunks/{chunk-PZRABNMZ.js → chunk-6MLDKHTY.js} +2 -2
  18. package/dist/chunks/{chunk-XVRRYHLM.js → chunk-72I7GDWL.js} +2 -2
  19. package/dist/chunks/chunk-BWDXJL7T.js +2 -0
  20. package/dist/chunks/{chunk-VO3E4Q6H.js → chunk-DD2GG4EC.js} +1 -1
  21. package/dist/chunks/{chunk-CIBAGTO2.js → chunk-EB45CDFA.js} +2 -2
  22. package/dist/chunks/chunk-EIUK6TKF.js +2 -0
  23. package/dist/chunks/chunk-GIIURG5X.js +2 -0
  24. package/dist/chunks/chunk-GLABB425.js +2 -0
  25. package/dist/chunks/{chunk-OO22LZ7Q.js → chunk-GOYTZ5RB.js} +2 -2
  26. package/dist/chunks/{chunk-HF4TT233.js → chunk-GTSK4IN4.js} +1 -1
  27. package/dist/chunks/{chunk-SNQABDAT.js → chunk-I2KJMF4G.js} +1 -1
  28. package/dist/chunks/chunk-JG4TWDQ4.js +2 -0
  29. package/dist/chunks/{chunk-UFJFVNC6.js → chunk-JHABMYNH.js} +1 -1
  30. package/dist/chunks/chunk-JV3POOET.js +2 -0
  31. package/dist/chunks/chunk-K3YSXDTU.js +2 -0
  32. package/dist/chunks/{chunk-R74QJUYU.js → chunk-KY53MB3J.js} +2 -2
  33. package/dist/chunks/{chunk-AGA7JCRF.js → chunk-L77QFL3C.js} +2 -2
  34. package/dist/chunks/chunk-LKKUUREA.js +2 -0
  35. package/dist/chunks/{chunk-WL3JGBLZ.js → chunk-LY2UZGUL.js} +2 -2
  36. package/dist/chunks/chunk-NCDPZSI2.js +2 -0
  37. package/dist/chunks/{chunk-6SZLUVSL.js → chunk-NCRL33PQ.js} +2 -2
  38. package/dist/chunks/{chunk-RHNGF7R7.js → chunk-NPWWGIFG.js} +2 -2
  39. package/dist/chunks/chunk-O4D43LWM.js +2 -0
  40. package/dist/chunks/chunk-PSQ6MLJM.js +2 -0
  41. package/dist/chunks/{chunk-M3HFLMXL.js → chunk-QCPGV7XH.js} +2 -2
  42. package/dist/chunks/{chunk-JAXYZJV7.js → chunk-RM5D7Q7W.js} +2 -2
  43. package/dist/chunks/{chunk-IMSXMJ43.js → chunk-RNGDVSTS.js} +2 -2
  44. package/dist/chunks/{chunk-3K47QLCY.js → chunk-SA2E5GVO.js} +2 -2
  45. package/dist/chunks/{chunk-VHMFOILD.js → chunk-T5ZALLTJ.js} +2 -2
  46. package/dist/chunks/{chunk-GBNGGBU3.js → chunk-TTOJDLIQ.js} +2 -2
  47. package/dist/chunks/{chunk-FV4ZQPRI.js → chunk-V54MBEJM.js} +2 -2
  48. package/dist/chunks/chunk-VZSQAGL2.js +3 -0
  49. package/dist/chunks/{chunk-NULJXDAR.js → chunk-XEJX5HBJ.js} +2 -2
  50. package/dist/chunks/chunk-XPYZOG5H.js +2 -0
  51. package/dist/chunks/{chunk-4EH3O466.js → chunk-XR7Y4ZV6.js} +2 -2
  52. package/dist/chunks/{chunk-JGZSGGMD.js → chunk-YMI33F7W.js} +2 -2
  53. package/dist/chunks/{chunk-MKCPS5QQ.js → chunk-ZRKXHVTJ.js} +2 -2
  54. package/dist/descriptive.js +2 -2
  55. package/dist/distributions.js +2 -2
  56. package/dist/entries/causal.d.ts +3 -0
  57. package/dist/entries/causal.js +3 -0
  58. package/dist/entries/distributions.d.ts +1 -0
  59. package/dist/entries/distributions.js +1 -0
  60. package/dist/entries/regression.d.ts +3 -0
  61. package/dist/entries/regression.js +6 -0
  62. package/dist/linalg.js +2 -2
  63. package/dist/mixed.js +2 -2
  64. package/dist/models/betareg.d.ts +278 -0
  65. package/dist/models/betareg.js +588 -0
  66. package/dist/models/fitOptions.js +6 -4
  67. package/dist/models/loglin.d.ts +186 -0
  68. package/dist/models/loglin.js +349 -0
  69. package/dist/models/survreg.d.ts +43 -0
  70. package/dist/models/survreg.js +6 -3
  71. package/dist/models/tobit.d.ts +132 -0
  72. package/dist/models/tobit.js +172 -0
  73. package/dist/multivariate.js +2 -2
  74. package/dist/numerics.js +2 -2
  75. package/dist/random/mvrnorm.d.ts +60 -0
  76. package/dist/random/mvrnorm.js +237 -0
  77. package/dist/regression.js +3 -3
  78. package/dist/rstats.js +16 -16
  79. package/dist/special.js +2 -2
  80. package/dist/tests.js +15 -15
  81. package/dist/timeseries.js +2 -2
  82. package/package.json +1 -1
  83. package/dist/chunks/chunk-5JKKIVYL.js +0 -3
  84. package/dist/chunks/chunk-5Q5YVM7S.js +0 -2
  85. package/dist/chunks/chunk-AILN2NGE.js +0 -2
  86. package/dist/chunks/chunk-APOF7BLH.js +0 -2
  87. package/dist/chunks/chunk-HSVVCFEN.js +0 -2
  88. package/dist/chunks/chunk-KQGH6SEW.js +0 -2
  89. package/dist/chunks/chunk-OBTCIG5D.js +0 -2
  90. package/dist/chunks/chunk-P4TKSL4W.js +0 -2
  91. package/dist/chunks/chunk-RV4JZHTE.js +0 -2
  92. package/dist/chunks/chunk-U5UOVXKD.js +0 -2
  93. package/dist/chunks/chunk-VHBIWPB4.js +0 -2
  94. package/dist/chunks/chunk-YYLBBEWZ.js +0 -2
  95. package/dist/chunks/chunk-ZDUVFNFH.js +0 -2
  96. package/dist/chunks/chunk-ZUTVNRML.js +0 -2
@@ -0,0 +1,240 @@
1
+ // ReactiveStat's mediation procedures outside R's functions (scripts/多変量/媒介分析.php and 調整媒介分析.php): the
2
+ // Sobel test, the Monte Carlo method on the coefficients, and moderated mediation with the index of moderated mediation
3
+ // (Hayes 2015). The behaviour is in oracle/mediation-behaviour.md. Written for rStats.js (no ported code).
4
+ //
5
+ // - Sobel: a b / sqrt(b² sa² + a² sb²) against the normal distribution
6
+ // - Monte Carlo (mediation): a ~ rnorm(nmc, a, sa), then (b, c') ~ mvrnorm(nmc, ...) of the outcome model (2 dimensions:
7
+ // R's values under the same setSeed)
8
+ // - Moderated mediation: with linear models, mvrnorm of all the coefficients of both models (3 or more dimensions: R's
9
+ // distribution, not R's values, see src/random/mvrnorm.ts); otherwise mediate at the moderator's low and high values
10
+ // on the same random stream
11
+ import { modelCovariance, vcovHC } from "../models/sandwich.js";
12
+ import { quantile } from "../descriptive/quantile.js";
13
+ import { mean as meanDD, variance } from "../internal/summary.js";
14
+ import { pnorm } from "../distributions/normal.js";
15
+ import { rnorm } from "../random/continuous.js";
16
+ import { mvrnorm } from "../random/mvrnorm.js";
17
+ import { getRandomSeed, setRandomSeed } from "../random/rng.js";
18
+ import { mediate } from "./mediate.js";
19
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
20
+ import { checkOptions } from "../internal/checkOptions.js";
21
+ const SOBEL_TEST_KEYS = ["treat", "mediator"];
22
+ const MEDIATION_MONTE_CARLO_KEYS = ["nmc", "confLevel", "treat", "mediator"];
23
+ const MODERATED_MEDIATION_KEYS = /* @__PURE__ */ new Set([
24
+ "moderator", "treatValue", "controlValue", "wLow", "wHigh", "method", "nmc", "sims", "confLevel", "robustSE",
25
+ "treat", "mediator",
26
+ ]);
27
+ /** A coefficient and its variance, by name */
28
+ function coefficient(fit, name, role) {
29
+ const cov = modelCovariance(fit);
30
+ const k = cov.names.indexOf(name);
31
+ if (k < 0)
32
+ throw new RangeError(`the ${role} model has no coefficient '${name}'`);
33
+ const names = "family" in fit ? fit.model.columnNames : fit.coefNames;
34
+ return { value: fit.coefficients[names.indexOf(name)], v: cov.vcov[k][k], names: cov.names, vcov: cov.vcov };
35
+ }
36
+ /**
37
+ * The Sobel test of the indirect effect a b (the product of the treatment's coefficient in the mediator model and the
38
+ * mediator's in the outcome model), as ReactiveStat computes it: SE = sqrt(b² sa² + a² sb²), z = a b / SE, p from the
39
+ * normal distribution. Not an R function. ReactiveStat computes it from the two models' coefficients.
40
+ *
41
+ * @param modelM The mediator model (a formula fit of {@link lm} or {@link glm}).
42
+ * @param modelY The outcome model.
43
+ * @param options See {@link SobelTestOptions}.
44
+ * @returns See {@link SobelTestResult}.
45
+ * @throws RangeError if a model lacks the coefficient.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const data = {
50
+ * X: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], C: [1.2, -0.4, 0.3, 0.8, -1.1, 0.5, -0.2, 1.4, -0.7, 0.1],
51
+ * M: [1.1, 0.4, 0.9, 1.6, 0.2, 1.9, 1.3, 2.6, 1.0, 1.8], Y: [2.0, 1.1, 1.5, 2.4, 0.8, 3.1, 2.2, 3.9, 1.9, 2.8],
52
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
53
+ * };
54
+ * const s = sobelTest(lm("M ~ X", data), lm("Y ~ X + M", data), { treat: "X", mediator: "M" });
55
+ * s.ab; // 1.0713
56
+ * s.z; // 2.3529
57
+ * s.p; // 0.018628
58
+ * ```
59
+ *
60
+ * @category Causal inference
61
+ */
62
+ export function sobelTest(modelM, modelY, options) {
63
+ checkOptions(options, SOBEL_TEST_KEYS, "sobelTest"); // generated: option-keys.mjs
64
+ const ca = coefficient(modelM, options.treat, "mediator"), cb = coefficient(modelY, options.mediator, "outcome");
65
+ const a = ca.value, b = cb.value, sa = Math.sqrt(ca.v), sb = Math.sqrt(cb.v);
66
+ const ab = a * b, se = Math.sqrt(b * b * sa * sa + a * a * sb * sb), z = ab / se;
67
+ return { a, sa, b, sb, ab, se, z, p: 2 * pnorm(Math.abs(z), { lowerTail: false }) };
68
+ }
69
+ const q7 = (v, level) => {
70
+ const al = 1 - level;
71
+ const q = quantile(v, [al / 2, 1 - al / 2], { type: 7 });
72
+ return [q[0], q[1]];
73
+ };
74
+ function checkLevel(level) {
75
+ if (!(level > 0 && level < 1))
76
+ throw new RangeError("confLevel must be in (0, 1)");
77
+ }
78
+ /**
79
+ * The Monte Carlo method on the coefficients for a mediation with continuous mediator and outcome, as ReactiveStat
80
+ * computes it: a is drawn by `rnorm(nmc, a, sa)`, then (b, c') of the outcome model by `mvrnorm` with their 2 x 2
81
+ * covariance; the intervals are type-7 quantiles. With the same {@link setSeed} the draws equal R's
82
+ * (`set.seed(...); rnorm(...); MASS::mvrnorm(...)`). Not an R function. ReactiveStat composes it from `rnorm` and
83
+ * `mvrnorm`.
84
+ *
85
+ * @param modelM The mediator model.
86
+ * @param modelY The outcome model.
87
+ * @param options See {@link MediationMonteCarloOptions}.
88
+ * @returns See {@link MediationMonteCarloResult}.
89
+ * @throws RangeError if a model lacks the coefficients or `confLevel` is outside (0, 1).
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const data = {
94
+ * X: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], C: [1.2, -0.4, 0.3, 0.8, -1.1, 0.5, -0.2, 1.4, -0.7, 0.1],
95
+ * M: [1.1, 0.4, 0.9, 1.6, 0.2, 1.9, 1.3, 2.6, 1.0, 1.8], Y: [2.0, 1.1, 1.5, 2.4, 0.8, 3.1, 2.2, 3.9, 1.9, 2.8],
96
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
97
+ * };
98
+ * setSeed(1234);
99
+ * mediationMonteCarlo(lm("M ~ X", data), lm("Y ~ X + M", data), { treat: "X", mediator: "M" }).indirect.ci; // [0.19969, 1.9643]
100
+ * ```
101
+ *
102
+ * @category Causal inference
103
+ */
104
+ export function mediationMonteCarlo(modelM, modelY, options) {
105
+ checkOptions(options, MEDIATION_MONTE_CARLO_KEYS, "mediationMonteCarlo"); // generated: option-keys.mjs
106
+ const nmc = Math.trunc(options.nmc ?? 20000), level = options.confLevel ?? 0.95;
107
+ checkLevel(level);
108
+ if (!(nmc >= 2))
109
+ throw new RangeError("nmc must be at least 2");
110
+ const ca = coefficient(modelM, options.treat, "mediator");
111
+ const cb = coefficient(modelY, options.mediator, "outcome"), cc = coefficient(modelY, options.treat, "outcome");
112
+ const iM = cb.names.indexOf(options.mediator), iX = cb.names.indexOf(options.treat);
113
+ const aDraws = rnorm(nmc, { mean: ca.value, sd: Math.sqrt(ca.v) });
114
+ const bc = mvrnorm(nmc, [cb.value, cc.value], [[cb.vcov[iM][iM], cb.vcov[iM][iX]], [cb.vcov[iX][iM], cb.vcov[iX][iX]]]);
115
+ const ind = aDraws.map((a, j) => a * bc[j][0]), dir = bc.map((r) => r[1]), tot = ind.map((v, j) => v + dir[j]);
116
+ const prop = ind.map((v, j) => v / tot[j]);
117
+ const ab = ca.value * cb.value, cp = cc.value;
118
+ const effect = (estimate, sims) => ({ estimate, ci: q7(sims, level), sims });
119
+ return { indirect: effect(ab, ind), direct: effect(cp, dir), total: effect(ab + cp, tot), proportion: effect(ab / (ab + cp), prop) };
120
+ }
121
+ /** ReactiveStat's two values of a variable: the two values if binary, else mean ± SD (on the model's rows) */
122
+ function twoValues(data, rows, name) {
123
+ const col = data[name];
124
+ if (col === undefined)
125
+ throw new RangeError(`object '${name}' not found`);
126
+ const v = rows.map((r) => Number(col[r]));
127
+ if (v.some((x) => !Number.isFinite(x)))
128
+ throw new RangeError(`'${name}' must be numeric`);
129
+ const u = [...new Set(v)].sort((a, b) => a - b);
130
+ if (u.length === 2)
131
+ return [u[0], u[1]];
132
+ const m = meanDD(v), s = Math.sqrt(variance(v));
133
+ return [m - s, m + s];
134
+ }
135
+ const isLinearFit = (fit) => !("family" in fit) || fit.family === "gaussian";
136
+ const rowsOfFit = (fit) => ("family" in fit ? fit.model.rows : fit.rows);
137
+ /**
138
+ * Moderated mediation with the index of moderated mediation, as ReactiveStat computes it: the indirect (ACME), direct
139
+ * (ADE) and total effects at a low and a high value of a moderator W that enters both models.
140
+ *
141
+ * With `method: "monteCarlo"` (linear models) all coefficients of both models are drawn by {@link mvrnorm}, the mediator
142
+ * model's first, and ACME(w) = (t1 − t0)(a1 + a3 w)(b1 + b3 w), ADE(w) = (t1 − t0)(c1 + c3 w), where a3, b3 and c3 are
143
+ * the interactions of the treatment and the mediator with W (0 when absent); the estimates come from the fitted
144
+ * coefficients. These draws are in 4 or more dimensions, where rStats.js's eigenvector signs may differ from R's, so the
145
+ * intervals agree with R's statistically, not digit for digit. With `method: "mediate"`, {@link mediate} is run at
146
+ * W = wLow and W = wHigh (R's `covariates`) from the same generator state, and the index's draws are the differences
147
+ * of the average ACME draws; these equal R's under the same {@link setSeed}. Not an R function. ReactiveStat composes
148
+ * it from `mvrnorm` or `mediate`.
149
+ *
150
+ * @param modelM The mediator model (with W, and the treatment × W interaction if any).
151
+ * @param modelY The outcome model (with W, and the mediator × W and treatment × W interactions if any).
152
+ * @param data The data both models were fitted on.
153
+ * @param options See {@link ModeratedMediationOptions}.
154
+ * @returns See {@link ModeratedMediationResult}.
155
+ * @throws RangeError if a model lacks the coefficients, or for the errors of {@link mediate}.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * const data = {
160
+ * X: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], C: [1.2, -0.4, 0.3, 0.8, -1.1, 0.5, -0.2, 1.4, -0.7, 0.1],
161
+ * M: [1.1, 0.4, 0.9, 1.6, 0.2, 1.9, 1.3, 2.6, 1.0, 1.8], Y: [2.0, 1.1, 1.5, 2.4, 0.8, 3.1, 2.2, 3.9, 1.9, 2.8],
162
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
163
+ * };
164
+ * const m = lm("M ~ X * W", data), y = lm("Y ~ X * W + M * W", data);
165
+ * setSeed(1234);
166
+ * const r = moderatedMediation(m, y, data, { treat: "X", mediator: "M", moderator: "W" });
167
+ * r.index.estimate; r.index.ci;
168
+ * ```
169
+ *
170
+ * @category Causal inference
171
+ */
172
+ export function moderatedMediation(modelM, modelY, data, options) {
173
+ checkOptions(options, MODERATED_MEDIATION_KEYS, "moderatedMediation"); // generated: option-keys.mjs
174
+ const { treat, mediator, moderator } = options;
175
+ if (typeof treat !== "string" || typeof mediator !== "string" || typeof moderator !== "string")
176
+ throw new TypeError("'treat', 'mediator' and 'moderator' are required");
177
+ const level = options.confLevel ?? 0.95;
178
+ checkLevel(level);
179
+ const rows = rowsOfFit(modelM);
180
+ const [cvDefault, tvDefault] = twoValues(data, rows, treat);
181
+ const [wloDefault, whiDefault] = twoValues(data, rows, moderator);
182
+ const t1 = options.treatValue ?? tvDefault, t0 = options.controlValue ?? cvDefault;
183
+ const wLow = options.wLow ?? wloDefault, wHigh = options.wHigh ?? whiDefault;
184
+ const method = options.method ?? (isLinearFit(modelM) && isLinearFit(modelY) ? "monteCarlo" : "mediate");
185
+ const effect = (estimate, sims) => ({ estimate, ci: q7(sims, level), sims });
186
+ const base = { method, wLow, wHigh, treatValue: t1, controlValue: t0 };
187
+ if (method === "mediate") {
188
+ const state = getRandomSeed();
189
+ const run = (w) => mediate(modelM, modelY, data, {
190
+ treat, mediator, treatValue: t1, controlValue: t0, covariates: { [moderator]: w }, sims: options.sims ?? 1000,
191
+ confLevel: level, robustSE: options.robustSE ?? false,
192
+ });
193
+ const low = run(wLow);
194
+ setRandomSeed(state);
195
+ const high = run(wHigh);
196
+ const idx = high.dAvg.sims.map((v, j) => v - low.dAvg.sims[j]);
197
+ const asEffect = (e) => ({ estimate: e.estimate, ci: e.ci, sims: e.sims });
198
+ return {
199
+ ...base, indirectLow: asEffect(low.dAvg), indirectHigh: asEffect(high.dAvg), directLow: asEffect(low.zAvg),
200
+ directHigh: asEffect(high.zAvg), totalLow: asEffect(low.tau), totalHigh: asEffect(high.tau),
201
+ index: effect(high.dAvg.estimate - low.dAvg.estimate, idx), low, high,
202
+ };
203
+ }
204
+ if (method !== "monteCarlo")
205
+ throw new RangeError("method must be \"monteCarlo\" or \"mediate\"");
206
+ const nmc = Math.trunc(options.nmc ?? 20000);
207
+ if (!(nmc >= 2))
208
+ throw new RangeError("nmc must be at least 2");
209
+ const covM = options.robustSE ? vcovHC(modelM, { type: "HC3" }) : modelCovariance(modelM);
210
+ const covY = options.robustSE ? vcovHC(modelY, { type: "HC3" }) : modelCovariance(modelY);
211
+ const coefOf = (fit, names) => names.map((nm) => {
212
+ const all = "family" in fit ? fit.model.columnNames : fit.coefNames;
213
+ return fit.coefficients[all.indexOf(nm)];
214
+ });
215
+ const bm = mvrnorm(nmc, coefOf(modelM, covM.names), covM.vcov), bo = mvrnorm(nmc, coefOf(modelY, covY.names), covY.vcov);
216
+ const cm = coefOf(modelM, covM.names), co = coefOf(modelY, covY.names);
217
+ const find = (names, a, b) => {
218
+ const k = b === undefined ? names.indexOf(a) : [`${a}:${b}`, `${b}:${a}`].map((x) => names.indexOf(x)).find((i) => i >= 0) ?? -1;
219
+ if (b === undefined && k < 0)
220
+ throw new RangeError(`a model has no coefficient '${a}'`);
221
+ return k;
222
+ };
223
+ const a1 = find(covM.names, treat), a3 = find(covM.names, treat, moderator);
224
+ const b1 = find(covY.names, mediator), b3 = find(covY.names, mediator, moderator);
225
+ const c1 = find(covY.names, treat), c3 = find(covY.names, treat, moderator);
226
+ const at = (v, k) => (k < 0 ? 0 : v[k]);
227
+ const dx = t1 - t0;
228
+ const acme = (m, o, w) => dx * (at(m, a1) + at(m, a3) * w) * (at(o, b1) + at(o, b3) * w);
229
+ const ade = (o, w) => dx * (at(o, c1) + at(o, c3) * w);
230
+ const series = (f) => Array.from({ length: nmc }, (_, j) => f(j));
231
+ const aLo = series((j) => acme(bm[j], bo[j], wLow)), aHi = series((j) => acme(bm[j], bo[j], wHigh));
232
+ const dLo = series((j) => ade(bo[j], wLow)), dHi = series((j) => ade(bo[j], wHigh));
233
+ const eaLo = acme(cm, co, wLow), eaHi = acme(cm, co, wHigh), edLo = ade(co, wLow), edHi = ade(co, wHigh);
234
+ return {
235
+ ...base,
236
+ indirectLow: effect(eaLo, aLo), indirectHigh: effect(eaHi, aHi), directLow: effect(edLo, dLo), directHigh: effect(edHi, dHi),
237
+ totalLow: effect(eaLo + edLo, aLo.map((v, j) => v + dLo[j])), totalHigh: effect(eaHi + edHi, aHi.map((v, j) => v + dHi[j])),
238
+ index: effect(eaHi - eaLo, aHi.map((v, j) => v - aLo[j])),
239
+ };
240
+ }
@@ -0,0 +1,148 @@
1
+ import type { LmFormulaResult } from "../models/lm.js";
2
+ import type { GlmFormulaResult } from "../models/glm.js";
3
+ import type { DataFrame } from "../models/modelFrame.js";
4
+ /**
5
+ * A model for {@link simSlopes} and {@link johnsonNeyman}: a formula fit of {@link lm} or {@link glm}.
6
+ *
7
+ * @category Causal inference
8
+ */
9
+ export type ModerationModel = LmFormulaResult | GlmFormulaResult;
10
+ /**
11
+ * Options for {@link johnsonNeyman}.
12
+ *
13
+ * @category Causal inference
14
+ */
15
+ export interface JohnsonNeymanOptions {
16
+ /** The predictor whose slope is examined. */
17
+ pred: string;
18
+ /** The moderator. */
19
+ modx: string;
20
+ /** Significance level (default 0.05). */
21
+ alpha?: number;
22
+ /** `"HC3"` for heteroskedasticity-consistent standard errors, `false` (the default) for the model's. */
23
+ robust?: false | "HC3";
24
+ }
25
+ /**
26
+ * Result of {@link johnsonNeyman}.
27
+ *
28
+ * @category Causal inference
29
+ */
30
+ export interface JohnsonNeymanResult {
31
+ /** The two bounds (sorted); `[-Infinity, Infinity]` when the interval could not be found. */
32
+ bounds: [number, number];
33
+ /** Whether the slope is significant inside the bounds (else outside them). */
34
+ inside: boolean;
35
+ /** Whether no real bound exists (interactions' "could not be found"). */
36
+ failed: boolean;
37
+ /** Whether no bound lies within the observed range of the moderator (interactions' `all_sig`; also when failed). */
38
+ allSig: boolean;
39
+ /** The observed range of the moderator. */
40
+ modrange: [number, number];
41
+ /** The significance level. */
42
+ alpha: number;
43
+ }
44
+ /**
45
+ * Options for {@link simSlopes}.
46
+ *
47
+ * @category Causal inference
48
+ */
49
+ export interface SimSlopesOptions {
50
+ /** The predictor whose slope is examined. */
51
+ pred: string;
52
+ /** The moderator. */
53
+ modx: string;
54
+ /** The moderator's values: `"mean-plus-minus"` (the default: mean − SD, mean, mean + SD) or numbers. */
55
+ modxValues?: "mean-plus-minus" | readonly number[];
56
+ /** Also compute the Johnson-Neyman interval (default `true`). */
57
+ johnsonNeyman?: boolean;
58
+ /** The Johnson-Neyman significance level (default 0.05). */
59
+ jnAlpha?: number;
60
+ /** Width of the confidence intervals (default 0.95). */
61
+ ciWidth?: number;
62
+ /** `"HC3"` for heteroskedasticity-consistent standard errors, `false` (the default) for the model's. */
63
+ robust?: false | "HC3";
64
+ }
65
+ /**
66
+ * Result of {@link simSlopes}: one row per moderator value.
67
+ *
68
+ * @category Causal inference
69
+ */
70
+ export interface SimSlopesResult {
71
+ /** The moderator's values. */
72
+ values: number[];
73
+ /** The slopes of the predictor. */
74
+ estimate: number[];
75
+ /** Their standard errors. */
76
+ se: number[];
77
+ /** Lower confidence limits. */
78
+ lower: number[];
79
+ /** Upper confidence limits. */
80
+ upper: number[];
81
+ /** The t (lm) or z (glm) statistics. */
82
+ statistic: number[];
83
+ /** `"t"` or `"z"`. */
84
+ statisticName: "t" | "z";
85
+ /** Two-sided p-values. */
86
+ p: number[];
87
+ /** The Johnson-Neyman interval, when asked for. */
88
+ jn?: JohnsonNeymanResult;
89
+ }
90
+ /**
91
+ * The Johnson-Neyman interval: the moderator values at which the predictor's slope stops being significant.
92
+ * Equivalent to `interactions::johnson_neyman()` in R. Its bounds, `inside`, `failed` and `all_sig` are returned; there
93
+ * is no plot.
94
+ *
95
+ * The bounds solve (b_X + b_XW w)² = t² Var(b_X + b_XW w), with the t quantile on the model's residual degrees of
96
+ * freedom (for a glm too, as interactions does). The slope is significant inside the bounds when the quadratic's
97
+ * leading coefficient is negative, else outside them.
98
+ *
99
+ * @param fit A formula fit of {@link lm} or {@link glm} with the interaction `pred:modx`.
100
+ * @param data The data it was fitted on (for the moderator's observed range).
101
+ * @param options See {@link JohnsonNeymanOptions}.
102
+ * @returns See {@link JohnsonNeymanResult}.
103
+ * @throws RangeError if the model lacks the coefficients or the moderator is not numeric.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * const data = {
108
+ * X: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], C: [1.2, -0.4, 0.3, 0.8, -1.1, 0.5, -0.2, 1.4, -0.7, 0.1],
109
+ * M: [1.1, 0.4, 0.9, 1.6, 0.2, 1.9, 1.3, 2.6, 1.0, 1.8], Y: [2.0, 1.1, 1.5, 2.4, 0.8, 3.1, 2.2, 3.9, 1.9, 2.8],
110
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
111
+ * };
112
+ * const fit = lm("Y ~ X * W", data);
113
+ * johnsonNeyman(fit, data, { pred: "X", modx: "W" }).bounds; // [2.4941, 3.4079]
114
+ * ```
115
+ *
116
+ * @category Causal inference
117
+ */
118
+ export declare function johnsonNeyman(fit: ModerationModel, data: DataFrame, options: JohnsonNeymanOptions): JohnsonNeymanResult;
119
+ /**
120
+ * Simple slopes of a predictor at values of a moderator, with the Johnson-Neyman interval. Equivalent to
121
+ * `interactions::sim_slopes()` in R. The slopes table (as with `confint = TRUE`) and the Johnson-Neyman results are
122
+ * returned.
123
+ *
124
+ * The slope at w is b_X + b_XW w with standard error sqrt(V_XX + 2 w V_XW + w² V_WW), from the model's covariance or
125
+ * its HC3 sandwich; intervals and p-values use t on the residual degrees of freedom for lm and the normal distribution
126
+ * for glm. `"mean-plus-minus"` takes the moderator's mean and mean ± SD on the model's rows.
127
+ *
128
+ * @param fit A formula fit of {@link lm} or {@link glm} (binomial or gaussian) with the interaction `pred:modx`.
129
+ * @param data The data it was fitted on.
130
+ * @param options See {@link SimSlopesOptions}.
131
+ * @returns See {@link SimSlopesResult}.
132
+ * @throws RangeError if the model lacks the coefficients, the moderator is not numeric or the levels are outside (0, 1).
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * const data = {
137
+ * X: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], C: [1.2, -0.4, 0.3, 0.8, -1.1, 0.5, -0.2, 1.4, -0.7, 0.1],
138
+ * M: [1.1, 0.4, 0.9, 1.6, 0.2, 1.9, 1.3, 2.6, 1.0, 1.8], Y: [2.0, 1.1, 1.5, 2.4, 0.8, 3.1, 2.2, 3.9, 1.9, 2.8],
139
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
140
+ * };
141
+ * const s = simSlopes(lm("Y ~ X * W", data), data, { pred: "X", modx: "W" });
142
+ * s.estimate; // [1.6926, 1.2999, 0.90721]
143
+ * s.p; // [0.045753, 0.031345, 0.22941]
144
+ * ```
145
+ *
146
+ * @category Causal inference
147
+ */
148
+ export declare function simSlopes(fit: ModerationModel, data: DataFrame, options: SimSlopesOptions): SimSlopesResult;
@@ -0,0 +1,165 @@
1
+ // Moderation: simple slopes and the Johnson-Neyman interval (interactions' sim_slopes and johnson_neyman) for lm and
2
+ // binomial glm models with a two-way interaction. The behaviour is in oracle/mediation-behaviour.md, from the package's
3
+ // documentation and published output (experiments/mediation116-slopes.R; every attempt in
4
+ // experiments/mediation116-log.md); Bauer & Curran (2005) for the interval. Written for rStats.js (no ported code).
5
+ //
6
+ // - The slope of the predictor at a moderator value w is b_X + b_XW w, its variance V_XX + 2 w V_XW + w^2 V_WW
7
+ // - Intervals and p-values use t on the residual degrees of freedom for lm and the normal distribution for glm; the
8
+ // Johnson-Neyman bounds use t on the residual degrees of freedom for both (as interactions does)
9
+ // - robust "HC3": sandwich's vcovHC with type HC3
10
+ import { modelCovariance, vcovHC } from "../models/sandwich.js";
11
+ import { mean as meanDD, variance } from "../internal/summary.js";
12
+ import { qt, pt } from "../distributions/t.js";
13
+ import { qnorm, pnorm } from "../distributions/normal.js";
14
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
15
+ import { checkOptions } from "../internal/checkOptions.js";
16
+ const SIM_SLOPES_KEYS = ["pred", "modx", "modxValues", "johnsonNeyman", "jnAlpha", "ciWidth", "robust"];
17
+ const JOHNSON_NEYMAN_KEYS = ["pred", "modx", "alpha", "robust"];
18
+ /** The coefficients and covariances of the predictor and the interaction, and the moderator's values on the model's rows */
19
+ function parts(fit, data, pred, modx, robust) {
20
+ if (typeof pred !== "string" || typeof modx !== "string")
21
+ throw new TypeError("'pred' and 'modx' are required");
22
+ if (robust !== false && robust !== "HC3")
23
+ throw new RangeError("robust must be false or \"HC3\"");
24
+ const isGlm = "family" in fit;
25
+ const names = isGlm ? fit.model.columnNames : fit.coefNames;
26
+ if (names === undefined)
27
+ throw new TypeError("the model must be a formula fit of lm or glm");
28
+ if (isGlm && fit.family !== "binomial" && fit.family !== "gaussian")
29
+ throw new RangeError("the model's family is not supported (binomial or gaussian)");
30
+ const inter = [`${pred}:${modx}`, `${modx}:${pred}`].find((k) => names.includes(k));
31
+ if (!names.includes(pred) || inter === undefined)
32
+ throw new RangeError(`the model has no coefficients '${pred}' and '${pred}:${modx}'`);
33
+ const cov = robust === "HC3" ? vcovHC(fit, { type: "HC3" }) : modelCovariance(fit);
34
+ const i1 = cov.names.indexOf(pred), i3 = cov.names.indexOf(inter);
35
+ if (i1 < 0 || i3 < 0)
36
+ throw new RangeError("the predictor's or the interaction's coefficient is aliased");
37
+ const c = fit.coefficients;
38
+ const rows = isGlm ? fit.model.rows : fit.rows;
39
+ const col = data[modx];
40
+ if (col === undefined)
41
+ throw new RangeError(`object '${modx}' not found`);
42
+ const w = rows.map((r) => Number(col[r]));
43
+ if (w.some((v) => !Number.isFinite(v)))
44
+ throw new RangeError(`'${modx}' must be numeric`);
45
+ return {
46
+ b1: c[names.indexOf(pred)], b3: c[names.indexOf(inter)], v11: cov.vcov[i1][i1], v13: cov.vcov[i1][i3],
47
+ v33: cov.vcov[i3][i3], df: fit.dfResidual, isGlm: isGlm && fit.family === "binomial", w,
48
+ };
49
+ }
50
+ function jn(q, alpha) {
51
+ if (!(alpha > 0 && alpha < 1))
52
+ throw new RangeError("alpha must be in (0, 1)");
53
+ const crit = qt(1 - alpha / 2, q.df);
54
+ const c2 = crit * crit;
55
+ const A = q.b3 * q.b3 - c2 * q.v33, B = 2 * (q.b1 * q.b3 - c2 * q.v13), C = q.b1 * q.b1 - c2 * q.v11;
56
+ const disc = B * B - 4 * A * C;
57
+ const lo = Math.min(...q.w), hi = Math.max(...q.w);
58
+ const modrange = [lo, hi];
59
+ let bounds, failed = false;
60
+ if (!(disc >= 0)) {
61
+ bounds = [-Infinity, Infinity];
62
+ failed = true;
63
+ }
64
+ else {
65
+ const s = Math.sqrt(disc);
66
+ // the root without cancellation, then the other from the product of the roots
67
+ const r1 = (-B - Math.sign(B || 1) * s) / (2 * A);
68
+ const r2 = r1 === 0 ? (-B + Math.sign(B || 1) * s) / (2 * A) : C / (A * r1);
69
+ bounds = r1 <= r2 ? [r1, r2] : [r2, r1];
70
+ }
71
+ // interactions reports inside = FALSE when the interval could not be found
72
+ const inside = !failed && A < 0;
73
+ const allSig = !(bounds[0] > lo && bounds[0] < hi) && !(bounds[1] > lo && bounds[1] < hi);
74
+ return { bounds, inside, failed, allSig, modrange, alpha };
75
+ }
76
+ /**
77
+ * The Johnson-Neyman interval: the moderator values at which the predictor's slope stops being significant.
78
+ * Equivalent to `interactions::johnson_neyman()` in R. Its bounds, `inside`, `failed` and `all_sig` are returned; there
79
+ * is no plot.
80
+ *
81
+ * The bounds solve (b_X + b_XW w)² = t² Var(b_X + b_XW w), with the t quantile on the model's residual degrees of
82
+ * freedom (for a glm too, as interactions does). The slope is significant inside the bounds when the quadratic's
83
+ * leading coefficient is negative, else outside them.
84
+ *
85
+ * @param fit A formula fit of {@link lm} or {@link glm} with the interaction `pred:modx`.
86
+ * @param data The data it was fitted on (for the moderator's observed range).
87
+ * @param options See {@link JohnsonNeymanOptions}.
88
+ * @returns See {@link JohnsonNeymanResult}.
89
+ * @throws RangeError if the model lacks the coefficients or the moderator is not numeric.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const data = {
94
+ * X: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], C: [1.2, -0.4, 0.3, 0.8, -1.1, 0.5, -0.2, 1.4, -0.7, 0.1],
95
+ * M: [1.1, 0.4, 0.9, 1.6, 0.2, 1.9, 1.3, 2.6, 1.0, 1.8], Y: [2.0, 1.1, 1.5, 2.4, 0.8, 3.1, 2.2, 3.9, 1.9, 2.8],
96
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
97
+ * };
98
+ * const fit = lm("Y ~ X * W", data);
99
+ * johnsonNeyman(fit, data, { pred: "X", modx: "W" }).bounds; // [2.4941, 3.4079]
100
+ * ```
101
+ *
102
+ * @category Causal inference
103
+ */
104
+ export function johnsonNeyman(fit, data, options) {
105
+ checkOptions(options, JOHNSON_NEYMAN_KEYS, "johnsonNeyman"); // generated: option-keys.mjs
106
+ return jn(parts(fit, data, options.pred, options.modx, options.robust ?? false), options.alpha ?? 0.05);
107
+ }
108
+ /**
109
+ * Simple slopes of a predictor at values of a moderator, with the Johnson-Neyman interval. Equivalent to
110
+ * `interactions::sim_slopes()` in R. The slopes table (as with `confint = TRUE`) and the Johnson-Neyman results are
111
+ * returned.
112
+ *
113
+ * The slope at w is b_X + b_XW w with standard error sqrt(V_XX + 2 w V_XW + w² V_WW), from the model's covariance or
114
+ * its HC3 sandwich; intervals and p-values use t on the residual degrees of freedom for lm and the normal distribution
115
+ * for glm. `"mean-plus-minus"` takes the moderator's mean and mean ± SD on the model's rows.
116
+ *
117
+ * @param fit A formula fit of {@link lm} or {@link glm} (binomial or gaussian) with the interaction `pred:modx`.
118
+ * @param data The data it was fitted on.
119
+ * @param options See {@link SimSlopesOptions}.
120
+ * @returns See {@link SimSlopesResult}.
121
+ * @throws RangeError if the model lacks the coefficients, the moderator is not numeric or the levels are outside (0, 1).
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * const data = {
126
+ * X: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], C: [1.2, -0.4, 0.3, 0.8, -1.1, 0.5, -0.2, 1.4, -0.7, 0.1],
127
+ * M: [1.1, 0.4, 0.9, 1.6, 0.2, 1.9, 1.3, 2.6, 1.0, 1.8], Y: [2.0, 1.1, 1.5, 2.4, 0.8, 3.1, 2.2, 3.9, 1.9, 2.8],
128
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
129
+ * };
130
+ * const s = simSlopes(lm("Y ~ X * W", data), data, { pred: "X", modx: "W" });
131
+ * s.estimate; // [1.6926, 1.2999, 0.90721]
132
+ * s.p; // [0.045753, 0.031345, 0.22941]
133
+ * ```
134
+ *
135
+ * @category Causal inference
136
+ */
137
+ export function simSlopes(fit, data, options) {
138
+ checkOptions(options, SIM_SLOPES_KEYS, "simSlopes"); // generated: option-keys.mjs
139
+ const q = parts(fit, data, options.pred, options.modx, options.robust ?? false);
140
+ const width = options.ciWidth ?? 0.95;
141
+ if (!(width > 0 && width < 1))
142
+ throw new RangeError("ciWidth must be in (0, 1)");
143
+ const mv = options.modxValues ?? "mean-plus-minus";
144
+ let values;
145
+ if (mv === "mean-plus-minus") {
146
+ const m = meanDD(q.w), s = Math.sqrt(variance(q.w));
147
+ values = [m - s, m, m + s];
148
+ }
149
+ else if (Array.isArray(mv) && mv.every((v) => Number.isFinite(v)))
150
+ values = [...mv];
151
+ else
152
+ throw new RangeError("modxValues must be \"mean-plus-minus\" or finite numbers");
153
+ const crit = q.isGlm ? qnorm((1 + width) / 2) : qt((1 + width) / 2, q.df);
154
+ const estimate = values.map((w) => q.b1 + q.b3 * w);
155
+ const se = values.map((w) => Math.sqrt(q.v11 + 2 * w * q.v13 + w * w * q.v33));
156
+ const statistic = estimate.map((e, i) => e / se[i]);
157
+ const p = statistic.map((t) => 2 * (q.isGlm ? pnorm(-Math.abs(t)) : pt(-Math.abs(t), q.df)));
158
+ const out = {
159
+ values, estimate, se, lower: estimate.map((e, i) => e - crit * se[i]), upper: estimate.map((e, i) => e + crit * se[i]),
160
+ statistic, statisticName: q.isGlm ? "z" : "t", p,
161
+ };
162
+ if (options.johnsonNeyman ?? true)
163
+ out.jn = jn(q, options.jnAlpha ?? 0.05);
164
+ return out;
165
+ }