@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.
Files changed (89) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.ja.md +28 -11
  3. package/README.md +27 -10
  4. package/dist/chunks/{chunk-RRO4LMCB.js → chunk-27VFB3SA.js} +2 -2
  5. package/dist/chunks/{chunk-BKV3FINA.js → chunk-56GFP4UU.js} +2 -2
  6. package/dist/chunks/{chunk-JWBSEL3V.js → chunk-5SW3L6J3.js} +2 -2
  7. package/dist/chunks/{chunk-NSU6U3ET.js → chunk-6FZAJQ4H.js} +2 -2
  8. package/dist/chunks/{chunk-VERBXW6E.js → chunk-BQJFFGYP.js} +2 -2
  9. package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-F6Z3GLWA.js} +2 -2
  10. package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-GBSMRVUY.js} +2 -2
  11. package/dist/chunks/{chunk-7WG7X2UI.js → chunk-GEF2YRBV.js} +2 -2
  12. package/dist/chunks/{chunk-L23RSC2N.js → chunk-GIER5WMB.js} +2 -2
  13. package/dist/chunks/{chunk-IAWXF73N.js → chunk-GLGOV3A5.js} +2 -2
  14. package/dist/chunks/{chunk-F3EQLL4F.js → chunk-H72MW7YP.js} +2 -2
  15. package/dist/chunks/{chunk-T5DRIITM.js → chunk-HWB7XRX2.js} +2 -2
  16. package/dist/chunks/chunk-J72MLFUG.js +2 -0
  17. package/dist/chunks/{chunk-TNETWBF5.js → chunk-PZ66PUWC.js} +2 -2
  18. package/dist/chunks/{chunk-IMPRIQE5.js → chunk-RUZATICF.js} +1 -1
  19. package/dist/chunks/{chunk-BI7NYJWP.js → chunk-RY7CCWVU.js} +1 -1
  20. package/dist/chunks/{chunk-7INBXTVV.js → chunk-S2YCFUCA.js} +2 -2
  21. package/dist/chunks/chunk-SVS54D6Z.js +2 -0
  22. package/dist/chunks/{chunk-HBHMEPGY.js → chunk-TEHMTQNB.js} +3 -3
  23. package/dist/chunks/chunk-UMMCVF53.js +2 -0
  24. package/dist/chunks/{chunk-5SGTWSCB.js → chunk-UNP4HBPP.js} +2 -2
  25. package/dist/chunks/{chunk-A66M3ZEA.js → chunk-V2KVTAVV.js} +2 -2
  26. package/dist/chunks/{chunk-EEU7D4RU.js → chunk-WWJGCBWH.js} +1 -1
  27. package/dist/chunks/chunk-X7K6EF7S.js +2 -0
  28. package/dist/chunks/{chunk-73LNRWU3.js → chunk-YBOSCQF2.js} +1 -1
  29. package/dist/chunks/{chunk-6FZHTD5G.js → chunk-ZQSOMEIM.js} +2 -2
  30. package/dist/chunks/{chunk-4AOTAT3O.js → chunk-ZRFZ5UIB.js} +2 -2
  31. package/dist/descriptive.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/tests.d.ts +13 -0
  34. package/dist/entries/tests.js +13 -0
  35. package/dist/htest/agreement.d.ts +2 -2
  36. package/dist/htest/blandAltman.d.ts +100 -0
  37. package/dist/htest/blandAltman.js +159 -0
  38. package/dist/htest/diagnosticTests.d.ts +91 -0
  39. package/dist/htest/diagnosticTests.js +116 -0
  40. package/dist/htest/iccPsych.d.ts +106 -0
  41. package/dist/htest/iccPsych.js +332 -0
  42. package/dist/htest/ksTest.d.ts +1 -1
  43. package/dist/htest/mcreg.d.ts +209 -0
  44. package/dist/htest/mcreg.js +735 -0
  45. package/dist/htest/roc.d.ts +287 -0
  46. package/dist/htest/roc.js +635 -0
  47. package/dist/htest/rocTest.d.ts +139 -0
  48. package/dist/htest/rocTest.js +444 -0
  49. package/dist/htest/tTOST.d.ts +202 -0
  50. package/dist/htest/tTOST.js +558 -0
  51. package/dist/htest/trendTests.d.ts +1 -1
  52. package/dist/htest/trendTests.js +1 -1
  53. package/dist/internal/summary.js +5 -0
  54. package/dist/linalg/qr.d.ts +3 -0
  55. package/dist/linalg/qr.js +3 -0
  56. package/dist/linalg.js +2 -2
  57. package/dist/mixed.js +2 -2
  58. package/dist/models/coeftest.d.ts +139 -0
  59. package/dist/models/coeftest.js +237 -0
  60. package/dist/models/competingRisks.d.ts +188 -0
  61. package/dist/models/competingRisks.js +673 -0
  62. package/dist/models/coxZph.d.ts +67 -0
  63. package/dist/models/coxZph.js +479 -0
  64. package/dist/models/coxph.d.ts +107 -16
  65. package/dist/models/coxph.js +641 -72
  66. package/dist/models/glm.d.ts +11 -1
  67. package/dist/models/glm.js +19 -2
  68. package/dist/models/inputRows.d.ts +10 -0
  69. package/dist/models/inputRows.js +23 -0
  70. package/dist/models/lm.d.ts +8 -0
  71. package/dist/models/lm.js +14 -2
  72. package/dist/models/rmst2.d.ts +126 -0
  73. package/dist/models/rmst2.js +365 -0
  74. package/dist/models/sandwich.d.ts +177 -0
  75. package/dist/models/sandwich.js +923 -0
  76. package/dist/models/survival.d.ts +65 -24
  77. package/dist/models/survival.js +407 -72
  78. package/dist/models/survreg.d.ts +160 -0
  79. package/dist/models/survreg.js +809 -0
  80. package/dist/numerics.js +2 -2
  81. package/dist/random/rng.d.ts +8 -1
  82. package/dist/random/rng.js +14 -1
  83. package/dist/rstats.js +16 -16
  84. package/dist/special.js +2 -2
  85. package/dist/tests.js +13 -13
  86. package/llms.txt +25 -0
  87. package/package.json +1 -1
  88. package/dist/chunks/chunk-47IIPUFN.js +0 -2
  89. package/dist/chunks/chunk-CQB4BJBR.js +0 -2
@@ -64,6 +64,8 @@ export interface GlmModel {
64
64
  start: number[] | undefined;
65
65
  /** k when the fit was computed on the response scaled by 2^-k (gaussian on the identity link; see scaledView). */
66
66
  yScale?: number;
67
+ /** 0-based indices of the input rows used (the rows without a missing value; rows of weight 0 included). */
68
+ rows: number[];
67
69
  }
68
70
  /**
69
71
  * Result of {@link glm}: R's `glm` object.
@@ -226,7 +228,10 @@ export interface GlmSummary {
226
228
  statistic: number[];
227
229
  /** Two-sided p-values (R's `Pr(>|z|)` or `Pr(>|t|)`). */
228
230
  pValue: number[];
229
- /** `"z value"` when the dispersion is fixed (binomial, poisson), else `"t value"`. */
231
+ /**
232
+ * `"z value"` when the dispersion is not estimated (fixed by the family: binomial, poisson; or given as
233
+ * `options.dispersion`), else `"t value"`.
234
+ */
230
235
  statisticName: "z value" | "t value";
231
236
  /** (R'R)^-1 of the columns that are not aliased. */
232
237
  covUnscaled: number[][];
@@ -321,6 +326,11 @@ export declare function glmResiduals(fit: GlmResult, options: GlmResidualsOption
321
326
  * @category Generalized linear models
322
327
  */
323
328
  export declare function glmHatvalues(fit: GlmResult): number[];
329
+ /**
330
+ * For each row of non-zero prior weight (in order, as glmHatvalues), its row in the fit's QR decomposition, or -1 for
331
+ * a row the last least squares step left out
332
+ */
333
+ export declare function glmQrRows(fit: GlmResult): number[];
324
334
  /**
325
335
  * Options for {@link glmRstandard}.
326
336
  *
@@ -17,6 +17,7 @@ import { optionalArgs } from "../internal/optionalArgs.js";
17
17
  import { ldexp, ldexpWide, scaleToUnit } from "../internal/summary.js";
18
18
  import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
19
19
  import { checkDot, checkedDot } from "../linalg/dot.js";
20
+ import { setInputRowCount } from "./inputRows.js";
20
21
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
21
22
  import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
22
23
  import { optionsIn } from "../internal/optionalArgs.js";
@@ -453,6 +454,7 @@ export function glm(x, y, options = {}) {
453
454
  // R loops over 1:maxit, so a fractional maxit runs (and reports) its integer part
454
455
  maxit: Math.floor(options.maxit ?? 25),
455
456
  start: options.start === undefined ? undefined : Array.from(options.start),
457
+ rows: keep.flatMap((k, i) => (k ? [i] : [])),
456
458
  };
457
459
  if (!(model.epsilon > 0 && model.epsilon < Infinity))
458
460
  throw new RangeError("value of 'epsilon' must be > 0 and finite");
@@ -462,7 +464,7 @@ export function glm(x, y, options = {}) {
462
464
  // (exact; src/internal/summary.ts), so that the deviance stays in range; see scaledView
463
465
  const k = !yIsMatrix && scalesWithResponse(familySpec) ? scaleToUnit([yGiven]).k : 0;
464
466
  if (k === 0)
465
- return reported("glm", fitModel(model));
467
+ return reported("glm", setInputRowCount(fitModel(model), nAll));
466
468
  const down = (v) => ldexp(v, -k);
467
469
  const scaled = fitModel({
468
470
  ...model,
@@ -470,7 +472,7 @@ export function glm(x, y, options = {}) {
470
472
  offset: offset.map(down),
471
473
  start: model.start?.map(down),
472
474
  });
473
- return reported("glm", unscaledResult(scaled, k, { ...model, yScale: k }));
475
+ return reported("glm", setInputRowCount(unscaledResult(scaled, k, { ...model, yScale: k }), nAll));
474
476
  }
475
477
  /** The fit of a model (the part of glm after its checks) */
476
478
  function fitModel(model) {
@@ -794,6 +796,21 @@ export function glmHatvalues(fit) {
794
796
  });
795
797
  return out;
796
798
  }
799
+ /**
800
+ * For each row of non-zero prior weight (in order, as glmHatvalues), its row in the fit's QR decomposition, or -1 for
801
+ * a row the last least squares step left out
802
+ */
803
+ export function glmQrRows(fit) {
804
+ const out = [];
805
+ let k = 0;
806
+ const usedRows = USED_ROWS.get(fit) ?? fit.weights.map((v) => v > 0);
807
+ fit.priorWeights.forEach((w, i) => {
808
+ const r = usedRows[i] ? k++ : -1;
809
+ if (w > 0)
810
+ out.push(r);
811
+ });
812
+ return out;
813
+ }
797
814
  function median(v) {
798
815
  const s = v.slice().sort((a, b) => a - b);
799
816
  const m = s.length >> 1;
@@ -0,0 +1,10 @@
1
+ import type { DataFrame } from "./modelFrame.js";
2
+ /** Records the number of input rows of a fit and returns the fit */
3
+ export declare function setInputRowCount<T extends object>(fit: T, n: number | undefined): T;
4
+ /**
5
+ * The number of input rows of a fit: as recorded, or else one more than the last row used (a fit copied from the
6
+ * result, whose trailing rows dropped for a missing value cannot be known)
7
+ */
8
+ export declare function inputRowCount(fit: object, rows: readonly number[]): number;
9
+ /** The number of rows of a data frame: the length of a column of the formula's variables, else of its first column */
10
+ export declare function dataRowCount(data: DataFrame, variables: readonly string[]): number | undefined;
@@ -0,0 +1,23 @@
1
+ // The number of input rows a fit was given (before the rows with a missing value were dropped), for the functions that
2
+ // take one value per input row of a fit (vcovCL's cluster). Kept beside the result, not in it.
3
+ const INPUT_ROWS = new WeakMap();
4
+ /** Records the number of input rows of a fit and returns the fit */
5
+ export function setInputRowCount(fit, n) {
6
+ if (n !== undefined)
7
+ INPUT_ROWS.set(fit, n);
8
+ return fit;
9
+ }
10
+ /**
11
+ * The number of input rows of a fit: as recorded, or else one more than the last row used (a fit copied from the
12
+ * result, whose trailing rows dropped for a missing value cannot be known)
13
+ */
14
+ export function inputRowCount(fit, rows) {
15
+ return INPUT_ROWS.get(fit) ?? (rows.length === 0 ? 0 : rows[rows.length - 1] + 1);
16
+ }
17
+ /** The number of rows of a data frame: the length of a column of the formula's variables, else of its first column */
18
+ export function dataRowCount(data, variables) {
19
+ for (const v of variables)
20
+ if (Object.hasOwn(data, v))
21
+ return data[v].length;
22
+ return Object.values(data)[0]?.length;
23
+ }
@@ -65,6 +65,12 @@ export interface LmResult {
65
65
  intercept: boolean;
66
66
  /** The QR decomposition of the (weighted) model matrix. */
67
67
  qr: QR;
68
+ /** The model matrix (with the column of ones when there is an intercept) of the rows used, unweighted. */
69
+ x: number[][];
70
+ /** 0-based indices of the input rows used (the rows without a missing value; rows of weight 0 included). */
71
+ rows: number[];
72
+ /** The weights of the rows used, if any. */
73
+ weights?: number[];
68
74
  }
69
75
  /**
70
76
  * Options of {@link lm} with a formula.
@@ -178,6 +184,8 @@ export interface LmCore {
178
184
  * fitted values, effects, sigma and standard errors are multiplied by 2^k, the residual sum of squares by 2^2k.
179
185
  */
180
186
  export declare function fitLm(Xall: number[][], Yall: number[], Wall: number[] | undefined, intercept: boolean, precise?: boolean): LmCore;
187
+ /** The exponent qw of the weights of an lm fit's decomposition (0 for the decomposition with the weights given) */
188
+ export declare function qrWeightExponent(q: QR): number;
181
189
  /**
182
190
  * Options for {@link confint}.
183
191
  *
package/dist/models/lm.js CHANGED
@@ -25,6 +25,7 @@ import { design } from "./modelMatrix.js";
25
25
  import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
26
26
  import { checkDot, checkedDot } from "../linalg/dot.js";
27
27
  import { reported } from "../internal/warnings.js";
28
+ import { dataRowCount, setInputRowCount } from "./inputRows.js";
28
29
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
29
30
  import { checkOptions } from "../internal/checkOptions.js";
30
31
  const LM_KEYS = ["weights", "contrasts", "levels", "intercept"];
@@ -77,7 +78,8 @@ export function lmFormulaFit(formula, d, aov) {
77
78
  export function lm(x, y, options = {}) {
78
79
  checkOptions(options, LM_KEYS, "lm"); // generated: option-keys.mjs
79
80
  if (typeof x === "string") {
80
- return reported("lm", lmFormulaFit(x, design(parseFormula(x), y, { ...options, dropUnusedLevels: true }), false));
81
+ const d = design(parseFormula(x), y, { ...options, dropUnusedLevels: true });
82
+ return reported("lm", setInputRowCount(lmFormulaFit(x, d, false), dataRowCount(y, d.terms.variables)));
81
83
  }
82
84
  return lmMatrix(x, y, options);
83
85
  }
@@ -100,7 +102,9 @@ function lmMatrix(x, y, options) {
100
102
  throw new RangeError("missing or negative weights not allowed");
101
103
  const Xall = xr.filter((_, i) => keep[i]).map((r) => (intercept ? [1, ...r] : r));
102
104
  const Yall = ys.filter((_, i) => keep[i]);
103
- return fitLm(Xall, Yall, Wall, intercept).result;
105
+ const result = fitLm(Xall, Yall, Wall, intercept).result;
106
+ result.rows = keep.flatMap((k, i) => (k ? [i] : []));
107
+ return setInputRowCount(result, ys.length);
104
108
  }
105
109
  /**
106
110
  * The coefficients, fitted values, residuals, effects and sums of squares of a fit recomputed in double-double on the
@@ -222,6 +226,10 @@ function zeroWeightRows(core, Xall, Yall, Wall) {
222
226
  * absent for the decomposition with the weights given
223
227
  */
224
228
  const QR_WEIGHT_EXPONENT = new WeakMap();
229
+ /** The exponent qw of the weights of an lm fit's decomposition (0 for the decomposition with the weights given) */
230
+ export function qrWeightExponent(q) {
231
+ return QR_WEIGHT_EXPONENT.get(q) ?? 0;
232
+ }
225
233
  /** Whether every entry of a decomposition is finite */
226
234
  function finiteQR(q) {
227
235
  return q.qr.every((r) => r.every(Number.isFinite)) && q.qraux.every(Number.isFinite);
@@ -353,7 +361,11 @@ function fitLmUnit(Xall, Yall, Wall, intercept, precise) {
353
361
  adjRSquared: 0,
354
362
  intercept,
355
363
  qr: q,
364
+ x: Xall,
365
+ rows: Xall.map((_, i) => i),
356
366
  };
367
+ if (Wall !== undefined)
368
+ result.weights = Wall;
357
369
  const dfInt = intercept ? 1 : 0;
358
370
  const numdf = rank - dfInt;
359
371
  const core = { result, fitRows, effects: (pf?.effects ?? []).map((e) => ldexp(e, kw / 2)), rss: ldexp(rss, kw + rs) };
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Options for {@link rmst2}.
3
+ *
4
+ * @category Survival analysis
5
+ */
6
+ export interface Rmst2Options {
7
+ /** Restriction time. Defaults to the largest follow-up time allowed by both arms. */
8
+ tau?: number;
9
+ /** Numeric covariates, one row per observation. A vector is treated as one column; rows with missing values are omitted. */
10
+ covariates?: readonly number[] | readonly (readonly number[])[];
11
+ /** Optional names of matrix columns; a vector is named "covariates", an unnamed matrix has empty names. */
12
+ covariateNames?: readonly string[];
13
+ /** Confidence level. Default 0.95. */
14
+ confLevel?: number;
15
+ }
16
+ /** An estimate, its standard error and a two-sided confidence interval. */
17
+ /**
18
+ * An RMST or RMTL estimate with its standard error and confidence interval.
19
+ *
20
+ * @category Survival analysis
21
+ */
22
+ export interface RmstEstimate {
23
+ /** Restricted mean or restricted mean time lost. */
24
+ estimate: number;
25
+ /** Greenwood or sandwich standard error. */
26
+ se: number;
27
+ /** Two-sided confidence interval. */
28
+ confInt: [number, number];
29
+ }
30
+ /** A between-arm difference or ratio with its confidence interval and two-sided p-value. */
31
+ /**
32
+ * A between-arm contrast with its confidence interval and p-value.
33
+ *
34
+ * @category Survival analysis
35
+ */
36
+ export interface RmstContrast {
37
+ /** Difference (arm 1 minus arm 0) or ratio (arm 1 divided by arm 0). */
38
+ estimate: number;
39
+ /** Two-sided confidence interval. */
40
+ confInt: [number, number];
41
+ /** Two-sided normal-tail p-value. */
42
+ pValue: number;
43
+ }
44
+ /** Coefficient estimates and robust Wald inference for an adjusted model. */
45
+ /**
46
+ * Coefficient estimates and robust Wald inference for an adjusted RMST model.
47
+ *
48
+ * @category Survival analysis
49
+ */
50
+ export interface RmstCoefficientTable {
51
+ /** Intercept, treatment indicator and covariate names. */
52
+ names: string[];
53
+ /** Model coefficients (log-scale coefficients for ratio models). */
54
+ estimate: number[];
55
+ se: number[];
56
+ z: number[];
57
+ pValue: number[];
58
+ /** Confidence limits: coefficient scale for the difference model, exponentiated scale for ratio models. */
59
+ confInt: [number[], number[]];
60
+ }
61
+ /**
62
+ * Result of {@link rmst2}.
63
+ *
64
+ * @category Survival analysis
65
+ */
66
+ export interface Rmst2Result {
67
+ /** Restriction time used in the analysis. */
68
+ tau: number;
69
+ /** Whether tau was selected from the follow-up times. */
70
+ tauDefault: boolean;
71
+ /** Confidence level. */
72
+ confLevel: number;
73
+ /** Warnings, each distinct message once. */
74
+ warnings: string[];
75
+ /** Unadjusted per-arm estimates; omitted when covariate adjustment is requested. */
76
+ arm1?: {
77
+ rmst: RmstEstimate;
78
+ rmtl: RmstEstimate;
79
+ };
80
+ arm0?: {
81
+ rmst: RmstEstimate;
82
+ rmtl: RmstEstimate;
83
+ };
84
+ /** Unadjusted between-arm contrasts. */
85
+ difference: RmstContrast;
86
+ ratio: RmstContrast;
87
+ rmtlRatio: RmstContrast;
88
+ /** Covariate-adjusted between-arm contrasts, present when covariates are supplied. */
89
+ adjusted?: {
90
+ difference: RmstContrast;
91
+ ratio: RmstContrast;
92
+ rmtlRatio: RmstContrast;
93
+ };
94
+ /** Coefficient estimates, robust standard errors and Wald tests for the three adjusted models. */
95
+ coefficients?: {
96
+ difference: RmstCoefficientTable;
97
+ ratio: RmstCoefficientTable;
98
+ rmtlRatio: RmstCoefficientTable;
99
+ };
100
+ }
101
+ /**
102
+ * Restricted mean survival time (RMST), restricted mean time lost (RMTL), and their between-arm contrasts.
103
+ * Implements the unadjusted Kaplan-Meier estimators and Tian, Zhao & Wei's adjusted estimating equations.
104
+ * Equivalent to `survRM2::rmst2()` in R.
105
+ *
106
+ * @param time Follow-up times.
107
+ * @param status Event indicator (1 event, 0 censored; 1/2 coding is also accepted). Invalid values are omitted with a warning.
108
+ * @param arm Treatment indicator (0 or 1; booleans are also accepted).
109
+ * @param options Restriction time, covariates, optional matrix column names and confidence level.
110
+ * @returns Per-arm RMST/RMTL estimates and between-arm contrasts; adjusted contrasts and coefficient tables are added
111
+ * when covariates are supplied.
112
+ *
113
+ * Rows with missing time, status, arm, or covariates are omitted. Negative follow-up times, non-positive tau, tau below
114
+ * the first retained observation, and tau above its default upper bound are errors.
115
+ * @example
116
+ * ```ts
117
+ * const r = rmst2([1,2,3,4,5,6,1.5,2.5,3.5,4.5,7,8],
118
+ * [1,0,1,1,0,1,1,1,0,1,1,0], [1,1,1,1,1,1,0,0,0,0,0,0]);
119
+ * r.tau; // 8
120
+ * r.arm1?.rmst.estimate; // 4.125
121
+ * r.arm0?.rmst.estimate; // 5
122
+ * r.difference.estimate; // -0.875
123
+ * ```
124
+ * @category Survival analysis
125
+ */
126
+ export declare function rmst2(time: readonly number[], status: readonly number[], arm: readonly (number | boolean)[], options?: Rmst2Options): Rmst2Result;