@numero-uno-jpn/rstats 1.2.0 → 1.4.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 +128 -0
- package/README.ja.md +28 -11
- package/README.md +27 -10
- package/dist/chunks/{chunk-RRO4LMCB.js → chunk-27VFB3SA.js} +2 -2
- package/dist/chunks/{chunk-BKV3FINA.js → chunk-56GFP4UU.js} +2 -2
- package/dist/chunks/{chunk-JWBSEL3V.js → chunk-5SW3L6J3.js} +2 -2
- package/dist/chunks/{chunk-NSU6U3ET.js → chunk-6FZAJQ4H.js} +2 -2
- package/dist/chunks/{chunk-VERBXW6E.js → chunk-BQJFFGYP.js} +2 -2
- package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-F6Z3GLWA.js} +2 -2
- package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-GBSMRVUY.js} +2 -2
- package/dist/chunks/{chunk-7WG7X2UI.js → chunk-GEF2YRBV.js} +2 -2
- package/dist/chunks/{chunk-L23RSC2N.js → chunk-GIER5WMB.js} +2 -2
- package/dist/chunks/{chunk-IAWXF73N.js → chunk-GLGOV3A5.js} +2 -2
- package/dist/chunks/{chunk-F3EQLL4F.js → chunk-H72MW7YP.js} +2 -2
- package/dist/chunks/{chunk-T5DRIITM.js → chunk-HWB7XRX2.js} +2 -2
- package/dist/chunks/chunk-J72MLFUG.js +2 -0
- package/dist/chunks/{chunk-TNETWBF5.js → chunk-PZ66PUWC.js} +2 -2
- package/dist/chunks/{chunk-IMPRIQE5.js → chunk-RUZATICF.js} +1 -1
- package/dist/chunks/{chunk-BI7NYJWP.js → chunk-RY7CCWVU.js} +1 -1
- package/dist/chunks/{chunk-7INBXTVV.js → chunk-S2YCFUCA.js} +2 -2
- package/dist/chunks/chunk-SVS54D6Z.js +2 -0
- package/dist/chunks/{chunk-HBHMEPGY.js → chunk-TEHMTQNB.js} +3 -3
- package/dist/chunks/chunk-UMMCVF53.js +2 -0
- package/dist/chunks/{chunk-5SGTWSCB.js → chunk-UNP4HBPP.js} +2 -2
- package/dist/chunks/{chunk-A66M3ZEA.js → chunk-V2KVTAVV.js} +2 -2
- package/dist/chunks/{chunk-EEU7D4RU.js → chunk-WWJGCBWH.js} +1 -1
- package/dist/chunks/chunk-X7K6EF7S.js +2 -0
- package/dist/chunks/{chunk-73LNRWU3.js → chunk-YBOSCQF2.js} +1 -1
- package/dist/chunks/{chunk-6FZHTD5G.js → chunk-ZQSOMEIM.js} +2 -2
- package/dist/chunks/{chunk-4AOTAT3O.js → chunk-ZRFZ5UIB.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +13 -0
- package/dist/entries/tests.js +13 -0
- package/dist/htest/agreement.d.ts +2 -2
- package/dist/htest/blandAltman.d.ts +100 -0
- package/dist/htest/blandAltman.js +159 -0
- package/dist/htest/diagnosticTests.d.ts +91 -0
- package/dist/htest/diagnosticTests.js +116 -0
- package/dist/htest/iccPsych.d.ts +106 -0
- package/dist/htest/iccPsych.js +332 -0
- package/dist/htest/ksTest.d.ts +1 -1
- package/dist/htest/mcreg.d.ts +209 -0
- package/dist/htest/mcreg.js +735 -0
- package/dist/htest/roc.d.ts +287 -0
- package/dist/htest/roc.js +635 -0
- package/dist/htest/rocTest.d.ts +139 -0
- package/dist/htest/rocTest.js +444 -0
- package/dist/htest/tTOST.d.ts +202 -0
- package/dist/htest/tTOST.js +558 -0
- package/dist/htest/trendTests.d.ts +1 -1
- package/dist/htest/trendTests.js +1 -1
- package/dist/internal/summary.js +5 -0
- package/dist/linalg/qr.d.ts +3 -0
- package/dist/linalg/qr.js +3 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/coeftest.d.ts +139 -0
- package/dist/models/coeftest.js +237 -0
- package/dist/models/competingRisks.d.ts +188 -0
- package/dist/models/competingRisks.js +673 -0
- package/dist/models/coxZph.d.ts +67 -0
- package/dist/models/coxZph.js +479 -0
- package/dist/models/coxph.d.ts +107 -16
- package/dist/models/coxph.js +641 -72
- package/dist/models/glm.d.ts +11 -1
- package/dist/models/glm.js +19 -2
- package/dist/models/inputRows.d.ts +10 -0
- package/dist/models/inputRows.js +23 -0
- package/dist/models/lm.d.ts +8 -0
- package/dist/models/lm.js +14 -2
- package/dist/models/rmst2.d.ts +126 -0
- package/dist/models/rmst2.js +365 -0
- package/dist/models/sandwich.d.ts +177 -0
- package/dist/models/sandwich.js +923 -0
- package/dist/models/survival.d.ts +65 -24
- package/dist/models/survival.js +407 -72
- package/dist/models/survreg.d.ts +160 -0
- package/dist/models/survreg.js +809 -0
- package/dist/numerics.js +2 -2
- package/dist/random/rng.d.ts +8 -1
- package/dist/random/rng.js +14 -1
- package/dist/rstats.js +16 -16
- package/dist/special.js +2 -2
- package/dist/tests.js +13 -13
- package/llms.txt +25 -0
- package/package.json +1 -1
- package/dist/chunks/chunk-47IIPUFN.js +0 -2
- package/dist/chunks/chunk-CQB4BJBR.js +0 -2
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
// Restricted mean survival time and adjusted contrasts.
|
|
2
|
+
// Written for rStats.js (no ported code), from oracle/survfit2-behaviour.md,
|
|
3
|
+
// Klein & Moeschberger (2003) §4.5, Uno et al. (2014), and Tian, Zhao & Wei (2014).
|
|
4
|
+
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
5
|
+
import { crossprod } from "../linalg/basic.js";
|
|
6
|
+
import { matMul } from "../linalg/ops.js";
|
|
7
|
+
import { solve } from "../linalg/solve.js";
|
|
8
|
+
import { reported } from "../internal/warnings.js";
|
|
9
|
+
import { wideSum, wideSumAdd, wideSumValue } from "../internal/summary.js";
|
|
10
|
+
import { glm } from "./glm.js";
|
|
11
|
+
import { lm } from "./lm.js";
|
|
12
|
+
import { survfit } from "./survival.js";
|
|
13
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
14
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
15
|
+
const RMST2_KEYS = ["tau", "covariates", "covariateNames", "confLevel"];
|
|
16
|
+
function pTwoSided(z) { return 2 * pnorm(-Math.abs(z)); }
|
|
17
|
+
function interval(estimate, se, z) { return [estimate - z * se, estimate + z * se]; }
|
|
18
|
+
function estimate(estimate, standardError, z) {
|
|
19
|
+
return { estimate, se: standardError, confInt: interval(estimate, standardError, z) };
|
|
20
|
+
}
|
|
21
|
+
function contrast(estimate, se, z, test) {
|
|
22
|
+
return { estimate, confInt: interval(estimate, se, z), pValue: pTwoSided(test) };
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Obtain the KM restricted mean and Greenwood standard error from the verified survfit implementation.
|
|
26
|
+
* The complementary area is accumulated from survfit's returned step curve to avoid tau - RMST cancellation.
|
|
27
|
+
*/
|
|
28
|
+
function armCurve(rows, tau) {
|
|
29
|
+
const fit = survfit(rows.map(r => r.time), rows.map(r => r.status), { rmean: tau });
|
|
30
|
+
const rmst = fit.rmean[0];
|
|
31
|
+
const se = fit.seRmean[0];
|
|
32
|
+
let previous = 0, survival = 1;
|
|
33
|
+
const lostArea = wideSum();
|
|
34
|
+
for (let i = 0; i < fit.time.length && fit.time[i] < tau; i++) {
|
|
35
|
+
const t = fit.time[i];
|
|
36
|
+
wideSumAdd(lostArea, (1 - survival) * (t - previous), fit.time.length + 1);
|
|
37
|
+
survival = fit.surv[i];
|
|
38
|
+
previous = t;
|
|
39
|
+
}
|
|
40
|
+
wideSumAdd(lostArea, (1 - survival) * (tau - previous), fit.time.length + 1);
|
|
41
|
+
const rmtl = wideSumValue(lostArea);
|
|
42
|
+
return { rmst: { estimate: rmst, se }, rmtl: { estimate: rmtl, se } };
|
|
43
|
+
}
|
|
44
|
+
function tableContrast(a, b, which, z) {
|
|
45
|
+
if (which === "difference") {
|
|
46
|
+
const d = a.estimate - b.estimate, se = Math.hypot(a.se, b.se);
|
|
47
|
+
return contrast(d, se, z, d / se);
|
|
48
|
+
}
|
|
49
|
+
const x = a.estimate, y = b.estimate;
|
|
50
|
+
if (x === 0 || y === 0) {
|
|
51
|
+
const value = x === 0 ? (y === 0 ? NaN : 0) : Infinity;
|
|
52
|
+
return { estimate: value, confInt: [NaN, NaN], pValue: NaN };
|
|
53
|
+
}
|
|
54
|
+
if (!(x > 0 && y > 0))
|
|
55
|
+
return { estimate: NaN, confInt: [NaN, NaN], pValue: NaN };
|
|
56
|
+
const ratio = x / y, logRatio = Math.log(ratio), se = Math.hypot(a.se / x, b.se / y);
|
|
57
|
+
return { estimate: ratio, confInt: [Math.exp(logRatio - z * se), Math.exp(logRatio + z * se)], pValue: pTwoSided(logRatio / se) };
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Right-continuous inverse censoring survival weights from the verified KM implementation.
|
|
61
|
+
*/
|
|
62
|
+
function censorWeights(rows) {
|
|
63
|
+
const weights = new Array(rows.length).fill(0);
|
|
64
|
+
for (const arm of [0, 1]) {
|
|
65
|
+
const indices = rows.flatMap((r, i) => r.arm === arm ? [i] : []);
|
|
66
|
+
const fit = survfit(indices.map(i => rows[i].time), indices.map(i => rows[i].status === 0 ? 1 : 0), { rmean: "none" });
|
|
67
|
+
for (const i of indices) {
|
|
68
|
+
const row = rows[i];
|
|
69
|
+
if (row.status === 0)
|
|
70
|
+
continue;
|
|
71
|
+
let g = 1;
|
|
72
|
+
for (let j = 0; j < fit.time.length && fit.time[j] <= row.time; j++)
|
|
73
|
+
g = fit.surv[j];
|
|
74
|
+
if (!(g > 0))
|
|
75
|
+
throw new Error("the censoring survival probability is zero");
|
|
76
|
+
weights[i] = 1 / g;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return weights;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Fit one specified estimating-equation model with validated lm/glm.
|
|
83
|
+
* Only the censoring-process correction in the subject-level B matrix is rmst2-specific.
|
|
84
|
+
*/
|
|
85
|
+
function adjustedFit(rows, tau, y, logLink, names, zCrit) {
|
|
86
|
+
const rawPredictors = rows.map(r => [r.arm, ...r.x]);
|
|
87
|
+
// Keep ordinary columns unchanged; only extreme magnitudes are divided by an exact power of two.
|
|
88
|
+
// The fit and sandwich are computed in these equivalent coordinates, then mapped back below.
|
|
89
|
+
const columnScales = rawPredictors[0].map((_, j) => {
|
|
90
|
+
const magnitude = rawPredictors.reduce((m, row) => Math.max(m, Math.abs(row[j])), 0);
|
|
91
|
+
if (magnitude === 0)
|
|
92
|
+
return 1;
|
|
93
|
+
const exponent = Math.floor(Math.log2(magnitude));
|
|
94
|
+
return exponent > 500 || exponent < -500 ? 2 ** exponent : 1;
|
|
95
|
+
});
|
|
96
|
+
const predictors = rawPredictors.map(row => row.map((v, j) => v / columnScales[j]));
|
|
97
|
+
const Z = rows.map((_, i) => [1, ...predictors[i]]);
|
|
98
|
+
const parameterScales = [1, ...columnScales];
|
|
99
|
+
const w = censorWeights(rows);
|
|
100
|
+
const fit = logLink
|
|
101
|
+
? glm(predictors, y, { family: "poisson", weights: w })
|
|
102
|
+
: lm(predictors, y, { weights: w });
|
|
103
|
+
if (logLink && !fit.converged) {
|
|
104
|
+
throw new Error("the adjusted RMST Poisson model did not converge");
|
|
105
|
+
}
|
|
106
|
+
const scaledCoef = fit.coefficients;
|
|
107
|
+
const coef = scaledCoef.map((v, j) => v / parameterScales[j]);
|
|
108
|
+
const mu = fit.fittedValues;
|
|
109
|
+
if (coef.some(v => !Number.isFinite(v)) || mu.some(v => !Number.isFinite(v))) {
|
|
110
|
+
throw new Error("the adjusted RMST model is singular or has non-finite fitted values");
|
|
111
|
+
}
|
|
112
|
+
const eps = Z.map((row, i) => row.map(v => w[i] * v * (y[i] - mu[i])));
|
|
113
|
+
const eta = eps.map(row => row.slice());
|
|
114
|
+
// B's extra influence term for the separately estimated censoring distribution, arm by arm.
|
|
115
|
+
for (const arm of [0, 1]) {
|
|
116
|
+
const indices = rows.flatMap((r, i) => r.arm === arm ? [i] : []);
|
|
117
|
+
const censorFit = survfit(indices.map(i => rows[i].time), indices.map(i => rows[i].status === 0 ? 1 : 0), { rmean: "none" });
|
|
118
|
+
for (let k = 0; k < censorFit.time.length; k++) {
|
|
119
|
+
const u = censorFit.time[k];
|
|
120
|
+
const dC = censorFit.nEvent[k];
|
|
121
|
+
if (!(u < tau) || dC === 0)
|
|
122
|
+
continue;
|
|
123
|
+
const pi = censorFit.nRisk[k];
|
|
124
|
+
if (!(pi > 0))
|
|
125
|
+
continue;
|
|
126
|
+
const q = new Array(Z[0].length).fill(0);
|
|
127
|
+
for (let j = 0; j < q.length; j++) {
|
|
128
|
+
const sum = wideSum();
|
|
129
|
+
for (const i of indices)
|
|
130
|
+
if (rows[i].time >= u)
|
|
131
|
+
wideSumAdd(sum, eps[i][j], indices.length);
|
|
132
|
+
q[j] = wideSumValue(sum);
|
|
133
|
+
}
|
|
134
|
+
const dLambda = dC / pi;
|
|
135
|
+
for (const i of indices) {
|
|
136
|
+
const row = rows[i];
|
|
137
|
+
const isCensor = row.time === u && row.status === 0;
|
|
138
|
+
const isAtRisk = row.time >= u;
|
|
139
|
+
for (let j = 0; j < q.length; j++) {
|
|
140
|
+
eta[i][j] += (q[j] / pi) * (Number(isCensor) - (isAtRisk ? dLambda : 0));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// A = sum Z_i Z_i' g_i (unweighted), B = sum eta_i eta_i'.
|
|
146
|
+
const derivativeRows = Z.map((row, i) => row.map(v => v * Math.sqrt(logLink ? mu[i] : 1)));
|
|
147
|
+
const A = crossprod(derivativeRows);
|
|
148
|
+
const B = crossprod(eta);
|
|
149
|
+
const Ainv = solve(A);
|
|
150
|
+
const scaledCov = matMul(matMul(Ainv, B), Ainv);
|
|
151
|
+
const cov = scaledCov.map((row, i) => row.map((v, j) => v / parameterScales[i] / parameterScales[j]));
|
|
152
|
+
const se = cov.map((row, i) => Math.sqrt(Math.max(0, row[i])));
|
|
153
|
+
const z = coef.map((v, i) => v / se[i]);
|
|
154
|
+
const pValue = z.map(pTwoSided);
|
|
155
|
+
const lower = coef.map((v, i) => v - zCrit * se[i]);
|
|
156
|
+
const upper = coef.map((v, i) => v + zCrit * se[i]);
|
|
157
|
+
const confInt = logLink
|
|
158
|
+
? [lower.map(Math.exp), upper.map(Math.exp)]
|
|
159
|
+
: [lower, upper];
|
|
160
|
+
return {
|
|
161
|
+
coef,
|
|
162
|
+
cov,
|
|
163
|
+
table: { names: ["intercept", "arm", ...names], estimate: coef, se, z, pValue, confInt },
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Restricted mean survival time (RMST), restricted mean time lost (RMTL), and their between-arm contrasts.
|
|
168
|
+
* Implements the unadjusted Kaplan-Meier estimators and Tian, Zhao & Wei's adjusted estimating equations.
|
|
169
|
+
* Equivalent to `survRM2::rmst2()` in R.
|
|
170
|
+
*
|
|
171
|
+
* @param time Follow-up times.
|
|
172
|
+
* @param status Event indicator (1 event, 0 censored; 1/2 coding is also accepted). Invalid values are omitted with a warning.
|
|
173
|
+
* @param arm Treatment indicator (0 or 1; booleans are also accepted).
|
|
174
|
+
* @param options Restriction time, covariates, optional matrix column names and confidence level.
|
|
175
|
+
* @returns Per-arm RMST/RMTL estimates and between-arm contrasts; adjusted contrasts and coefficient tables are added
|
|
176
|
+
* when covariates are supplied.
|
|
177
|
+
*
|
|
178
|
+
* Rows with missing time, status, arm, or covariates are omitted. Negative follow-up times, non-positive tau, tau below
|
|
179
|
+
* the first retained observation, and tau above its default upper bound are errors.
|
|
180
|
+
* @example
|
|
181
|
+
* ```ts
|
|
182
|
+
* const r = rmst2([1,2,3,4,5,6,1.5,2.5,3.5,4.5,7,8],
|
|
183
|
+
* [1,0,1,1,0,1,1,1,0,1,1,0], [1,1,1,1,1,1,0,0,0,0,0,0]);
|
|
184
|
+
* r.tau; // 8
|
|
185
|
+
* r.arm1?.rmst.estimate; // 4.125
|
|
186
|
+
* r.arm0?.rmst.estimate; // 5
|
|
187
|
+
* r.difference.estimate; // -0.875
|
|
188
|
+
* ```
|
|
189
|
+
* @category Survival analysis
|
|
190
|
+
*/
|
|
191
|
+
export function rmst2(time, status, arm, options = {}) {
|
|
192
|
+
checkOptions(options, RMST2_KEYS, "rmst2"); // generated: option-keys.mjs
|
|
193
|
+
if (time.length !== status.length || time.length !== arm.length)
|
|
194
|
+
throw new RangeError("'time', 'status' and 'arm' must have the same length");
|
|
195
|
+
if (options.tau !== undefined && typeof options.tau !== "number")
|
|
196
|
+
throw new TypeError("'tau' must be a number");
|
|
197
|
+
if (options.confLevel !== undefined && typeof options.confLevel !== "number")
|
|
198
|
+
throw new TypeError("'confLevel' must be a number");
|
|
199
|
+
if (options.covariateNames !== undefined && !Array.isArray(options.covariateNames))
|
|
200
|
+
throw new TypeError("'covariateNames' must be an array of strings");
|
|
201
|
+
const confLevel = options.confLevel ?? 0.95;
|
|
202
|
+
if (!(confLevel > 0 && confLevel < 1))
|
|
203
|
+
throw new RangeError("'confLevel' must be between 0 and 1");
|
|
204
|
+
// Normalize very large follow-up times by an exact power of two before integration.
|
|
205
|
+
// This keeps the RMST/RMTL ratios and their Wald statistics scale-invariant while
|
|
206
|
+
// avoiding loss of low-order bits in long interval sums.
|
|
207
|
+
const maxTimeMagnitude = time.reduce((m, t) => Number.isFinite(t) ? Math.max(m, Math.abs(t)) : m, 0);
|
|
208
|
+
const proposedTimeScale = maxTimeMagnitude > 2 ** 500 ? 2 ** Math.floor(Math.log2(maxTimeMagnitude)) : 1;
|
|
209
|
+
const scalePreservesInputs = time.every(t => !Number.isFinite(t) || t === 0 || t / proposedTimeScale !== 0) &&
|
|
210
|
+
(options.tau === undefined || options.tau === 0 || options.tau / proposedTimeScale !== 0);
|
|
211
|
+
const timeScale = scalePreservesInputs ? proposedTimeScale : 1;
|
|
212
|
+
const toWorkingTime = (t) => t / timeScale;
|
|
213
|
+
const raw = Array.from(status);
|
|
214
|
+
// Surv objects are constructed within each arm. A 1/2-coded arm can therefore coexist with a 0/1-coded arm;
|
|
215
|
+
// in a 1/2-coded arm, zero is an invalid status and is omitted (while it remains part of the raw tau rule).
|
|
216
|
+
const status12Arms = new Set();
|
|
217
|
+
for (let i = 0; i < raw.length; i++) {
|
|
218
|
+
const a = arm[i] === true ? 1 : arm[i] === false ? 0 : arm[i];
|
|
219
|
+
if ((a === 0 || a === 1) && raw[i] === 2)
|
|
220
|
+
status12Arms.add(a);
|
|
221
|
+
}
|
|
222
|
+
const firstCovariate = options.covariates?.[0];
|
|
223
|
+
const vectorCovariate = options.covariates !== undefined && typeof firstCovariate === "number";
|
|
224
|
+
if (options.covariates !== undefined && options.covariates.length > 0 && !vectorCovariate && !Array.isArray(firstCovariate)) {
|
|
225
|
+
throw new TypeError("'covariates' must be a numeric vector or a matrix of numeric rows");
|
|
226
|
+
}
|
|
227
|
+
const X = options.covariates === undefined ? undefined : (vectorCovariate
|
|
228
|
+
? options.covariates.map(v => [v])
|
|
229
|
+
: options.covariates.map(r => Array.from(r)));
|
|
230
|
+
if (X && X.length !== time.length)
|
|
231
|
+
throw new RangeError("'covariates' must have one row per observation");
|
|
232
|
+
if (X && X.some(row => row.length !== X[0].length))
|
|
233
|
+
throw new RangeError("'covariates' must have the same number of columns in every row");
|
|
234
|
+
if (X && X.some(row => row.some(v => typeof v !== "number")))
|
|
235
|
+
throw new TypeError("'covariates' must contain numeric values");
|
|
236
|
+
if (X && X.some(row => row.some(v => !Number.isFinite(v) && !Number.isNaN(v))))
|
|
237
|
+
throw new RangeError("'covariates' must be finite");
|
|
238
|
+
const rows = [];
|
|
239
|
+
const tauCandidates = [];
|
|
240
|
+
const extraArmTimes = [];
|
|
241
|
+
const warnings = [];
|
|
242
|
+
for (let i = 0; i < time.length; i++) {
|
|
243
|
+
if (time[i] == null || Number.isNaN(time[i]) || raw[i] == null || Number.isNaN(raw[i]) ||
|
|
244
|
+
arm[i] == null || Number.isNaN(arm[i])) {
|
|
245
|
+
throw new Error("missing value where TRUE/FALSE needed");
|
|
246
|
+
}
|
|
247
|
+
if (typeof time[i] !== "number")
|
|
248
|
+
throw new TypeError("'time' must contain numbers");
|
|
249
|
+
if (!Number.isFinite(time[i]))
|
|
250
|
+
throw new RangeError("'time' must be finite");
|
|
251
|
+
if (typeof arm[i] !== "number" && typeof arm[i] !== "boolean")
|
|
252
|
+
throw new TypeError("'arm' must contain numbers or booleans");
|
|
253
|
+
const a = arm[i] === true ? 1 : arm[i] === false ? 0 : arm[i];
|
|
254
|
+
// Additional arm levels are ignored only when their observations lie beyond tau,
|
|
255
|
+
// where they cannot contribute to either restricted curve.
|
|
256
|
+
if (a !== 0 && a !== 1) {
|
|
257
|
+
extraArmTimes.push(toWorkingTime(time[i]));
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (typeof raw[i] !== "number")
|
|
261
|
+
throw new TypeError("'status' must contain numbers");
|
|
262
|
+
const rawD = raw[i];
|
|
263
|
+
// The default-tau rule uses the original 0/1 status convention, independently of
|
|
264
|
+
// the per-arm Surv coding used for the Kaplan-Meier curves below.
|
|
265
|
+
const tauStatus = rawD === 1 ? 1 : 0;
|
|
266
|
+
const x = X ? X[i] : [];
|
|
267
|
+
if (x.some(v => !Number.isFinite(v)))
|
|
268
|
+
continue;
|
|
269
|
+
tauCandidates.push({ time: toWorkingTime(time[i]), status: tauStatus, arm: a, x, index: i });
|
|
270
|
+
let d = rawD;
|
|
271
|
+
if (status12Arms.has(a)) {
|
|
272
|
+
if (rawD === 2)
|
|
273
|
+
d = 1;
|
|
274
|
+
else if (rawD === 1)
|
|
275
|
+
d = 0;
|
|
276
|
+
else {
|
|
277
|
+
if (!warnings.includes("Invalid status value, converted to NA"))
|
|
278
|
+
warnings.push("Invalid status value, converted to NA");
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
else if (d !== 0 && d !== 1) {
|
|
283
|
+
if (!warnings.includes("Invalid status value, converted to NA"))
|
|
284
|
+
warnings.push("Invalid status value, converted to NA");
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
rows.push({ time: toWorkingTime(time[i]), status: d, arm: a, x, index: i });
|
|
288
|
+
}
|
|
289
|
+
if (tauCandidates.some(r => r.time < 0))
|
|
290
|
+
throw new Error("negative follow-up times are not supported");
|
|
291
|
+
if (!rows.some(r => r.arm === 0) || !rows.some(r => r.arm === 1))
|
|
292
|
+
throw new Error("both arms 0 and 1 are required");
|
|
293
|
+
const maxima = [0, 1].map(a => Math.max(...tauCandidates.filter(r => r.arm === a).map(r => r.time)));
|
|
294
|
+
const censored = [0, 1].map(a => { const m = maxima[a]; return tauCandidates.some(r => r.arm === a && r.time === m && r.status === 0); });
|
|
295
|
+
const tauMax = censored.some(Boolean) ? Math.min(...maxima.filter((_, i) => censored[i])) : Math.max(...maxima);
|
|
296
|
+
const tauDefault = options.tau === undefined;
|
|
297
|
+
const tau = options.tau === undefined ? tauMax : toWorkingTime(options.tau);
|
|
298
|
+
const tauOutput = options.tau === undefined ? tau * timeScale : options.tau;
|
|
299
|
+
if (extraArmTimes.some(t => t <= tau))
|
|
300
|
+
throw new RangeError("'arm' must contain only 0 and 1 through tau");
|
|
301
|
+
if (!(tau > 0))
|
|
302
|
+
throw new RangeError("'tau' must be greater than zero");
|
|
303
|
+
if (tau > tauMax)
|
|
304
|
+
throw new RangeError(`'tau' must be at most ${tauMax * timeScale}: the minimum of the largest times allowed by both arms`);
|
|
305
|
+
if (tau < Math.min(...tauCandidates.map(r => r.time)))
|
|
306
|
+
throw new RangeError("'tau' must not be below the first observed time");
|
|
307
|
+
const a2 = (1 - confLevel) / 2, z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - a2);
|
|
308
|
+
const arm1Rows = rows.filter(r => r.arm === 1), arm0Rows = rows.filter(r => r.arm === 0);
|
|
309
|
+
const c1Working = armCurve(arm1Rows, tau), c0Working = armCurve(arm0Rows, tau);
|
|
310
|
+
const scaleCurve = (curve) => ({ estimate: curve.estimate * timeScale, se: curve.se * timeScale });
|
|
311
|
+
const c1 = { rmst: scaleCurve(c1Working.rmst), rmtl: scaleCurve(c1Working.rmtl) };
|
|
312
|
+
const c0 = { rmst: scaleCurve(c0Working.rmst), rmtl: scaleCurve(c0Working.rmtl) };
|
|
313
|
+
const arm1Rmst = estimate(c1.rmst.estimate, c1.rmst.se, z), arm0Rmst = estimate(c0.rmst.estimate, c0.rmst.se, z);
|
|
314
|
+
const arm1Rmtl = { estimate: c1.rmtl.estimate, se: c1.rmtl.se,
|
|
315
|
+
confInt: [tauOutput - arm1Rmst.confInt[1], tauOutput - arm1Rmst.confInt[0]] };
|
|
316
|
+
const arm0Rmtl = { estimate: c0.rmtl.estimate, se: c0.rmtl.se,
|
|
317
|
+
confInt: [tauOutput - arm0Rmst.confInt[1], tauOutput - arm0Rmst.confInt[0]] };
|
|
318
|
+
const difference = tableContrast(c1.rmst, c0.rmst, "difference", z);
|
|
319
|
+
const ratio = tableContrast(c1.rmst, c0.rmst, "ratio", z);
|
|
320
|
+
const rmtlRatio = tableContrast(c1.rmtl, c0.rmtl, "rmtlRatio", z);
|
|
321
|
+
const result = { tau: tauOutput, tauDefault, confLevel, arm1: { rmst: arm1Rmst, rmtl: arm1Rmtl },
|
|
322
|
+
arm0: { rmst: arm0Rmst, rmtl: arm0Rmtl }, difference, ratio, rmtlRatio, warnings };
|
|
323
|
+
if (X) {
|
|
324
|
+
const names = options.covariateNames === undefined
|
|
325
|
+
? (vectorCovariate ? ["covariates"] : Array.from({ length: X[0].length }, () => ""))
|
|
326
|
+
: Array.from(options.covariateNames);
|
|
327
|
+
if (names.some(name => typeof name !== "string"))
|
|
328
|
+
throw new TypeError("'covariateNames' must contain strings");
|
|
329
|
+
if (names.length !== X[0].length)
|
|
330
|
+
throw new RangeError("'covariateNames' must have one name per covariate column");
|
|
331
|
+
const adjustedRows = rows.map(r => ({ ...r, time: Math.min(r.time, tau), status: r.time >= tau ? 1 : r.status }));
|
|
332
|
+
const yRmst = adjustedRows.map(r => r.time), yRmtl = adjustedRows.map(r => tau - r.time);
|
|
333
|
+
const fD = adjustedFit(adjustedRows, tau, yRmst, false, names, z);
|
|
334
|
+
const noRmst = !(c1.rmst.estimate > 0 && c0.rmst.estimate > 0), noRmtl = !(c1.rmtl.estimate > 0 && c0.rmtl.estimate > 0);
|
|
335
|
+
const fR = noRmst ? undefined : adjustedFit(adjustedRows, tau, yRmst, true, names, z);
|
|
336
|
+
const fL = noRmtl ? undefined : adjustedFit(adjustedRows, tau, yRmtl, true, names, z);
|
|
337
|
+
const get = (f, log) => {
|
|
338
|
+
const b = f.coef[1], se = Math.sqrt(Math.max(0, f.cov[1][1]));
|
|
339
|
+
return log ? { estimate: Math.exp(b), confInt: [Math.exp(b - z * se), Math.exp(b + z * se)], pValue: pTwoSided(b / se) } :
|
|
340
|
+
{ estimate: b * timeScale, confInt: [(b - z * se) * timeScale, (b + z * se) * timeScale], pValue: pTwoSided(b / se) };
|
|
341
|
+
};
|
|
342
|
+
const scaleLinearTable = (table) => ({
|
|
343
|
+
...table, estimate: table.estimate.map(v => v * timeScale), se: table.se.map(v => v * timeScale),
|
|
344
|
+
confInt: [table.confInt[0].map(v => v * timeScale), table.confInt[1].map(v => v * timeScale)],
|
|
345
|
+
});
|
|
346
|
+
const restoreLogIntercept = (table) => ({
|
|
347
|
+
...table, estimate: table.estimate.map((v, i) => i === 0 ? v + Math.log(timeScale) : v),
|
|
348
|
+
confInt: [table.confInt[0].map((v, i) => i === 0 ? v + Math.log(timeScale) : v),
|
|
349
|
+
table.confInt[1].map((v, i) => i === 0 ? v + Math.log(timeScale) : v)],
|
|
350
|
+
});
|
|
351
|
+
const unavailable = { names: ["intercept", "arm", ...names],
|
|
352
|
+
estimate: Array(fD.coef.length).fill(NaN), se: Array(fD.coef.length).fill(NaN),
|
|
353
|
+
z: Array(fD.coef.length).fill(NaN), pValue: Array(fD.coef.length).fill(NaN),
|
|
354
|
+
confInt: [Array(fD.coef.length).fill(NaN), Array(fD.coef.length).fill(NaN)] };
|
|
355
|
+
const undefinedRatio = { estimate: NaN, confInt: [NaN, NaN], pValue: NaN };
|
|
356
|
+
result.adjusted = { difference: get(fD, false), ratio: noRmst ? undefinedRatio : get(fR, true),
|
|
357
|
+
rmtlRatio: noRmtl ? undefinedRatio : get(fL, true) };
|
|
358
|
+
result.coefficients = { difference: scaleLinearTable(fD.table),
|
|
359
|
+
ratio: fR ? restoreLogIntercept(fR.table) : unavailable,
|
|
360
|
+
rmtlRatio: fL ? restoreLogIntercept(fL.table) : unavailable };
|
|
361
|
+
delete result.arm1;
|
|
362
|
+
delete result.arm0;
|
|
363
|
+
}
|
|
364
|
+
return reported("rmst2", result);
|
|
365
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { type GlmResult } from "./glm.js";
|
|
2
|
+
import { type LmResult } from "./lm.js";
|
|
3
|
+
/**
|
|
4
|
+
* A fit that {@link vcovHC}, {@link vcovCL}, {@link coeftest} and {@link coefci} take: the result of {@link lm} (from a
|
|
5
|
+
* matrix or a formula) or of {@link glm}.
|
|
6
|
+
*
|
|
7
|
+
* @category Linear models and ANOVA
|
|
8
|
+
*/
|
|
9
|
+
export type RobustFit = LmResult | GlmResult;
|
|
10
|
+
/**
|
|
11
|
+
* A covariance matrix of the coefficients that are not aliased, with their names: the result of {@link vcovHC} and
|
|
12
|
+
* {@link vcovCL}.
|
|
13
|
+
*
|
|
14
|
+
* @category Linear models and ANOVA
|
|
15
|
+
*/
|
|
16
|
+
export interface VcovResult {
|
|
17
|
+
/** The covariance matrix (k × k, k the number of coefficients that are not aliased), or the meat with `sandwich: false`. */
|
|
18
|
+
vcov: number[][];
|
|
19
|
+
/**
|
|
20
|
+
* The names of its rows and columns: the coefficient names of a formula fit, else `"(Intercept)"`, `"x1"`, `"x2"`,
|
|
21
|
+
* ... (aliased coefficients left out).
|
|
22
|
+
*/
|
|
23
|
+
names: string[];
|
|
24
|
+
/** R's warnings. */
|
|
25
|
+
warnings: string[];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Types of {@link vcovHC}.
|
|
29
|
+
*
|
|
30
|
+
* @category Linear models and ANOVA
|
|
31
|
+
*/
|
|
32
|
+
export type VcovHCType = "const" | "HC" | "HC0" | "HC1" | "HC2" | "HC3" | "HC4" | "HC4m" | "HC5";
|
|
33
|
+
/**
|
|
34
|
+
* Options for {@link vcovHC}.
|
|
35
|
+
*
|
|
36
|
+
* @category Linear models and ANOVA
|
|
37
|
+
*/
|
|
38
|
+
export interface VcovHCOptions {
|
|
39
|
+
/**
|
|
40
|
+
* The estimator: `"HC3"` (default), `"const"`, `"HC0"` (alias `"HC"`), `"HC1"`, `"HC2"`, `"HC4"`, `"HC4m"` or
|
|
41
|
+
* `"HC5"`. Unambiguous abbreviations are accepted, as R's `match.arg`.
|
|
42
|
+
*/
|
|
43
|
+
type?: VcovHCType;
|
|
44
|
+
/**
|
|
45
|
+
* The weights omega_i of the meat instead of the type's: an array of one value per row of non-zero weight (or one per
|
|
46
|
+
* row used, those of weight 0 then left out), or a function `(res, hat, df) => omega` of the residual factors, the
|
|
47
|
+
* hat values and n - k.
|
|
48
|
+
*/
|
|
49
|
+
omega?: readonly number[] | ((res: number[], hat: number[], df: number) => readonly number[]);
|
|
50
|
+
/** Return the sandwich (default `true`) or the meat only (`false`). */
|
|
51
|
+
sandwich?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Types of {@link vcovCL}.
|
|
55
|
+
*
|
|
56
|
+
* @category Linear models and ANOVA
|
|
57
|
+
*/
|
|
58
|
+
export type VcovCLType = "HC" | "HC0" | "HC1" | "HC2" | "HC3";
|
|
59
|
+
/**
|
|
60
|
+
* A cluster label: a number, a string or a boolean (`null`, `undefined` and NaN are missing, an error).
|
|
61
|
+
*
|
|
62
|
+
* @category Linear models and ANOVA
|
|
63
|
+
*/
|
|
64
|
+
export type ClusterLabel = number | string | boolean | null | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Options for {@link vcovCL}.
|
|
67
|
+
*
|
|
68
|
+
* @category Linear models and ANOVA
|
|
69
|
+
*/
|
|
70
|
+
export interface VcovCLOptions {
|
|
71
|
+
/**
|
|
72
|
+
* The clusters: one label per input row of the fit (the rows the fit dropped for a missing value are dropped here
|
|
73
|
+
* too), an array or a typed array, or for multi-way clustering an array of such arrays, one per clustering
|
|
74
|
+
* dimension. Default: every observation its own cluster.
|
|
75
|
+
*/
|
|
76
|
+
cluster?: readonly ClusterLabel[] | Float64Array | Int32Array | readonly (readonly ClusterLabel[] | Float64Array | Int32Array)[];
|
|
77
|
+
/** `"HC0"` (alias `"HC"`), `"HC1"`, `"HC2"` or `"HC3"`. Default `"HC1"` for an lm fit and `"HC0"` for a glm fit, as sandwich. */
|
|
78
|
+
type?: VcovCLType;
|
|
79
|
+
/** Multiply each clustering term by G / (G - 1), G its number of clusters. Default `true`. */
|
|
80
|
+
cadjust?: boolean;
|
|
81
|
+
/** Multi-way clustering: use clusters of one observation for the intersection of all dimensions. Default `false`. */
|
|
82
|
+
multi0?: boolean;
|
|
83
|
+
/** Set negative eigenvalues of the result to 0. Default `false`. */
|
|
84
|
+
fix?: boolean;
|
|
85
|
+
/** Return the sandwich (default `true`) or the meat only (`false`). */
|
|
86
|
+
sandwich?: boolean;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A covariance in units of powers of 2: V_ab = mant_ab 2^(exp_a + exp_b). Kept by the matrix returned (whose entries
|
|
90
|
+
* are those values rounded to double, Infinity or 0 where they are not representable), so that coeftest and coefci
|
|
91
|
+
* take the standard errors sqrt(mant_aa) 2^exp_a, which are representable where V is not (responses near 1e±300)
|
|
92
|
+
*/
|
|
93
|
+
export interface ScaledVcov {
|
|
94
|
+
mant: number[][];
|
|
95
|
+
exp: number[];
|
|
96
|
+
}
|
|
97
|
+
export declare const scaledVcovs: WeakMap<object, ScaledVcov>;
|
|
98
|
+
/**
|
|
99
|
+
* The standard error of row j of a covariance matrix kept in scaledVcovs: sqrt(mant_jj) 2^exp_j, or undefined if the
|
|
100
|
+
* matrix has no record or was changed since
|
|
101
|
+
*/
|
|
102
|
+
export declare function scaledStandardError(V: object, j: number, entry: number): number | undefined;
|
|
103
|
+
export declare function isGlm(fit: RobustFit): fit is GlmResult;
|
|
104
|
+
export declare function checkFit(fit: unknown): asserts fit is RobustFit;
|
|
105
|
+
export declare function coefficientNames(fit: RobustFit): string[];
|
|
106
|
+
/**
|
|
107
|
+
* The model-based covariance of the coefficients that are not aliased (R's vcov(fit) without the NA rows): sigma^2 A
|
|
108
|
+
* for an lm, the dispersion of summary.glm times A for a glm, with A = (X'WX)^-1 from the fit's QR factor. Formed as
|
|
109
|
+
* inv_ab d~ 2^(x - e_a - e_b - shift) with the dispersion d = d~ 2^x (x even), so that the standard errors are
|
|
110
|
+
* representable where sigma^2 or the covariance is not (the same bits as A d wherever that is in range)
|
|
111
|
+
*/
|
|
112
|
+
export declare function modelCovariance(fit: RobustFit): {
|
|
113
|
+
vcov: number[][];
|
|
114
|
+
names: string[];
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Heteroskedasticity-consistent covariance matrix of the coefficients of an `lm` or `glm` fit. Equivalent to R's
|
|
118
|
+
* `sandwich::vcovHC()`.
|
|
119
|
+
*
|
|
120
|
+
* The sandwich A (X' diag(omega) X) A (Zeileis 2006), A = (X'WX)^-1, with omega_i = res_i^2 (HC0, White 1980), times n
|
|
121
|
+
* / (n - k) (HC1), divided by 1 - h_i (HC2) or (1 - h_i)^2 (HC3, MacKinnon and White 1985), by (1 - h_i)^delta_i
|
|
122
|
+
* (HC4, Cribari-Neto 2004; HC4m, Cribari-Neto and da Silva 2011) or by its square root (HC5, Cribari-Neto et al.
|
|
123
|
+
* 2007), with HC4m's gamma = (1, 1.5) and HC5's k = 0.7 fixed as in sandwich; res_i is w_i e_i for an lm and W_i z_i /
|
|
124
|
+
* phi_s for a glm (working weights and residuals). `"const"` is the model-based covariance of the fit (R's `vcov(fit)`:
|
|
125
|
+
* sigma^2 A, or the dispersion times A for a glm); sandwich's `"const"` equals it only for an unweighted lm.
|
|
126
|
+
*
|
|
127
|
+
* Rows of prior weight 0 are left out (R counts them in n and returns different values); a hat value of 1 gives R's
|
|
128
|
+
* warning, and with HC2 to HC5, whose value is then undefined (R's NaN), an error, as is HC1 with as many
|
|
129
|
+
* observations as coefficients. Aliased coefficients are left out of the matrix. Data far from 1 (weights, responses)
|
|
130
|
+
* are handled in units of powers of 2: entries that are not representable are Infinity or 0, and {@link coeftest}
|
|
131
|
+
* still gives their standard errors, from a record kept with the matrix object returned (a copy of the matrix loses it:
|
|
132
|
+
* pass the result or its original matrix). See docs/differences-from-r.md.
|
|
133
|
+
*
|
|
134
|
+
* @param fit The result of {@link lm} or {@link glm}.
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* ```ts
|
|
138
|
+
* const fit = lm([1, 2, 3, 4, 5, 6], [1.1, 2.3, 2.8, 4.5, 4.9, 6.4]);
|
|
139
|
+
* vcovHC(fit).vcov; // [[0.043766, -0.01134], [-0.01134, 0.0045125]] (HC3)
|
|
140
|
+
* vcovHC(fit, { type: "HC0" }).names; // ["(Intercept)", "x1"]
|
|
141
|
+
* ```
|
|
142
|
+
*
|
|
143
|
+
* @category Linear models and ANOVA
|
|
144
|
+
*/
|
|
145
|
+
export declare function vcovHC(fit: RobustFit, options?: VcovHCOptions): VcovResult;
|
|
146
|
+
/**
|
|
147
|
+
* Clustered covariance matrix of the coefficients of an `lm` or `glm` fit. Equivalent to R's
|
|
148
|
+
* `sandwich::vcovCL()`.
|
|
149
|
+
*
|
|
150
|
+
* The meat sums the estimating functions within each cluster (Zeileis, Köll and Graham 2020), times G / (G - 1) with
|
|
151
|
+
* `cadjust`; HC1 multiplies by (n - 1) / (n - k). Several clustering dimensions are combined by inclusion and exclusion
|
|
152
|
+
* over all their intersections, each term with its own G (Cameron, Gelbach and Miller 2011); `multi0` uses clusters of
|
|
153
|
+
* one observation for the full intersection. HC2 and HC3 adjust each cluster's residuals by (I - H_gg)^-1/2 or
|
|
154
|
+
* (I - H_gg)^-1 in the symmetric form of Bell and McCaffrey (2002) (for HC3 the leave-one-cluster-out jackknife),
|
|
155
|
+
* which is sandwich's for an unweighted lm; sandwich transposes the adjustment for a weighted lm or a glm. A singular
|
|
156
|
+
* block (cluster fixed effects) is an error. `fix` sets negative eigenvalues to 0.
|
|
157
|
+
*
|
|
158
|
+
* The default type is HC1 for an lm and HC0 for a glm, as sandwich. Without `cluster` each observation is its own
|
|
159
|
+
* cluster. G is the number of distinct labels among the rows used (labels are compared as text, numbers with 15
|
|
160
|
+
* significant digits as R's `as.character`: 1 and 1 + 2^-52, or 0.1 + 0.2 and 0.3, are one label); intersections of
|
|
161
|
+
* dimensions are tuples of labels; at least two clusters are needed. Rows of prior weight 0 are left out. HC1 needs
|
|
162
|
+
* more observations than coefficients. Data far from 1 as {@link vcovHC} (the same record of the units, lost by a copy
|
|
163
|
+
* of the matrix); with `fix`, a negative eigenvalue is set to 0 in the units of the largest coefficient's variance, so
|
|
164
|
+
* that coefficients whose scale is about 2^537 or more below it then get variance 0. See docs/differences-from-r.md.
|
|
165
|
+
*
|
|
166
|
+
* @param fit The result of {@link lm} or {@link glm}.
|
|
167
|
+
*
|
|
168
|
+
* @example
|
|
169
|
+
* ```ts
|
|
170
|
+
* const fit = lm([1, 2, 3, 4, 5, 6, 7, 8], [1.2, 1.9, 3.2, 3.8, 5.3, 5.9, 7.1, 8.2]);
|
|
171
|
+
* vcovCL(fit, { cluster: ["a", "a", "b", "b", "c", "c", "d", "d"] }).vcov;
|
|
172
|
+
* // [[0.002257, -0.00053463], [-0.00053463, 0.00016363]] (HC1)
|
|
173
|
+
* ```
|
|
174
|
+
*
|
|
175
|
+
* @category Linear models and ANOVA
|
|
176
|
+
*/
|
|
177
|
+
export declare function vcovCL(fit: RobustFit, options?: VcovCLOptions): VcovResult;
|