@numero-uno-jpn/rstats 1.16.0 → 1.18.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 +34 -0
- package/README.ja.md +6 -6
- package/README.md +6 -6
- package/dist/causal/mediationProcedures.js +18 -1
- package/dist/causal/moderation.js +11 -2
- package/dist/causal.js +2 -2
- package/dist/chunks/{chunk-J74CELYL.js → chunk-2JB7F646.js} +2 -2
- package/dist/chunks/{chunk-K23MXTLC.js → chunk-3JFRDXN7.js} +2 -2
- package/dist/chunks/chunk-53WQDB3C.js +2 -0
- package/dist/chunks/{chunk-DP6TE35N.js → chunk-5CTWYFMB.js} +2 -2
- package/dist/chunks/chunk-6I23C2YJ.js +2 -0
- package/dist/chunks/{chunk-57BGTHS7.js → chunk-CTZUYKVL.js} +2 -2
- package/dist/chunks/{chunk-UMXY4R4G.js → chunk-EC77KAAM.js} +2 -2
- package/dist/chunks/{chunk-37YHUVXL.js → chunk-FLFNMSHI.js} +2 -2
- package/dist/chunks/{chunk-FCE6N6PI.js → chunk-GEHMND3C.js} +2 -2
- package/dist/chunks/{chunk-W5D6CIZM.js → chunk-GIK34P23.js} +2 -2
- package/dist/chunks/chunk-H6Z7JVSD.js +2 -0
- package/dist/chunks/{chunk-HOH5KGSU.js → chunk-HG4LJBNV.js} +2 -2
- package/dist/chunks/chunk-HGAEVPVS.js +2 -0
- package/dist/chunks/{chunk-ISOLPXQV.js → chunk-HMLYEFQN.js} +2 -2
- package/dist/chunks/chunk-HRRCC2BD.js +2 -0
- package/dist/chunks/chunk-IBHMM2SL.js +2 -0
- package/dist/chunks/chunk-ICDW3I2F.js +2 -0
- package/dist/chunks/{chunk-6DP2U23T.js → chunk-IKMW63BE.js} +2 -2
- package/dist/chunks/{chunk-KSN6A4OK.js → chunk-IOJVFYHW.js} +2 -2
- package/dist/chunks/chunk-IW4S634O.js +2 -0
- package/dist/chunks/{chunk-ZZ6KYMBW.js → chunk-JF4PXFJE.js} +2 -2
- package/dist/chunks/{chunk-NQWFURFV.js → chunk-JPWYGTUN.js} +2 -2
- package/dist/chunks/{chunk-XMA2NWYX.js → chunk-KJMLQHCY.js} +1 -1
- package/dist/chunks/chunk-KVJBCT3D.js +2 -0
- package/dist/chunks/chunk-LCIX76FR.js +2 -0
- package/dist/chunks/chunk-LY5XGFPU.js +2 -0
- package/dist/chunks/{chunk-JYE3T7FS.js → chunk-MKZH65DK.js} +2 -2
- package/dist/chunks/{chunk-B5QE2FDM.js → chunk-MVPHISOV.js} +1 -1
- package/dist/chunks/chunk-MXZ64QME.js +2 -0
- package/dist/chunks/{chunk-XAMWBGTP.js → chunk-N7BUE54L.js} +2 -2
- package/dist/chunks/{chunk-244M5C2B.js → chunk-NDZVVNBB.js} +2 -2
- package/dist/chunks/{chunk-AC22FPFB.js → chunk-NOTJ45G3.js} +2 -2
- package/dist/chunks/{chunk-MNPZUMPL.js → chunk-QUD3374N.js} +2 -2
- package/dist/chunks/{chunk-AIII5VRA.js → chunk-RXYZQ3UX.js} +2 -2
- package/dist/chunks/{chunk-LHMG6Q5C.js → chunk-SCFFHEDZ.js} +2 -2
- package/dist/chunks/{chunk-BHNDCNWM.js → chunk-V6FMGGUV.js} +2 -2
- package/dist/chunks/{chunk-FHHI3PYN.js → chunk-VATAUY7N.js} +2 -2
- package/dist/chunks/chunk-W5M3R4NH.js +2 -0
- package/dist/chunks/{chunk-H6WBOIFZ.js → chunk-WYVUCQO3.js} +1 -1
- package/dist/chunks/{chunk-7MFMRNMT.js → chunk-XQCHC3SH.js} +1 -1
- package/dist/chunks/{chunk-IPMC3VOC.js → chunk-XUMVTGMM.js} +2 -2
- package/dist/chunks/{chunk-6MHLWTBF.js → chunk-YXMHWS5R.js} +2 -2
- package/dist/chunks/{chunk-K5IP4ZJ5.js → chunk-Z33Q545U.js} +2 -2
- package/dist/descriptive/qcc.d.ts +320 -0
- package/dist/descriptive/qcc.js +524 -0
- package/dist/descriptive/qccTools.d.ts +301 -0
- package/dist/descriptive/qccTools.js +390 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +2 -0
- package/dist/entries/descriptive.js +2 -0
- package/dist/entries/regression.d.ts +4 -0
- package/dist/entries/regression.js +8 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/betareg.d.ts +278 -0
- package/dist/models/betareg.js +600 -0
- package/dist/models/bradleyterry.d.ts +188 -0
- package/dist/models/bradleyterry.js +533 -0
- package/dist/models/loglin.d.ts +186 -0
- package/dist/models/loglin.js +349 -0
- package/dist/models/survreg.d.ts +48 -0
- package/dist/models/survreg.js +29 -6
- package/dist/models/tobit.d.ts +132 -0
- package/dist/models/tobit.js +183 -0
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -3
- package/dist/rstats.js +17 -17
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-3L333CTJ.js +0 -2
- package/dist/chunks/chunk-3RO5FWJ5.js +0 -2
- package/dist/chunks/chunk-3VKN6K3P.js +0 -2
- package/dist/chunks/chunk-7IU5OE5I.js +0 -2
- package/dist/chunks/chunk-GKDA5W53.js +0 -2
- package/dist/chunks/chunk-IVJTWTGV.js +0 -2
- package/dist/chunks/chunk-NCVEJDRI.js +0 -2
- package/dist/chunks/chunk-P3Q6IJMR.js +0 -2
- package/dist/chunks/chunk-PIWXBWMD.js +0 -2
- package/dist/chunks/chunk-QBY63DGM.js +0 -2
- package/dist/chunks/chunk-RV4SUKXV.js +0 -2
- package/dist/chunks/chunk-SALMA4XX.js +0 -2
- package/dist/chunks/chunk-ZTZX2UYP.js +0 -2
package/dist/models/survreg.js
CHANGED
|
@@ -12,12 +12,15 @@ import { midpoint } from "../internal/extremes.js";
|
|
|
12
12
|
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
13
13
|
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
14
14
|
const SURVREG_KEYS = /* @__PURE__ */ new Set([
|
|
15
|
-
"type", "time2", "dist", "weights", "offset", "strata", "scale", "init", "df", "
|
|
15
|
+
"type", "time2", "dist", "weights", "offset", "strata", "scale", "init", "df", "parms", "control", "intercept",
|
|
16
|
+
"confLevel",
|
|
16
17
|
]);
|
|
17
18
|
const SURVREG_CONTROL_KEYS = ["maxiter", "relTolerance", "tolerChol"];
|
|
18
19
|
const SURVREG_PREDICT_KEYS = ["type", "p", "newX", "newStrata", "newOffset", "seFit"];
|
|
19
20
|
const SURVREG_RESIDUALS_KEYS = ["type", "weighted"];
|
|
20
21
|
const survregNumericState = new WeakMap();
|
|
22
|
+
/** The covariance in the fit's scaled coordinates (coefficient j times 2^xExponent[j]), for statistics of covariates far from 1 in size */
|
|
23
|
+
export function survregScaledState(fit) { return survregNumericState.get(fit); }
|
|
21
24
|
const LOG2PI = Math.log(2 * Math.PI);
|
|
22
25
|
const safelyNumber = (x) => Number(x);
|
|
23
26
|
const log1mexp = (x) => x < -Math.LN2 ? Math.log1p(-Math.exp(x)) : Math.log(-Math.expm1(x));
|
|
@@ -426,7 +429,7 @@ function fitCore(X, y, lo, hi, status, weights, offset, strata, k, d, nu, fixed,
|
|
|
426
429
|
export function survreg(time, event, x = [], options = {}) {
|
|
427
430
|
checkOptions(options, SURVREG_KEYS, "survreg"); // generated: option-keys.mjs
|
|
428
431
|
checkOptions(nestedOptions(options, "control"), SURVREG_CONTROL_KEYS, "survreg", "control"); // generated: option-keys.mjs
|
|
429
|
-
const type = options.type ?? "right", d = options.dist ?? "weibull", nu = options.df ?? 4, intercept = options.intercept ?? true;
|
|
432
|
+
const type = options.type ?? "right", d = options.dist ?? "weibull", nu = options.df ?? options.parms ?? 4, intercept = options.intercept ?? true;
|
|
430
433
|
const n0 = time.length, events = event === undefined ? Array(n0).fill(1) : Array.from(event, Number);
|
|
431
434
|
if (events.length !== n0 || x.length !== 0 && x.length !== n0)
|
|
432
435
|
throw new RangeError("variable lengths differ");
|
|
@@ -444,7 +447,9 @@ export function survreg(time, event, x = [], options = {}) {
|
|
|
444
447
|
throw new RangeError("Invalid scale value");
|
|
445
448
|
if (d === "t" && (!(nu >= 3) || !Number.isFinite(nu)))
|
|
446
449
|
throw new RangeError("Degrees of freedom must be >=3");
|
|
447
|
-
if (
|
|
450
|
+
if (options.df !== undefined && options.parms !== undefined)
|
|
451
|
+
throw new RangeError("give the degrees of freedom of the t distribution as 'df' or as 'parms', not both");
|
|
452
|
+
if (d !== "t" && (options.df !== undefined || options.parms !== undefined))
|
|
448
453
|
throw new RangeError("Extreme value distribution has no optional parameters");
|
|
449
454
|
const logTime = ["weibull", "exponential", "rayleigh", "loggaussian", "lognormal", "loglogistic"].includes(d);
|
|
450
455
|
const fixed0 = options.scale !== undefined && options.scale > 0 ? options.scale : undefined;
|
|
@@ -652,11 +657,29 @@ export function survreg(time, event, x = [], options = {}) {
|
|
|
652
657
|
}
|
|
653
658
|
catch { }
|
|
654
659
|
}
|
|
655
|
-
|
|
660
|
+
let model = isNull ? nullFit : fitCore(X, yy, lo, hi, st, ww, oo, sid, k, d, nu, fixed, start, maxiter, tol, control.tolerChol ?? 1e-10);
|
|
661
|
+
// A covariate with a large common value (x + 1e8) is collinear with the intercept to the Cholesky tolerance, though
|
|
662
|
+
// R's survreg fits it (experiments/qccbt118-old-extreme.R): when a coefficient comes out aliased, fit again with the
|
|
663
|
+
// covariates centred and take the intercept and the covariance back exactly (b0 = b0c - sum c_j b_j, V = T Vc T').
|
|
664
|
+
// Ordinary fits are not refitted, so their iterations stay R's.
|
|
665
|
+
if (!isNull && intercept && p > 1 && model.z.slice(1, p).some(Number.isNaN)) {
|
|
666
|
+
const c = Array.from({ length: p }, (_, j) => j === 0 ? 0 : X.reduce((s, r) => s + r[j], 0) / X.length);
|
|
667
|
+
const Xc = X.map(r => r.map((v, j) => v - c[j])), startC = start.slice();
|
|
668
|
+
startC[0] = start[0] + c.reduce((s, cj, j) => s + cj * start[j], 0);
|
|
669
|
+
const refit = fitCore(Xc, yy, lo, hi, st, ww, oo, sid, k, d, nu, fixed, startC, maxiter, tol, control.tolerChol ?? 1e-10);
|
|
670
|
+
if (!refit.z.slice(0, p).some(Number.isNaN)) {
|
|
671
|
+
const q2 = refit.b.length, T = Array.from({ length: q2 }, (_, i) => Array.from({ length: q2 }, (_, j) => i === j ? 1 : i === 0 && j > 0 && j < p ? -c[j] : 0));
|
|
672
|
+
const b = matVec(T, refit.b), V = T.map(r => T.map(t => dot(r, matVec(refit.V, t))));
|
|
673
|
+
model = { ...refit, b, V, VScaled: V.map(r => r.slice()), xExponent: Array(p).fill(0), z: V.map((r, j) => r[j] > 0 ? b[j] / Math.sqrt(r[j]) : NaN) };
|
|
674
|
+
}
|
|
675
|
+
}
|
|
656
676
|
const jac = logTime ? rows.reduce((s, orig, j) => s + (st[j] === 1 ? ww[j] * Math.log(time[orig]) : 0), 0) * -1 : 0;
|
|
657
677
|
const varmat = model.V.map(r => r.slice());
|
|
658
678
|
const coefs = model.b.slice(0, p).map((v, j) => Number.isNaN(model.z[j]) ? NaN : v);
|
|
659
|
-
|
|
679
|
+
// standard errors from the scaled covariance: for a covariate near 1e+-300 its variance (1e-+600) is not a double, the
|
|
680
|
+
// standard error is
|
|
681
|
+
const seOf = (j) => { const v = model.VScaled[j]?.[j] ?? 0; return v === 0 ? 0 : ldexpWide(Math.sqrt(Math.max(0, v)), j < p ? -model.xExponent[j] : 0); };
|
|
682
|
+
const ses = coefs.map((_, j) => seOf(j));
|
|
660
683
|
const zstat = coefs.map((_, j) => model.z[j]);
|
|
661
684
|
const pv = zstat.map(v => 2 * pnorm(-Math.abs(v)));
|
|
662
685
|
const scales = fixed !== undefined ? [fixed] : Array.from({ length: k }, (_, s) => Math.exp(model.b[p + s]));
|
|
@@ -665,7 +688,7 @@ export function survreg(time, event, x = [], options = {}) {
|
|
|
665
688
|
const lp = X.map((r, i) => dot(r, model.b.slice(0, p)) + oo[i]);
|
|
666
689
|
const chi = 2 * ((model.ll + jac) - (nullFit.ll + jac)), chiDf = p + (fixed === undefined ? k : 0) - (1 + (fixed === undefined ? k : 0));
|
|
667
690
|
const tableNames = [...coefs.map((_, j) => j === 0 && intercept ? "(Intercept)" : `x${j + (intercept ? 0 : 1)}`), ...(fixed === undefined ? (k === 1 ? ["Log(scale)"] : lev) : [])];
|
|
668
|
-
const values = [...coefs, ...(fixed === undefined ? model.b.slice(p) : [])], seAll = values.map((_, j) => (
|
|
691
|
+
const values = [...coefs, ...(fixed === undefined ? model.b.slice(p) : [])], seAll = values.map((_, j) => seOf(j)), zAll = values.map((_, j) => model.z[j]), pAll = zAll.map(v => 2 * pnorm(-Math.abs(v)));
|
|
669
692
|
const result = { coefficients: coefs, coefNames: tableNames.slice(0, p), scale: scales, table: { value: values, se: seAll, z: zAll, p: pAll }, strataLevels: lev.map(s => strataIn.find(v => String(v) === s)), hasOffset: options.offset !== undefined, icoef: fixed === undefined || rows.length === 1 ? nullFit.b.slice() : [nullFit.b[0], Math.log(fixed)], var: varmat, loglik: [nullFit.ll + jac, model.ll + jac], iter: model.iter, df: p + (fixed === undefined ? k : 0), idf: 1 + (fixed === undefined ? k : 0), dfResidual: rows.length - (p + (fixed === undefined ? k : 0)), n: rows.length, linearPredictors: lp, means, score: model.score.slice(), tableRowNames: tableNames, value: values, se: seAll, z: zAll, p: pAll, chi, chiDf, chiP: pchisq(chi, chiDf, { lowerTail: false }), dist: d, distributionDf: nu, parms: nu, intercept, x: X, offset: oo, rows, weights: ww, strata: sid, y: yy, lower: lo, upper: hi, status: st, type, warnings: [...dataWarnings, ...(model.warn || nullFit.warn ? ["Ran out of iterations and did not converge"] : []), ...(d === "exponential" && options.scale !== undefined && options.scale > 0 ? ["Exponential has a fixed scale, user specified value ignored"] : [])] };
|
|
670
693
|
survregNumericState.set(result, { V: model.VScaled, xExponent: model.xExponent });
|
|
671
694
|
return reported("survreg", result);
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { type DesignContrast } from "./modelMatrix.js";
|
|
2
|
+
import type { DataFrame } from "./modelFrame.js";
|
|
3
|
+
import { type SurvregDistribution, type SurvregResult, type SurvregControl } from "./survreg.js";
|
|
4
|
+
import type { Sample } from "../htest/types.js";
|
|
5
|
+
/**
|
|
6
|
+
* Options for {@link tobit}.
|
|
7
|
+
* @category Regression
|
|
8
|
+
*/
|
|
9
|
+
export interface TobitOptions {
|
|
10
|
+
/** Left limit: responses at or below it are left censored at it (default 0; `-Infinity` for none). */
|
|
11
|
+
left?: number;
|
|
12
|
+
/** Right limit: responses at or above it are right censored at it (default `Infinity`, none). */
|
|
13
|
+
right?: number;
|
|
14
|
+
/**
|
|
15
|
+
* The error distribution (survreg's): `"gaussian"` (default, the classical tobit model), `"logistic"`, `"t"`,
|
|
16
|
+
* `"extreme"`, or one for positive responses (`"weibull"`, `"exponential"`, `"rayleigh"`, `"lognormal"` /
|
|
17
|
+
* `"loggaussian"`, `"loglogistic"`), where the limits are on the scale of the response.
|
|
18
|
+
*/
|
|
19
|
+
dist?: SurvregDistribution;
|
|
20
|
+
/** Degrees of freedom of the t distribution (default 4, at least 3); `parms` is the same (give one). */
|
|
21
|
+
df?: number;
|
|
22
|
+
/** R's name for `df` (tobit and survreg take the degrees of freedom of the t distribution as `parms`). */
|
|
23
|
+
parms?: number;
|
|
24
|
+
/** Case weights, one per row of `data` (positive), or the name of a column of `data`. */
|
|
25
|
+
weights?: Sample | string;
|
|
26
|
+
/** A contrast per factor of the formula (default treatment contrasts). */
|
|
27
|
+
contrasts?: Record<string, DesignContrast>;
|
|
28
|
+
/** Iteration control, as {@link survreg}'s. */
|
|
29
|
+
control?: SurvregControl;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Result of {@link tobit}: {@link survreg}'s result with the coefficients named after the formula's terms, and the
|
|
33
|
+
* censoring.
|
|
34
|
+
* @category Regression
|
|
35
|
+
*/
|
|
36
|
+
export interface TobitResult extends SurvregResult {
|
|
37
|
+
/** The formula. */
|
|
38
|
+
formula: string;
|
|
39
|
+
/** The left limit used. */
|
|
40
|
+
left: number;
|
|
41
|
+
/** The right limit used. */
|
|
42
|
+
right: number;
|
|
43
|
+
/** Observations: total, left censored, uncensored, right censored. */
|
|
44
|
+
counts: TobitCounts;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The censoring counts of a {@link tobit} fit.
|
|
48
|
+
* @category Regression
|
|
49
|
+
*/
|
|
50
|
+
export interface TobitCounts {
|
|
51
|
+
/** Observations used. */
|
|
52
|
+
total: number;
|
|
53
|
+
/** Left censored (at or below the left limit). */
|
|
54
|
+
left: number;
|
|
55
|
+
/** Uncensored. */
|
|
56
|
+
uncensored: number;
|
|
57
|
+
/** Right censored (at or above the right limit). */
|
|
58
|
+
right: number;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Tobit regression: a linear model for a response censored at a left and/or right limit, fitted by maximum likelihood
|
|
62
|
+
* with {@link survreg} on the response clipped to [left, right]. Equivalent to R's `AER::tobit()`.
|
|
63
|
+
*
|
|
64
|
+
* A response at or below `left` is left censored at `left`, at or above `right` right censored at `right`. The
|
|
65
|
+
* classical tobit model is the default (left censoring at 0, gaussian errors). `loglik` holds the log-likelihoods of
|
|
66
|
+
* the intercept-only model and of the model (McFadden's R² is `1 - loglik[1] / loglik[0]`), and `chi`, `chiDf`, `chiP`
|
|
67
|
+
* their likelihood-ratio test.
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* const fit = tobit("y ~ x", { y: [0, 0, 1.2, 0.4, 2.5, 0, 3.1, 1.8], x: [1, 2, 3, 2, 5, 1, 6, 4] });
|
|
71
|
+
* fit.counts; // { total: 8, left: 3, uncensored: 5, right: 0 }
|
|
72
|
+
* ```
|
|
73
|
+
* @category Regression
|
|
74
|
+
*/
|
|
75
|
+
export declare function tobit(formula: string, data: DataFrame, options?: TobitOptions): TobitResult;
|
|
76
|
+
/**
|
|
77
|
+
* Result of {@link tobitSummary}.
|
|
78
|
+
* @category Regression
|
|
79
|
+
*/
|
|
80
|
+
export interface TobitSummaryResult {
|
|
81
|
+
/** Row names of the table: the coefficients, then `Log(scale)` (when the scale is estimated). */
|
|
82
|
+
names: string[];
|
|
83
|
+
/** Estimates. */
|
|
84
|
+
estimate: number[];
|
|
85
|
+
/** Standard errors. */
|
|
86
|
+
se: number[];
|
|
87
|
+
/** Wald z statistics. */
|
|
88
|
+
z: number[];
|
|
89
|
+
/** Two-sided p-values. */
|
|
90
|
+
p: number[];
|
|
91
|
+
/** The scale. */
|
|
92
|
+
scale: number;
|
|
93
|
+
/** Log-likelihood of the model. */
|
|
94
|
+
loglik: number;
|
|
95
|
+
/** Its degrees of freedom (coefficients and scale). */
|
|
96
|
+
df: number;
|
|
97
|
+
/** Observations: total, left censored, uncensored, right censored. */
|
|
98
|
+
counts: TobitCounts;
|
|
99
|
+
/**
|
|
100
|
+
* Wald test of the coefficients other than the intercept: `b' V⁻¹ b`, on the number of coefficients minus 1 degrees
|
|
101
|
+
* of freedom (as R; without an intercept R tests all coefficients on one degree of freedom too few). `null` for the
|
|
102
|
+
* intercept-only model.
|
|
103
|
+
*/
|
|
104
|
+
wald: TobitWald | null;
|
|
105
|
+
/** Iterations. */
|
|
106
|
+
iter: number;
|
|
107
|
+
/** The distribution. */
|
|
108
|
+
dist: SurvregDistribution;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The Wald test of {@link tobitSummary}.
|
|
112
|
+
* @category Regression
|
|
113
|
+
*/
|
|
114
|
+
export interface TobitWald {
|
|
115
|
+
/** `b' V⁻¹ b` over the coefficients other than the intercept. */
|
|
116
|
+
statistic: number;
|
|
117
|
+
/** Degrees of freedom: the number of coefficients minus 1. */
|
|
118
|
+
df: number;
|
|
119
|
+
/** Upper chi-squared tail probability. */
|
|
120
|
+
p: number;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Summary of a {@link tobit} fit: the Wald table with the scale and the Wald test of the regression. Equivalent to
|
|
124
|
+
* `AER::summary.tobit()` in R.
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* const fit = tobit("y ~ x", { y: [0, 0, 1.2, 0.4, 2.5, 0, 3.1, 1.8], x: [1, 2, 3, 2, 5, 1, 6, 4] });
|
|
128
|
+
* tobitSummary(fit).wald; // { statistic: 215.5, df: 1, p: 8.598e-49 }
|
|
129
|
+
* ```
|
|
130
|
+
* @category Regression
|
|
131
|
+
*/
|
|
132
|
+
export declare function tobitSummary(fit: TobitResult): TobitSummaryResult;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Tobit regression: AER's tobit, a formula entry point to survreg with the response censored at fixed limits.
|
|
2
|
+
// Behaviour: oracle/tobit-betareg-loglin-behaviour.md (clean room: from AER's documentation and the output of R; no
|
|
3
|
+
// source of R or of a package was read). Written for rStats.js.
|
|
4
|
+
import { pchisq } from "../distributions/chisq.js";
|
|
5
|
+
import { parseFormula } from "./formula.js";
|
|
6
|
+
import { design } from "./modelMatrix.js";
|
|
7
|
+
import { survreg, survregScaledState } from "./survreg.js";
|
|
8
|
+
import { ldexpWide } from "../internal/summary.js";
|
|
9
|
+
/** The inner survreg fit's scaled covariance and coefficients, for the Wald test of tobitSummary */
|
|
10
|
+
const waldState = new WeakMap();
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
13
|
+
const TOBIT_KEYS = ["left", "right", "dist", "df", "parms", "weights", "contrasts", "control"];
|
|
14
|
+
const TOBIT_CONTROL_KEYS = ["maxiter", "relTolerance", "tolerChol"];
|
|
15
|
+
/**
|
|
16
|
+
* Tobit regression: a linear model for a response censored at a left and/or right limit, fitted by maximum likelihood
|
|
17
|
+
* with {@link survreg} on the response clipped to [left, right]. Equivalent to R's `AER::tobit()`.
|
|
18
|
+
*
|
|
19
|
+
* A response at or below `left` is left censored at `left`, at or above `right` right censored at `right`. The
|
|
20
|
+
* classical tobit model is the default (left censoring at 0, gaussian errors). `loglik` holds the log-likelihoods of
|
|
21
|
+
* the intercept-only model and of the model (McFadden's R² is `1 - loglik[1] / loglik[0]`), and `chi`, `chiDf`, `chiP`
|
|
22
|
+
* their likelihood-ratio test.
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* const fit = tobit("y ~ x", { y: [0, 0, 1.2, 0.4, 2.5, 0, 3.1, 1.8], x: [1, 2, 3, 2, 5, 1, 6, 4] });
|
|
26
|
+
* fit.counts; // { total: 8, left: 3, uncensored: 5, right: 0 }
|
|
27
|
+
* ```
|
|
28
|
+
* @category Regression
|
|
29
|
+
*/
|
|
30
|
+
export function tobit(formula, data, options = {}) {
|
|
31
|
+
checkOptions(options, TOBIT_KEYS, "tobit"); // generated: option-keys.mjs
|
|
32
|
+
checkOptions(nestedOptions(options, "control"), TOBIT_CONTROL_KEYS, "tobit", "control"); // generated: option-keys.mjs
|
|
33
|
+
const left = options.left ?? 0, right = options.right ?? Infinity;
|
|
34
|
+
if (Number.isNaN(left) || Number.isNaN(right) || !(left < right))
|
|
35
|
+
throw new RangeError("all(left < right) is not TRUE");
|
|
36
|
+
const parsed = parseFormula(formula);
|
|
37
|
+
if (parsed.response === undefined)
|
|
38
|
+
throw new TypeError("the formula must have a response");
|
|
39
|
+
const designOptions = {};
|
|
40
|
+
if (options.weights !== undefined)
|
|
41
|
+
designOptions.weights = options.weights;
|
|
42
|
+
if (options.contrasts !== undefined)
|
|
43
|
+
designOptions.contrasts = options.contrasts;
|
|
44
|
+
const d = design(parsed, data, designOptions);
|
|
45
|
+
const y = d.y;
|
|
46
|
+
if (y === undefined)
|
|
47
|
+
throw new TypeError("the response must be numeric");
|
|
48
|
+
const intercept = d.terms.intercept;
|
|
49
|
+
const x = d.x.map((row) => (intercept ? row.slice(1) : row.slice()));
|
|
50
|
+
// the clipped response as interval2 data: left censored (-Inf, left], right censored [right, Inf), exact y
|
|
51
|
+
const lo = [], hi = [];
|
|
52
|
+
let nLeft = 0, nRight = 0;
|
|
53
|
+
for (const v of y) {
|
|
54
|
+
if (v <= left) {
|
|
55
|
+
lo.push(-Infinity);
|
|
56
|
+
hi.push(left);
|
|
57
|
+
nLeft++;
|
|
58
|
+
}
|
|
59
|
+
else if (v >= right) {
|
|
60
|
+
lo.push(right);
|
|
61
|
+
hi.push(Infinity);
|
|
62
|
+
nRight++;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
lo.push(v);
|
|
66
|
+
hi.push(v);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const sOptions = { type: "interval2", time2: hi, dist: options.dist ?? "gaussian", intercept };
|
|
70
|
+
if (options.df !== undefined)
|
|
71
|
+
sOptions.df = options.df;
|
|
72
|
+
if (options.parms !== undefined)
|
|
73
|
+
sOptions.parms = options.parms;
|
|
74
|
+
if (d.frame.weights !== undefined)
|
|
75
|
+
sOptions.weights = d.frame.weights;
|
|
76
|
+
if (options.control !== undefined)
|
|
77
|
+
sOptions.control = options.control;
|
|
78
|
+
// a location-scale distribution is fitted to the response divided by a power of 2 near its size, and the result
|
|
79
|
+
// scaled back exactly: survreg's iterations fail for responses near 1e-150 (R's do not; log 29). Not for responses
|
|
80
|
+
// of ordinary size, so that the iterations stay R's
|
|
81
|
+
const dist = sOptions.dist;
|
|
82
|
+
let top = 0;
|
|
83
|
+
for (const v of [...lo, ...hi])
|
|
84
|
+
if (Number.isFinite(v))
|
|
85
|
+
top = Math.max(top, Math.abs(v));
|
|
86
|
+
const e = ["gaussian", "logistic", "t", "extreme"].includes(dist) && top > 0 ? Math.floor(Math.log2(top)) : 0;
|
|
87
|
+
const scaled = Math.abs(e) > 30;
|
|
88
|
+
const sc = scaled ? 2 ** e : 1;
|
|
89
|
+
const inner = scaled ? survreg(lo.map((v) => v / sc), undefined, x, { ...sOptions, time2: hi.map((v) => v / sc) }) : survreg(lo, undefined, x, sOptions);
|
|
90
|
+
const fit = scaled ? unscale(inner, sc, lo, hi) : inner;
|
|
91
|
+
const names = d.colNames.slice();
|
|
92
|
+
const rowNames = [...names, ...fit.tableRowNames.slice(names.length)];
|
|
93
|
+
const result = {
|
|
94
|
+
...fit, coefNames: names, tableRowNames: rowNames, formula, left, right,
|
|
95
|
+
counts: { total: y.length, left: nLeft, uncensored: y.length - nLeft - nRight, right: nRight },
|
|
96
|
+
warnings: [...d.warnings, ...fit.warnings],
|
|
97
|
+
};
|
|
98
|
+
// the Wald statistic does not change with the scale of the response or of a covariate: tobitSummary computes it in
|
|
99
|
+
// the inner fit's scaled coordinates (a covariate near 1e+-300 has a variance outside the doubles)
|
|
100
|
+
const state = survregScaledState(inner);
|
|
101
|
+
if (state)
|
|
102
|
+
waldState.set(result, { V: state.V, exponent: state.xExponent, b: inner.coefficients.slice() });
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Summary of a {@link tobit} fit: the Wald table with the scale and the Wald test of the regression. Equivalent to
|
|
107
|
+
* `AER::summary.tobit()` in R.
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* const fit = tobit("y ~ x", { y: [0, 0, 1.2, 0.4, 2.5, 0, 3.1, 1.8], x: [1, 2, 3, 2, 5, 1, 6, 4] });
|
|
111
|
+
* tobitSummary(fit).wald; // { statistic: 215.5, df: 1, p: 8.598e-49 }
|
|
112
|
+
* ```
|
|
113
|
+
* @category Regression
|
|
114
|
+
*/
|
|
115
|
+
export function tobitSummary(fit) {
|
|
116
|
+
const p = fit.coefficients.length;
|
|
117
|
+
const keep = fit.coefNames.map((nm, j) => (nm === "(Intercept)" ? -1 : j)).filter((j) => j >= 0 && Number.isFinite(fit.coefficients[j]));
|
|
118
|
+
let wald = null;
|
|
119
|
+
if (keep.length > 0 && p > 1) {
|
|
120
|
+
const st = waldState.get(fit);
|
|
121
|
+
const V = st ? keep.map((a) => keep.map((b) => st.V[a][b])) : keep.map((a) => keep.map((b) => fit.var[a][b]));
|
|
122
|
+
const b = st ? keep.map((j) => ldexpWide(st.b[j], st.exponent[j])) : keep.map((j) => fit.coefficients[j]);
|
|
123
|
+
const sol = solveSymmetric(V, b);
|
|
124
|
+
const statistic = b.reduce((s, v, i) => s + v * sol[i], 0);
|
|
125
|
+
const df = p - 1;
|
|
126
|
+
wald = { statistic, df, p: pchisq(statistic, df, { lowerTail: false }) };
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
names: fit.tableRowNames.slice(), estimate: fit.value.slice(), se: fit.se.slice(), z: fit.z.slice(), p: fit.p.slice(),
|
|
130
|
+
scale: fit.scale[0], loglik: fit.loglik[1], df: fit.df, counts: { ...fit.counts }, wald, iter: fit.iter, dist: fit.dist,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// Solves V s = b for a symmetric positive definite V (Cholesky); NaN when V is not.
|
|
134
|
+
function solveSymmetric(V, b) {
|
|
135
|
+
const n = b.length, L = V.map(() => new Array(n).fill(0));
|
|
136
|
+
for (let i = 0; i < n; i++)
|
|
137
|
+
for (let j = 0; j <= i; j++) {
|
|
138
|
+
let s = V[i][j];
|
|
139
|
+
for (let k = 0; k < j; k++)
|
|
140
|
+
s -= L[i][k] * L[j][k];
|
|
141
|
+
if (i === j) {
|
|
142
|
+
if (!(s > 0))
|
|
143
|
+
return new Array(n).fill(NaN);
|
|
144
|
+
L[i][i] = Math.sqrt(s);
|
|
145
|
+
}
|
|
146
|
+
else
|
|
147
|
+
L[i][j] = s / L[j][j];
|
|
148
|
+
}
|
|
149
|
+
const z = new Array(n);
|
|
150
|
+
for (let i = 0; i < n; i++) {
|
|
151
|
+
let s = b[i];
|
|
152
|
+
for (let k = 0; k < i; k++)
|
|
153
|
+
s -= L[i][k] * z[k];
|
|
154
|
+
z[i] = s / L[i][i];
|
|
155
|
+
}
|
|
156
|
+
const s = new Array(n);
|
|
157
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
158
|
+
let t = z[i];
|
|
159
|
+
for (let k = i + 1; k < n; k++)
|
|
160
|
+
t -= L[k][i] * s[k];
|
|
161
|
+
s[i] = t / L[i][i];
|
|
162
|
+
}
|
|
163
|
+
return s;
|
|
164
|
+
}
|
|
165
|
+
// The fit of y / s taken back to y: coefficients, scales and standard errors times s, log scale plus log s, the
|
|
166
|
+
// log-likelihoods minus log s per exact observation (weighted), z and p unchanged.
|
|
167
|
+
function unscale(f, s, lo, hi) {
|
|
168
|
+
const p = f.coefficients.length, ls = Math.log(s);
|
|
169
|
+
let exact = 0;
|
|
170
|
+
f.rows.forEach((r, i) => { if (lo[r] === hi[r])
|
|
171
|
+
exact += f.weights[i]; });
|
|
172
|
+
const isCoef = (j) => j < p;
|
|
173
|
+
const value = f.value.map((v, j) => (isCoef(j) ? v * s : v + ls)), se = f.se.map((v, j) => (isCoef(j) ? v * s : v));
|
|
174
|
+
const icoef = f.icoef.map((v, j) => (j === 0 ? v * s : v + ls));
|
|
175
|
+
return {
|
|
176
|
+
...f, coefficients: f.coefficients.map((v) => v * s), scale: f.scale.map((v) => v * s),
|
|
177
|
+
var: f.var.map((row, a) => row.map((v, b) => v * (isCoef(a) ? s : 1) * (isCoef(b) ? s : 1))),
|
|
178
|
+
loglik: [f.loglik[0] - exact * ls, f.loglik[1] - exact * ls], icoef, value, se,
|
|
179
|
+
table: { value, se, z: f.z.slice(), p: f.p.slice() }, linearPredictors: f.linearPredictors.map((v) => v * s),
|
|
180
|
+
score: f.score.map((v, j) => (isCoef(j) ? v / s : v)), y: f.y.map((v) => v * s),
|
|
181
|
+
lower: f.lower.map((v) => v * s), upper: f.upper.map((v) => v * s),
|
|
182
|
+
};
|
|
183
|
+
}
|