@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,399 @@
1
+ // Causal mediation analysis: mediation's mediate (Imai, Keele & Tingley 2010, Algorithms 1 and 2) for lm and binomial
2
+ // glm models. The behaviour is in oracle/mediation-behaviour.md, from the package's documentation and published output
3
+ // (experiments/mediation116*.R; every attempt, the failed ones too, in experiments/mediation116-log.md). Written for
4
+ // rStats.js (no ported code).
5
+ //
6
+ // - Quasi-Bayesian (boot false): the mediator model's coefficients, then the outcome model's, are drawn as rows of
7
+ // normals times the symmetric square root of their covariance; then the mediator is drawn for every simulation and
8
+ // observation (normal errors shared by M(t1) and M(t0) for an lm mediator, rbinom for M(t1) then M(t0) for a
9
+ // binomial one); the effects are means over the observations of differences of predicted outcomes
10
+ // - Bootstrap (boot true): one sample(n, n * sims, replace) as a sims x n matrix by column (replicate = row), an
11
+ // original-data draw whose value R does not use, each replicate refitted on its resample and evaluated on the
12
+ // original data, and a last original-data draw that gives the point estimates
13
+ // - The same values as R under the same setSeed (the symmetric square root does not depend on eigenvector signs)
14
+ import { lm } from "../models/lm.js";
15
+ import { glm, familyOf } from "../models/glm.js";
16
+ import { fitOptions } from "../models/fitOptions.js";
17
+ import { design } from "../models/modelMatrix.js";
18
+ import { parseFormula } from "../models/formula.js";
19
+ import { modelCovariance, vcovHC } from "../models/sandwich.js";
20
+ import { quantile } from "../descriptive/quantile.js";
21
+ import { mean as meanDD } from "../internal/summary.js";
22
+ import { median } from "../descriptive/basic.js";
23
+ import { qnorm, pnorm } from "../distributions/normal.js";
24
+ import { rnorm } from "../random/continuous.js";
25
+ import { rbinom1 } from "../random/binomial.js";
26
+ import { sampleInt } from "../random/sample.js";
27
+ import { symmetricSqrt } from "../random/mvrnorm.js";
28
+ import { reported, unreported } from "../internal/warnings.js";
29
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
30
+ import { checkOptions } from "../internal/checkOptions.js";
31
+ const MEDIATE_KEYS = /* @__PURE__ */ new Set([
32
+ "treat", "mediator", "treatValue", "controlValue", "covariates", "sims", "boot", "bootCiType", "confLevel",
33
+ "robustSE",
34
+ ]);
35
+ function prepare(fit, data, role) {
36
+ const options = fitOptions(fit);
37
+ if (options === undefined || typeof fit.formula !== "string")
38
+ throw new TypeError(`the ${role} model must be a formula fit of lm or glm`);
39
+ if (options.weights !== undefined || options.offset !== undefined)
40
+ throw new RangeError(`weights and offsets are not supported (the ${role} model)`);
41
+ const isGlm = "family" in fit;
42
+ let linkinv = (eta) => eta;
43
+ if (isGlm) {
44
+ const g = fit;
45
+ if (g.family === "binomial" && (g.link === "logit" || g.link === "probit"))
46
+ linkinv = familyOf(g).linkinv;
47
+ else if (!(g.family === "gaussian" && g.link === "identity"))
48
+ throw new RangeError(`the ${role} model's family is not supported (binomial with logit or probit, or gaussian)`);
49
+ }
50
+ if (fit.coefficients.some((c) => Number.isNaN(c)))
51
+ throw new RangeError(`the ${role} model has aliased coefficients`);
52
+ const formula = fit.formula;
53
+ const d = design(parseFormula(formula, false, false, true), data, {
54
+ ...(options.contrasts === undefined ? {} : { contrasts: options.contrasts }),
55
+ ...(options.levels === undefined ? {} : { levels: options.levels }),
56
+ dropUnusedLevels: true,
57
+ anyResponse: true,
58
+ });
59
+ const rows = isGlm ? fit.model.rows : fit.rows;
60
+ const names = isGlm ? fit.model.columnNames : fit.coefNames;
61
+ if (d.frame.rows.length !== rows.length || d.frame.rows.some((r, i) => r !== rows[i]) || d.colNames.join("\u0000") !== names.join("\u0000"))
62
+ throw new RangeError(`the data do not give the ${role} model's rows and columns (pass the data it was fitted on)`);
63
+ return { fit, isGlm, formula, options, coef: fit.coefficients.slice(), names, linkinv, d, rows };
64
+ }
65
+ /** Index of a variable among the design's variables, which must be numeric */
66
+ function numericVariable(p, name, role, required) {
67
+ const j = p.d.terms.variables.indexOf(name);
68
+ if (j < 0) {
69
+ if (required)
70
+ throw new RangeError(`'${name}' is not a variable of the ${role} model`);
71
+ return -1;
72
+ }
73
+ if (p.d.frame.variables[j].kind !== "numeric")
74
+ throw new RangeError(`'${name}' must be numeric in the ${role} model`);
75
+ return j;
76
+ }
77
+ /** Design rows for set values of some variables (each an array over the observations, or a constant) */
78
+ function rowsWith(p, set, n) {
79
+ const vars = p.d.frame.variables.map((v, j) => {
80
+ const s = set.get(j);
81
+ if (s === undefined)
82
+ return v;
83
+ return { kind: "numeric", values: typeof s === "number" ? new Array(n).fill(s) : s.slice() };
84
+ });
85
+ return p.d.rowsOf(vars, n);
86
+ }
87
+ const dot = (row, b) => {
88
+ let s = 0;
89
+ for (let k = 0; k < row.length; k++)
90
+ s += row[k] * b[k];
91
+ return s;
92
+ };
93
+ /**
94
+ * Rows of normals filled by row, times the symmetric square root of V, plus mu: R's parameter draws. A covariance whose
95
+ * entries leave the double range (variables on scales beyond about 1e+-150 make variances of 1e+-300 and more) cannot
96
+ * be decomposed: an error, where R errors or gives meaningless draws (experiments/mediation116-edge.R)
97
+ */
98
+ function drawParameters(mu, V, sims, role) {
99
+ const p = mu.length;
100
+ const MIN = 2 ** -1022, MAX = Number.MAX_VALUE;
101
+ if (V.some((r, i) => r.some((v) => !Number.isFinite(v)) || !(r[i] >= MIN && r[i] <= MAX)))
102
+ throw new RangeError(`the ${role} model's coefficient covariance is out of the double range (rescale the variables, or use boot: true)`);
103
+ const R = symmetricSqrt(V);
104
+ const z = rnorm(sims * p);
105
+ const out = [];
106
+ for (let j = 0; j < sims; j++) {
107
+ const row = [];
108
+ for (let c = 0; c < p; c++) {
109
+ let s = 0;
110
+ for (let k = 0; k < p; k++)
111
+ s += z[j * p + k] * R[k][c];
112
+ row.push(mu[c] + s);
113
+ }
114
+ out.push(row);
115
+ }
116
+ return out;
117
+ }
118
+ /** The mediator model's design rows with the treatment at t */
119
+ function mediatorRows(ctx, t) {
120
+ const set = new Map(ctx.mCov);
121
+ set.set(ctx.mTreat, t);
122
+ return rowsWith(ctx.m, set, ctx.n);
123
+ }
124
+ /** The outcome model's design rows at treatment t and mediator values m */
125
+ function outcomeRows(ctx, t, m) {
126
+ const set = new Map(ctx.yCov);
127
+ set.set(ctx.yTreat, t);
128
+ set.set(ctx.yMed, m);
129
+ return rowsWith(ctx.y, set, ctx.n);
130
+ }
131
+ /** The predicted outcomes (inverse link) at treatment t and mediator values m */
132
+ function outcomeMeans(ctx, t, m, b) {
133
+ return outcomeRows(ctx, t, m).map((row) => ctx.y.linkinv(dot(row, b)));
134
+ }
135
+ const meanDiff = (a, b) => meanDD(a.map((v, i) => v - b[i]));
136
+ function effectsFrom(ctx, m1, m0, b) {
137
+ if (isLinear(ctx.y)) {
138
+ // a linear outcome: the differences of the design rows times b, so that rows equal in the two conditions give
139
+ // exactly 0 (R's differences of predictions keep rounding residues of either sign, see oracle/mediation-behaviour.md)
140
+ const r01 = outcomeRows(ctx, ctx.t0, m1), r00 = outcomeRows(ctx, ctx.t0, m0);
141
+ const r11 = outcomeRows(ctx, ctx.t1, m1), r10 = outcomeRows(ctx, ctx.t1, m0);
142
+ const diff = (a, c) => meanDD(a.map((row, i) => {
143
+ let s = 0;
144
+ for (let k = 0; k < row.length; k++)
145
+ s += (row[k] - c[i][k]) * b[k];
146
+ return s;
147
+ }));
148
+ return [diff(r01, r00), diff(r11, r10), diff(r10, r00), diff(r11, r01), diff(r11, r00)];
149
+ }
150
+ const y01 = outcomeMeans(ctx, ctx.t0, m1, b), y00 = outcomeMeans(ctx, ctx.t0, m0, b);
151
+ const y11 = outcomeMeans(ctx, ctx.t1, m1, b), y10 = outcomeMeans(ctx, ctx.t1, m0, b);
152
+ return [meanDiff(y01, y00), meanDiff(y11, y10), meanDiff(y10, y00), meanDiff(y11, y01), meanDiff(y11, y00)];
153
+ }
154
+ /** One original-data (or one replicate's) draw of the mediator and the effects, for coefficients a, b */
155
+ function effectsOnce(ctx, a, sigma, b) {
156
+ const n = ctx.n;
157
+ const x1 = mediatorRows(ctx, ctx.t1).map((r) => dot(r, a)), x0 = mediatorRows(ctx, ctx.t0).map((r) => dot(r, a));
158
+ let m1, m0;
159
+ if (isLinear(ctx.m)) {
160
+ const e = rnorm(n, { sd: sigma });
161
+ m1 = x1.map((v, i) => v + e[i]);
162
+ m0 = x0.map((v, i) => v + e[i]);
163
+ }
164
+ else {
165
+ m1 = x1.map((v) => rbinom1(1, ctx.m.linkinv(v)));
166
+ m0 = x0.map((v) => rbinom1(1, ctx.m.linkinv(v)));
167
+ }
168
+ return effectsFrom(ctx, m1, m0, b);
169
+ }
170
+ const isLinear = (p) => !p.isGlm || p.fit.family === "gaussian";
171
+ const sigmaOf = (p) => (p.isGlm ? Math.sqrt(dispersion(p.fit)) : p.fit.sigma);
172
+ function dispersion(fit) {
173
+ // the Pearson dispersion of a gaussian glm: the residual sum of squares over the residual degrees of freedom
174
+ let s = 0;
175
+ for (let i = 0; i < fit.residuals.length; i++)
176
+ s += fit.weights[i] * fit.residuals[i] ** 2;
177
+ return s / fit.dfResidual;
178
+ }
179
+ /** The quantile of type 7 at two probabilities */
180
+ const q7 = (v, lo, hi) => {
181
+ const q = quantile(v, [lo, hi], { type: 7 });
182
+ return [q[0], q[1]];
183
+ };
184
+ /**
185
+ * Causal mediation analysis for linear and binomial (logit or probit) mediator and outcome models. Equivalent to
186
+ * `mediation::mediate()` in R.
187
+ *
188
+ * The average causal mediation effects (ACME, `d0` and `d1`), the average direct effects (ADE, `z0` and `z1`), the total
189
+ * effect (`tau`) and the proportions mediated (`n0`, `n1`) with their averages, by the quasi-Bayesian Monte Carlo
190
+ * approximation (the default) or the nonparametric bootstrap (`boot: true`), as in Imai, Keele and Tingley (2010).
191
+ * With the same {@link setSeed} the draws, estimates, intervals and p-values equal R's: the parameters are drawn with
192
+ * the symmetric square root of their covariance, then the mediator for every simulation and observation (normal errors
193
+ * with the residual standard error for a linear mediator, binomial draws for a binary one).
194
+ *
195
+ * Quasi-Bayesian estimates are the means of the draws (the proportions mediated: their medians; `nAvg` the average of
196
+ * the two medians); bootstrap estimates come from a final draw on the original data, after the replicates, as in R.
197
+ * Intervals are quantiles of type 7 of the draws (with `bootCiType: "bca"`: the bias-corrected and accelerated levels,
198
+ * the bias measured against the draws' mean and the acceleration from their skewness, as R).
199
+ *
200
+ * The models must be formula fits of {@link lm} or {@link glm} (binomial with logit or probit, or gaussian) on `data`,
201
+ * on the same rows, without weights or offsets; the treatment and the mediator are numeric variables.
202
+ *
203
+ * @param modelM The mediator model (its response is the mediator).
204
+ * @param modelY The outcome model (it includes the treatment and the mediator).
205
+ * @param data The data both models were fitted on.
206
+ * @param options See {@link MediateOptions}; `treat` and `mediator` are required.
207
+ * @returns See {@link MediateResult}.
208
+ * @throws TypeError or RangeError for unsupported models, data that do not reproduce the fits, a treatment or mediator
209
+ * that is not a numeric variable of the models, models on different rows, `sims` below 2, or
210
+ * `confLevel` outside (0, 1).
211
+ *
212
+ * @example
213
+ * ```ts
214
+ * const data = {
215
+ * 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],
216
+ * 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],
217
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
218
+ * };
219
+ * const m = lm("M ~ X + C", data), y = lm("Y ~ X + M + C", data);
220
+ * setSeed(1234);
221
+ * const r = mediate(m, y, data, { treat: "X", mediator: "M", sims: 500 });
222
+ * r.d0.estimate; // 0.8851 (R: set.seed(1234); mediate(m, y, treat = "X", mediator = "M", sims = 500)$d0)
223
+ * r.d0.ci; // [0.5261, 1.3011]
224
+ * r.n0.estimate; // 0.7432
225
+ * ```
226
+ *
227
+ * @category Causal inference
228
+ */
229
+ export function mediate(modelM, modelY, data, options) {
230
+ checkOptions(options, MEDIATE_KEYS, "mediate"); // generated: option-keys.mjs
231
+ const { treat, mediator } = options;
232
+ if (typeof treat !== "string" || typeof mediator !== "string")
233
+ throw new TypeError("'treat' and 'mediator' are required");
234
+ const t1 = options.treatValue ?? 1, t0 = options.controlValue ?? 0;
235
+ if (!Number.isFinite(t1) || !Number.isFinite(t0))
236
+ throw new RangeError("treatValue and controlValue must be finite");
237
+ const sims = Math.trunc(options.sims ?? 1000);
238
+ const boot = options.boot ?? false;
239
+ const ciType = options.bootCiType ?? "perc";
240
+ if (ciType !== "perc" && ciType !== "bca")
241
+ throw new RangeError("bootCiType must be \"perc\" or \"bca\"");
242
+ const level = options.confLevel ?? 0.95;
243
+ if (!(level > 0 && level < 1))
244
+ throw new RangeError("confLevel must be in (0, 1)");
245
+ const robust = options.robustSE ?? false;
246
+ // R's mediate fails with sims = 1 ("dim(X) must have a positive length"; always without the bootstrap, for some
247
+ // models with it), so 2 is the least
248
+ if (!(sims >= 2))
249
+ throw new RangeError("sims must be at least 2");
250
+ const warnings = [];
251
+ if (boot && robust)
252
+ warnings.push("'robustSE' is ignored for nonparametric bootstrap");
253
+ const m = prepare(modelM, data, "mediator"), y = prepare(modelY, data, "outcome");
254
+ if (!isLinear(m) && modelM.family !== "binomial")
255
+ throw new RangeError("unsupported mediator model");
256
+ if (m.d.terms.variables[0] !== mediator)
257
+ throw new RangeError(`the mediator model's response must be '${mediator}'`);
258
+ if (m.rows.length !== y.rows.length || m.rows.some((r, i) => r !== y.rows[i]))
259
+ throw new RangeError("number of observations do not match between mediator and outcome models");
260
+ const n = m.rows.length;
261
+ const covariates = Object.entries(options.covariates ?? {});
262
+ for (const [, v] of covariates)
263
+ if (!Number.isFinite(v))
264
+ throw new RangeError("covariate values must be finite");
265
+ const ctx = {
266
+ m, y, treat, mediator, t1, t0, n,
267
+ mTreat: numericVariable(m, treat, "mediator", true),
268
+ yTreat: numericVariable(y, treat, "outcome", true),
269
+ yMed: numericVariable(y, mediator, "outcome", true),
270
+ mCov: covariates.map(([k, v]) => [numericVariable(m, k, "mediator", false), v]).filter(([j]) => j >= 0),
271
+ yCov: covariates.map(([k, v]) => [numericVariable(y, k, "outcome", false), v]).filter(([j]) => j >= 0),
272
+ };
273
+ if (covariates.some(([k]) => !m.d.terms.variables.includes(k) && !y.d.terms.variables.includes(k)))
274
+ throw new RangeError("covariates must be variables of the models");
275
+ const linearM = isLinear(m);
276
+ let draws;
277
+ let point;
278
+ if (!boot) {
279
+ const vm = robust ? vcovHC(modelM, { type: "HC3" }).vcov : modelCovariance(modelM).vcov;
280
+ const vy = robust ? vcovHC(modelY, { type: "HC3" }).vcov : modelCovariance(modelY).vcov;
281
+ const A = drawParameters(m.coef, vm, sims, "mediator"), B = drawParameters(y.coef, vy, sims, "outcome");
282
+ const x1 = mediatorRows(ctx, t1), x0 = mediatorRows(ctx, t0);
283
+ // the mediator for all simulations at once, a sims x n matrix filled by column
284
+ const M1 = Array.from({ length: sims }, () => new Array(n));
285
+ const M0 = Array.from({ length: sims }, () => new Array(n));
286
+ if (linearM) {
287
+ const e = rnorm(sims * n, { sd: sigmaOf(m) });
288
+ for (let i = 0; i < n; i++)
289
+ for (let j = 0; j < sims; j++) {
290
+ M1[j][i] = dot(x1[i], A[j]) + e[i * sims + j];
291
+ M0[j][i] = dot(x0[i], A[j]) + e[i * sims + j];
292
+ }
293
+ }
294
+ else {
295
+ for (let i = 0; i < n; i++)
296
+ for (let j = 0; j < sims; j++)
297
+ M1[j][i] = rbinom1(1, m.linkinv(dot(x1[i], A[j])));
298
+ for (let i = 0; i < n; i++)
299
+ for (let j = 0; j < sims; j++)
300
+ M0[j][i] = rbinom1(1, m.linkinv(dot(x0[i], A[j])));
301
+ }
302
+ draws = A.map((_, j) => effectsFrom(ctx, M1[j], M0[j], B[j]));
303
+ }
304
+ else {
305
+ const idx = sampleInt(n, { size: n * sims, replace: true });
306
+ const variables = [...new Set([...m.d.terms.variables, ...y.d.terms.variables])];
307
+ const sigmaM = linearM ? sigmaOf(m) : NaN;
308
+ // the original-data draw that R makes before the replicates (its value is not used)
309
+ effectsOnce(ctx, m.coef, sigmaM, y.coef);
310
+ draws = [];
311
+ for (let j = 0; j < sims; j++) {
312
+ const take = Array.from({ length: n }, (_, i) => m.rows[idx[j + i * sims]]);
313
+ const resample = Object.fromEntries(variables.map((v) => {
314
+ const col = data[v];
315
+ return [v, take.map((r) => col[r])];
316
+ }));
317
+ const fm = refit(m, resample), fy = refit(y, resample);
318
+ draws.push(effectsOnce(ctx, aligned(fm, m, warnings), linearM ? sigmaOf({ ...m, fit: fm, isGlm: "family" in fm }) : NaN, aligned(fy, y, warnings)));
319
+ }
320
+ point = effectsOnce(ctx, m.coef, sigmaM, y.coef);
321
+ }
322
+ // the draws of every effect, then the summaries
323
+ const col = (k) => draws.map((e) => e[k]);
324
+ const d0 = col(0), d1 = col(1), z0 = col(2), z1 = col(3), tau = col(4);
325
+ const n0 = d0.map((v, j) => v / tau[j]), n1 = d1.map((v, j) => v / tau[j]);
326
+ const dAvg = d0.map((v, j) => (v + d1[j]) / 2), zAvg = z0.map((v, j) => (v + z1[j]) / 2), nAvg = n0.map((v, j) => (v + n1[j]) / 2);
327
+ const lo = (1 - level) / 2, hi = (1 + level) / 2;
328
+ const summarise = (v, est) => {
329
+ let ci;
330
+ if (boot && ciType === "bca") {
331
+ const mv = meanDD(v);
332
+ let s2 = 0, s3 = 0, below = 0;
333
+ for (const x of v) {
334
+ const u = mv - x;
335
+ s2 += u * u;
336
+ s3 += u * u * u;
337
+ if (x < mv)
338
+ below++;
339
+ }
340
+ const a = s3 / (6 * s2 ** 1.5);
341
+ const z0b = qnorm(below / v.length);
342
+ const level = (zq) => pnorm(z0b + (z0b + zq) / (1 - a * (z0b + zq)));
343
+ ci = q7(v, level(qnorm(lo)), level(qnorm(hi)));
344
+ }
345
+ else
346
+ ci = q7(v, lo, hi);
347
+ let pos = 0, neg = 0;
348
+ for (const x of v) {
349
+ if (x > 0)
350
+ pos++;
351
+ else if (x < 0)
352
+ neg++;
353
+ }
354
+ return { estimate: est, ci, p: 2 * Math.min(pos / v.length, neg / v.length), sims: v };
355
+ };
356
+ let est;
357
+ if (point === undefined) {
358
+ const mn0 = median(n0), mn1 = median(n1);
359
+ est = [meanDD(d0), meanDD(d1), meanDD(z0), meanDD(z1), meanDD(tau), mn0, mn1, meanDD(dAvg), meanDD(zAvg), (mn0 + mn1) / 2];
360
+ }
361
+ else {
362
+ const [p0, p1, q0, q1, pt] = point;
363
+ est = [p0, p1, q0, q1, pt, p0 / pt, p1 / pt, (p0 + p1) / 2, (q0 + q1) / 2, (p0 / pt + p1 / pt) / 2];
364
+ }
365
+ const INT = y.d.terms.termLabels.some((l) => {
366
+ const parts = l.split(":");
367
+ return parts.length > 1 && parts.includes(treat) && parts.includes(mediator);
368
+ });
369
+ return reported("mediate", {
370
+ d0: summarise(d0, est[0]), d1: summarise(d1, est[1]), z0: summarise(z0, est[2]), z1: summarise(z1, est[3]),
371
+ tau: summarise(tau, est[4]), n0: summarise(n0, est[5]), n1: summarise(n1, est[6]), dAvg: summarise(dAvg, est[7]),
372
+ zAvg: summarise(zAvg, est[8]), nAvg: summarise(nAvg, est[9]),
373
+ treatValue: t1, controlValue: t0, nobs: n, sims, boot, bootCiType: ciType, confLevel: level, robustSE: robust && !boot, INT,
374
+ warnings,
375
+ });
376
+ }
377
+ /** Refits a prepared model on a resample with its own options (warnings of the refits are not reported, as R's are only printed) */
378
+ function refit(p, resample) {
379
+ const opts = { ...p.options };
380
+ return unreported(() => (p.isGlm ? glm(p.formula, resample, opts) : lm(p.formula, resample, opts)));
381
+ }
382
+ const RANK_DEFICIENT = 'prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases';
383
+ /**
384
+ * A refit's coefficients in the original model's column order. A coefficient the resample cannot estimate (aliased,
385
+ * or the column of a level it lost) counts as 0 in the predictions, as R's predict does, with R's warning
386
+ * (experiments/mediation116-rankdeficient.R)
387
+ */
388
+ function aligned(fit, p, warnings) {
389
+ const names = "family" in fit ? fit.model.columnNames : fit.coefNames;
390
+ return p.names.map((nm) => {
391
+ const k = names.indexOf(nm);
392
+ if (k < 0 || Number.isNaN(fit.coefficients[k])) {
393
+ if (!warnings.includes(RANK_DEFICIENT))
394
+ warnings.push(RANK_DEFICIENT);
395
+ return 0;
396
+ }
397
+ return fit.coefficients[k];
398
+ });
399
+ }
@@ -0,0 +1,231 @@
1
+ import type { DataFrame } from "../models/modelFrame.js";
2
+ import { type MediateResult, type MediationModel } from "./mediate.js";
3
+ /**
4
+ * Options for {@link sobelTest} and {@link mediationMonteCarlo}.
5
+ *
6
+ * @category Causal inference
7
+ */
8
+ export interface SobelTestOptions {
9
+ /** The treatment (a coefficient of both models). */
10
+ treat: string;
11
+ /** The mediator (the mediator model's response, a coefficient of the outcome model). */
12
+ mediator: string;
13
+ }
14
+ /**
15
+ * Result of {@link sobelTest}.
16
+ *
17
+ * @category Causal inference
18
+ */
19
+ export interface SobelTestResult {
20
+ /** The treatment's coefficient in the mediator model. */
21
+ a: number;
22
+ /** Its standard error. */
23
+ sa: number;
24
+ /** The mediator's coefficient in the outcome model. */
25
+ b: number;
26
+ /** Its standard error. */
27
+ sb: number;
28
+ /** The indirect effect a b. */
29
+ ab: number;
30
+ /** Its standard error sqrt(b² sa² + a² sb²). */
31
+ se: number;
32
+ /** The z statistic a b / se. */
33
+ z: number;
34
+ /** The two-sided p-value. */
35
+ p: number;
36
+ }
37
+ /**
38
+ * The Sobel test of the indirect effect a b (the product of the treatment's coefficient in the mediator model and the
39
+ * mediator's in the outcome model), as ReactiveStat computes it: SE = sqrt(b² sa² + a² sb²), z = a b / SE, p from the
40
+ * normal distribution. Not an R function. ReactiveStat computes it from the two models' coefficients.
41
+ *
42
+ * @param modelM The mediator model (a formula fit of {@link lm} or {@link glm}).
43
+ * @param modelY The outcome model.
44
+ * @param options See {@link SobelTestOptions}.
45
+ * @returns See {@link SobelTestResult}.
46
+ * @throws RangeError if a model lacks the coefficient.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const data = {
51
+ * 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],
52
+ * 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],
53
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
54
+ * };
55
+ * const s = sobelTest(lm("M ~ X", data), lm("Y ~ X + M", data), { treat: "X", mediator: "M" });
56
+ * s.ab; // 1.0713
57
+ * s.z; // 2.3529
58
+ * s.p; // 0.018628
59
+ * ```
60
+ *
61
+ * @category Causal inference
62
+ */
63
+ export declare function sobelTest(modelM: MediationModel, modelY: MediationModel, options: SobelTestOptions): SobelTestResult;
64
+ /**
65
+ * One Monte Carlo quantity: the estimate from the fitted coefficients, the interval and the draws.
66
+ *
67
+ * @category Causal inference
68
+ */
69
+ export interface MonteCarloEffect {
70
+ /** The estimate (from the fitted coefficients, or as mediate's). */
71
+ estimate: number;
72
+ /** The confidence interval (type-7 quantiles of the draws). */
73
+ ci: [number, number];
74
+ /** The draws. */
75
+ sims: number[];
76
+ }
77
+ /**
78
+ * Options for {@link mediationMonteCarlo}.
79
+ *
80
+ * @category Causal inference
81
+ */
82
+ export interface MediationMonteCarloOptions extends SobelTestOptions {
83
+ /** Number of draws (default 20000, as ReactiveStat). */
84
+ nmc?: number;
85
+ /** Confidence level (default 0.95). */
86
+ confLevel?: number;
87
+ }
88
+ /**
89
+ * Result of {@link mediationMonteCarlo}: effects per unit of the treatment.
90
+ *
91
+ * @category Causal inference
92
+ */
93
+ export interface MediationMonteCarloResult {
94
+ /** The indirect effect a b. */
95
+ indirect: MonteCarloEffect;
96
+ /** The direct effect c'. */
97
+ direct: MonteCarloEffect;
98
+ /** The total effect a b + c'. */
99
+ total: MonteCarloEffect;
100
+ /** The proportion mediated a b / (a b + c'). */
101
+ proportion: MonteCarloEffect;
102
+ }
103
+ /**
104
+ * The Monte Carlo method on the coefficients for a mediation with continuous mediator and outcome, as ReactiveStat
105
+ * computes it: a is drawn by `rnorm(nmc, a, sa)`, then (b, c') of the outcome model by `mvrnorm` with their 2 x 2
106
+ * covariance; the intervals are type-7 quantiles. With the same {@link setSeed} the draws equal R's
107
+ * (`set.seed(...); rnorm(...); MASS::mvrnorm(...)`). Not an R function. ReactiveStat composes it from `rnorm` and
108
+ * `mvrnorm`.
109
+ *
110
+ * @param modelM The mediator model.
111
+ * @param modelY The outcome model.
112
+ * @param options See {@link MediationMonteCarloOptions}.
113
+ * @returns See {@link MediationMonteCarloResult}.
114
+ * @throws RangeError if a model lacks the coefficients or `confLevel` is outside (0, 1).
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * const data = {
119
+ * 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],
120
+ * 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],
121
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
122
+ * };
123
+ * setSeed(1234);
124
+ * mediationMonteCarlo(lm("M ~ X", data), lm("Y ~ X + M", data), { treat: "X", mediator: "M" }).indirect.ci; // [0.19969, 1.9643]
125
+ * ```
126
+ *
127
+ * @category Causal inference
128
+ */
129
+ export declare function mediationMonteCarlo(modelM: MediationModel, modelY: MediationModel, options: MediationMonteCarloOptions): MediationMonteCarloResult;
130
+ /**
131
+ * Options for {@link moderatedMediation}.
132
+ *
133
+ * @category Causal inference
134
+ */
135
+ export interface ModeratedMediationOptions extends SobelTestOptions {
136
+ /** The moderator W (a numeric variable of both models). */
137
+ moderator: string;
138
+ /** The treated value (default: the larger value of a binary treatment, else its mean + SD). */
139
+ treatValue?: number;
140
+ /** The control value (default: the smaller value of a binary treatment, else its mean − SD). */
141
+ controlValue?: number;
142
+ /** The moderator's low value (default: the smaller value of a binary moderator, else its mean − SD). */
143
+ wLow?: number;
144
+ /** The moderator's high value (default: the larger value of a binary moderator, else its mean + SD). */
145
+ wHigh?: number;
146
+ /**
147
+ * `"monteCarlo"` (draws of all the coefficients of both models) or `"mediate"` ({@link mediate} at the two moderator
148
+ * values on the same random stream). Default: `"monteCarlo"` when both models are linear, else `"mediate"`, as
149
+ * ReactiveStat.
150
+ */
151
+ method?: "monteCarlo" | "mediate";
152
+ /** Number of Monte Carlo draws (default 20000). */
153
+ nmc?: number;
154
+ /** Number of simulations of {@link mediate} (default 1000). */
155
+ sims?: number;
156
+ /** Confidence level (default 0.95). */
157
+ confLevel?: number;
158
+ /** HC3 covariances in {@link mediate} (default `false`). */
159
+ robustSE?: boolean;
160
+ }
161
+ /**
162
+ * Result of {@link moderatedMediation}.
163
+ *
164
+ * @category Causal inference
165
+ */
166
+ export interface ModeratedMediationResult {
167
+ /** The method used. */
168
+ method: "monteCarlo" | "mediate";
169
+ /** The moderator's low value. */
170
+ wLow: number;
171
+ /** The moderator's high value. */
172
+ wHigh: number;
173
+ /** The treated value. */
174
+ treatValue: number;
175
+ /** The control value. */
176
+ controlValue: number;
177
+ /** The indirect effect (ACME; with `mediate`, the average of d0 and d1) at the low moderator value. */
178
+ indirectLow: MonteCarloEffect;
179
+ /** The indirect effect at the high moderator value. */
180
+ indirectHigh: MonteCarloEffect;
181
+ /** The direct effect (ADE) at the low moderator value. */
182
+ directLow: MonteCarloEffect;
183
+ /** The direct effect at the high moderator value. */
184
+ directHigh: MonteCarloEffect;
185
+ /** The total effect at the low moderator value. */
186
+ totalLow: MonteCarloEffect;
187
+ /** The total effect at the high moderator value. */
188
+ totalHigh: MonteCarloEffect;
189
+ /** The index of moderated mediation: the indirect effect at the high value minus that at the low value. */
190
+ index: MonteCarloEffect;
191
+ /** With `method: "mediate"`, the {@link mediate} result at the low moderator value. */
192
+ low?: MediateResult;
193
+ /** With `method: "mediate"`, the {@link mediate} result at the high moderator value. */
194
+ high?: MediateResult;
195
+ }
196
+ /**
197
+ * Moderated mediation with the index of moderated mediation, as ReactiveStat computes it: the indirect (ACME), direct
198
+ * (ADE) and total effects at a low and a high value of a moderator W that enters both models.
199
+ *
200
+ * With `method: "monteCarlo"` (linear models) all coefficients of both models are drawn by {@link mvrnorm}, the mediator
201
+ * 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
202
+ * the interactions of the treatment and the mediator with W (0 when absent); the estimates come from the fitted
203
+ * coefficients. These draws are in 4 or more dimensions, where rStats.js's eigenvector signs may differ from R's, so the
204
+ * intervals agree with R's statistically, not digit for digit. With `method: "mediate"`, {@link mediate} is run at
205
+ * W = wLow and W = wHigh (R's `covariates`) from the same generator state, and the index's draws are the differences
206
+ * of the average ACME draws; these equal R's under the same {@link setSeed}. Not an R function. ReactiveStat composes
207
+ * it from `mvrnorm` or `mediate`.
208
+ *
209
+ * @param modelM The mediator model (with W, and the treatment × W interaction if any).
210
+ * @param modelY The outcome model (with W, and the mediator × W and treatment × W interactions if any).
211
+ * @param data The data both models were fitted on.
212
+ * @param options See {@link ModeratedMediationOptions}.
213
+ * @returns See {@link ModeratedMediationResult}.
214
+ * @throws RangeError if a model lacks the coefficients, or for the errors of {@link mediate}.
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * const data = {
219
+ * 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],
220
+ * 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],
221
+ * W: [3.1, 2.2, 4.0, 2.8, 3.5, 2.9, 3.8, 2.4, 3.3, 4.2],
222
+ * };
223
+ * const m = lm("M ~ X * W", data), y = lm("Y ~ X * W + M * W", data);
224
+ * setSeed(1234);
225
+ * const r = moderatedMediation(m, y, data, { treat: "X", mediator: "M", moderator: "W" });
226
+ * r.index.estimate; r.index.ci;
227
+ * ```
228
+ *
229
+ * @category Causal inference
230
+ */
231
+ export declare function moderatedMediation(modelM: MediationModel, modelY: MediationModel, data: DataFrame, options: ModeratedMediationOptions): ModeratedMediationResult;