@numero-uno-jpn/rstats 1.1.0 → 1.3.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 (97) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/README.ja.md +33 -15
  3. package/README.md +32 -14
  4. package/dist/chunks/{chunk-4KCSBTR5.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-Z2HGLFZN.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-U7BRXOUS.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-GJEKNJP7.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-GRUQRNX7.js → chunk-BNTBZ5W3.js} +3 -3
  10. package/dist/chunks/{chunk-DR4GQ7PW.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-OG7UORIX.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-N5BDSMXS.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-GGJA3JRO.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-HRA7PCQT.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-YN5MLKDL.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-GYGQUYEP.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-X4J6UJHN.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-DTJG2IL2.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-4VRMAYPY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/chunk-P7ZHH2SF.js +2 -0
  23. package/dist/chunks/{chunk-HUWOSLKE.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-7KJ24LYK.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-QUTJEYDX.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-HZLSNJQM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-EJYCDE4Z.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7IJCUSA5.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-JNWWLNE3.js → chunk-Z74ZOTUN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions.js +2 -2
  32. package/dist/entries/tests.d.ts +14 -0
  33. package/dist/entries/tests.js +14 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/binomCI.d.ts +116 -0
  36. package/dist/htest/binomCI.js +252 -0
  37. package/dist/htest/blandAltman.d.ts +100 -0
  38. package/dist/htest/blandAltman.js +159 -0
  39. package/dist/htest/boschlooTest.d.ts +65 -0
  40. package/dist/htest/boschlooTest.js +394 -0
  41. package/dist/htest/chisqTest.d.ts +19 -0
  42. package/dist/htest/chisqTest.js +30 -2
  43. package/dist/htest/core/twoProportions.d.ts +48 -0
  44. package/dist/htest/core/twoProportions.js +476 -0
  45. package/dist/htest/diagnosticTests.d.ts +91 -0
  46. package/dist/htest/diagnosticTests.js +116 -0
  47. package/dist/htest/equivalence.d.ts +172 -0
  48. package/dist/htest/equivalence.js +189 -0
  49. package/dist/htest/fisherTest.d.ts +49 -0
  50. package/dist/htest/fisherTest.js +136 -13
  51. package/dist/htest/iccPsych.d.ts +106 -0
  52. package/dist/htest/iccPsych.js +332 -0
  53. package/dist/htest/ksTest.d.ts +1 -1
  54. package/dist/htest/mcreg.d.ts +209 -0
  55. package/dist/htest/mcreg.js +735 -0
  56. package/dist/htest/roc.d.ts +287 -0
  57. package/dist/htest/roc.js +635 -0
  58. package/dist/htest/rocTest.d.ts +139 -0
  59. package/dist/htest/rocTest.js +444 -0
  60. package/dist/htest/tTOST.d.ts +202 -0
  61. package/dist/htest/tTOST.js +558 -0
  62. package/dist/htest/tableTests.d.ts +216 -0
  63. package/dist/htest/tableTests.js +650 -0
  64. package/dist/htest/trendTests.d.ts +1 -1
  65. package/dist/htest/trendTests.js +1 -1
  66. package/dist/htest/twoByTwo.d.ts +203 -0
  67. package/dist/htest/twoByTwo.js +385 -0
  68. package/dist/internal/summary.js +5 -0
  69. package/dist/linalg/qr.d.ts +3 -0
  70. package/dist/linalg/qr.js +3 -0
  71. package/dist/linalg.js +2 -2
  72. package/dist/mixed.js +2 -2
  73. package/dist/models/coeftest.d.ts +139 -0
  74. package/dist/models/coeftest.js +237 -0
  75. package/dist/models/coxph.d.ts +60 -9
  76. package/dist/models/coxph.js +367 -38
  77. package/dist/models/glm.d.ts +11 -1
  78. package/dist/models/glm.js +19 -2
  79. package/dist/models/inputRows.d.ts +10 -0
  80. package/dist/models/inputRows.js +23 -0
  81. package/dist/models/lm.d.ts +8 -0
  82. package/dist/models/lm.js +14 -2
  83. package/dist/models/sandwich.d.ts +177 -0
  84. package/dist/models/sandwich.js +923 -0
  85. package/dist/numerics.js +2 -2
  86. package/dist/random/rng.d.ts +8 -1
  87. package/dist/random/rng.js +14 -1
  88. package/dist/rstats.js +16 -16
  89. package/dist/special/igam.js +140 -23
  90. package/dist/special/loader.js +8 -0
  91. package/dist/special.js +2 -2
  92. package/dist/tests.js +13 -13
  93. package/llms.txt +25 -0
  94. package/package.json +1 -1
  95. package/dist/chunks/chunk-NDTJ23A6.js +0 -2
  96. package/dist/chunks/chunk-UMLMY4XS.js +0 -2
  97. package/dist/chunks/chunk-Y4YWLSWU.js +0 -2
@@ -0,0 +1,116 @@
1
+ // Diagnostic accuracy of a binary test from its 2 x 2 table (epiR's epi.tests): sensitivity, specificity, predictive
2
+ // values, likelihood ratios, accuracy, the diagnostic odds ratio and the prevalences, with intervals.
3
+ //
4
+ // Written for rStats.js from oracle/roc-behaviour.md, section 9 (no ported code; the source of epiR was not read):
5
+ // - The proportions' intervals are binomCI's: Clopper-Pearson ("exact"; Clopper and Pearson, Biometrika 26, 1934,
6
+ // computed with qbeta directly, where epiR's 1 - qbeta(...) loses digits), Wilson's (Wilson, JASA 22, 1927) and
7
+ // Jeffreys' (Brown, Cai and DasGupta, Statistical Science 16, 2001).
8
+ // - The likelihood ratios' intervals: the log method of Simel, Samsa and Matchar (J Clin Epidemiol 44, 1991), with
9
+ // the variance of log LR+ written as c/(a M1) + d/(b M0) (= 1/a - 1/M1 + 1/b - 1/M0, without the cancellation).
10
+ // - The diagnostic odds ratio's interval: Woolf's (Annals of Human Genetics 19, 1955), exp(log OR -+ z sqrt(1/a + 1/b
11
+ // + 1/c + 1/d)).
12
+ // - Predictive values at a given prevalence p by Bayes' theorem: se p/(se p + (1 - sp)(1 - p)) and sp (1 - p)/(sp (1 -
13
+ // p) + (1 - se) p), from the counts (1 - sp = b/M0 and 1 - se = c/M1 without cancellation).
14
+ // Zero cells give what the formulas give (Inf, 0 and NaN limits), as epiR; no correction is added.
15
+ import { qnorm } from "../distributions/normal.js";
16
+ import { reported, unreported } from "../internal/warnings.js";
17
+ import { binomCI } from "./binomCI.js";
18
+ import { matchChoice } from "./power.js";
19
+ import { ratioToDouble } from "./roc.js";
20
+ import { checkConfLevelOpen, isCount } from "./types.js";
21
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
22
+ import { checkOptions } from "../internal/checkOptions.js";
23
+ const DIAGNOSTIC_TESTS_KEYS = ["method", "confLevel", "prevalence"];
24
+ /**
25
+ * Sensitivity, specificity, predictive values, likelihood ratios, accuracy, the diagnostic odds ratio and the true and
26
+ * apparent prevalence of a binary test, each with a confidence interval, from its 2 × 2 table. Equivalent to
27
+ * `epiR::epi.tests()` in R.
28
+ *
29
+ * The table is epiR's: rows test positive and negative, columns disease present and absent, `[[a, b], [c, d]]` with
30
+ * a the true positives, b the false positives, c the false negatives and d the true negatives. The proportions'
31
+ * intervals are those of {@link binomCI}: `"exact"` is Clopper-Pearson's, computed directly (epiR computes it as 1 −
32
+ * qbeta(...), which loses digits for small limits); `"jeffreys"` gives 0 and 1 at the ends, as binomCI (epiR the
33
+ * beta quantiles). The likelihood ratios have the log interval (Simel, Samsa and Matchar 1991) and the odds ratio
34
+ * Woolf's. Zero cells give infinite ratios and NaN limits, as epiR; a zero row or column total is an error.
35
+ *
36
+ * @param table The 2 × 2 table of counts (an array of two rows).
37
+ * @param options See {@link DiagnosticTestsOptions}.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const r = diagnosticTests([[670, 202], [74, 640]]);
42
+ * r.sensitivity.estimate; // 0.9005376344086021
43
+ * r.sensitivity.confInt; // [0.8767461767957109, 0.9210922995836943]
44
+ * r.lrPos.estimate; // 3.7537261790695196
45
+ * diagnosticTests([[670, 202], [74, 640]], { prevalence: 0.1 }).ppvAtPrevalence; // 0.2943238804381625
46
+ * ```
47
+ *
48
+ * @category Hypothesis tests
49
+ */
50
+ export function diagnosticTests(table, options = {}) {
51
+ checkOptions(options, DIAGNOSTIC_TESTS_KEYS, "diagnosticTests"); // generated: option-keys.mjs
52
+ const method = matchChoice(options.method, ["exact", "wilson", "jeffreys"]);
53
+ const confLevel = options.confLevel ?? 0.95;
54
+ checkConfLevelOpen(confLevel);
55
+ if (!Array.isArray(table) || table.length !== 2 || table.some((r) => !(Array.isArray(r) || ArrayBuffer.isView(r)) || r.length !== 2)) {
56
+ throw new TypeError("'table' must be a 2 x 2 table (an array of two rows of two counts)");
57
+ }
58
+ const cells = [table[0][0], table[0][1], table[1][0], table[1][1]];
59
+ if (cells.some((v) => typeof v !== "number"))
60
+ throw new TypeError("the counts must be numbers");
61
+ if (!cells.every(isCount))
62
+ throw new RangeError("the counts must be nonnegative integers");
63
+ const [a, b, c, d] = cells.map(Math.round);
64
+ const M1 = a + c;
65
+ const M0 = b + d;
66
+ const N1 = a + b;
67
+ const N0 = c + d;
68
+ const total = M1 + M0;
69
+ if (M1 === 0 || M0 === 0 || N1 === 0 || N0 === 0)
70
+ throw new RangeError("every row and column total of the table must be positive");
71
+ const prop = (x, n) => {
72
+ const r = unreported(() => binomCI(x, n, { method: method === "exact" ? "clopper-pearson" : method, confLevel }));
73
+ return { estimate: r.estimate, confInt: r.confInt };
74
+ };
75
+ const alpha = 1 - confLevel;
76
+ const z = alpha / 2 < 1e-8 ? qnorm(alpha / 2, { lowerTail: false }) : qnorm(1 - alpha / 2);
77
+ const logInterval = (est, v) => {
78
+ const half = z * Math.sqrt(v);
79
+ return { estimate: est, confInt: [Math.exp(Math.log(est) - half), Math.exp(Math.log(est) + half)] };
80
+ };
81
+ const se = a / M1;
82
+ const sp = d / M0;
83
+ const result = {
84
+ sensitivity: prop(a, M1),
85
+ specificity: prop(d, M0),
86
+ ppv: prop(a, N1),
87
+ npv: prop(d, N0),
88
+ // se/(1 - sp) with 1 - sp = b/M0, and (1 - se)/sp with 1 - se = c/M1, each from the counts and rounded once:
89
+ // (a M0)/(M1 b) (se / (b / M0) was rounded three times); b = 0 gives Inf, or NaN for a = 0
90
+ lrPos: logInterval(b === 0 ? se / 0 : ratioToDouble(BigInt(a) * BigInt(M0), BigInt(M1) * BigInt(b)), c / (a * M1) + d / (b * M0)),
91
+ // (c M0)/(M1 d), rounded once (c / M1 / sp was rounded three times); d = 0 gives Inf or NaN
92
+ lrNeg: logInterval(d === 0 ? c / M1 / sp : ratioToDouble(BigInt(c) * BigInt(M0), BigInt(M1) * BigInt(d)), a / (c * M1) + b / (d * M0)),
93
+ accuracy: prop(a + d, total),
94
+ diagnosticOR: logInterval((a * d) / (b * c), 1 / a + 1 / b + 1 / c + 1 / d),
95
+ prevalence: prop(M1, total),
96
+ apparentPrevalence: prop(N1, total),
97
+ method,
98
+ confLevel,
99
+ warnings: [],
100
+ };
101
+ if (options.prevalence !== undefined) {
102
+ const p = options.prevalence;
103
+ if (!(typeof p === "number" && p > 0 && p < 1))
104
+ throw new RangeError("'prevalence' must be a number in (0, 1)");
105
+ // p and 1 - p scaled by 2^600 in the positive predictive value when p is tiny: se p underflowed (to 0, and 0/0
106
+ // for b = 0, at p = 5e-324), and the ratio is unchanged by a common power of 2
107
+ const scale = p < 2 ** -500 ? 2 ** 600 : 1;
108
+ const tpr = se * (p * scale);
109
+ const fpr = (b / M0) * ((1 - p) * scale);
110
+ const tnr = sp * (1 - p);
111
+ const fnr = (c / M1) * p;
112
+ result.ppvAtPrevalence = tpr / (tpr + fpr);
113
+ result.npvAtPrevalence = tnr / (tnr + fnr);
114
+ }
115
+ return reported("diagnosticTests", result);
116
+ }
@@ -0,0 +1,172 @@
1
+ import { type Sample } from "./types.js";
2
+ /**
3
+ * Options for {@link tost}.
4
+ *
5
+ * @category Hypothesis tests
6
+ */
7
+ export interface TostOptions {
8
+ /** The equivalence margin: equivalence means |mean difference| < epsilon. Positive. Default `1` (as R). */
9
+ epsilon?: number;
10
+ /** Paired TOST on `x - y` (pairs with `NaN` are dropped). Default `false`. */
11
+ paired?: boolean;
12
+ /** Pooled variance (Student's t) instead of Welch's. Default `false`. */
13
+ varEqual?: boolean;
14
+ /** One minus the level of each one-sided test, in (0.5, 1); the interval is a 1 - 2(1 - confLevel) interval.
15
+ * Default `0.95`. */
16
+ confLevel?: number;
17
+ /** The level of each one-sided test, in (0, 0.5); overrides `confLevel` (which becomes `1 - alpha`). */
18
+ alpha?: number;
19
+ }
20
+ /**
21
+ * Result of {@link tost}.
22
+ *
23
+ * @category Hypothesis tests
24
+ */
25
+ export interface TostResult {
26
+ /** `"Welch Two Sample TOST"`, `" Two Sample TOST"` (pooled; the leading space is R's) or `"Paired TOST"`. */
27
+ method: string;
28
+ /** Degrees of freedom of the t tests (`parameterName` `"df"`). */
29
+ parameter: number;
30
+ /** `"df"`. */
31
+ parameterName: string;
32
+ /** The larger of the two one-sided p-values, `P(T > (epsilon - |d|)/se)` (R's `tost.p.value`). */
33
+ pValue: number;
34
+ /** `"rejected"` (equivalence shown: `confInt` lies inside (-epsilon, epsilon)) or `"not rejected"`, as R. */
35
+ result: "rejected" | "not rejected";
36
+ /** `d -+ qt(confLevel, df) se`: the 1 - 2(1 - confLevel) interval of the difference (R's `tost.interval`). */
37
+ confInt: [number, number];
38
+ /** `confLevel` (or `1 - alpha`), R's `conf.level` attribute of the interval. */
39
+ confLevel: number;
40
+ /** `[mean of x, mean of y]`, or the mean of the differences for a paired test. */
41
+ estimate: number | number[];
42
+ /** Names of `estimate`, as tTest's. */
43
+ estimateNames: string | string[];
44
+ /** The margin. */
45
+ epsilon: number;
46
+ /** Standard error of the difference (R's `se.diff`). */
47
+ seDiff: number;
48
+ /** Warnings (none: input without a defined result is an error). */
49
+ warnings: string[];
50
+ }
51
+ /**
52
+ * Two one-sided t tests (TOST) of equivalence of two means. Equivalent to `equivalence::tost()` in R.
53
+ *
54
+ * Equivalence, |mean(x) - mean(y)| < epsilon, is shown at level alpha = 1 - confLevel when both one-sided t tests of
55
+ * H01: d <= -epsilon and H02: d >= epsilon reject; the p-value is the larger of their p-values and `confInt` the dual
56
+ * 1 - 2 alpha interval (90% for the default `confLevel` 0.95). The difference, standard error and degrees of freedom are
57
+ * those of {@link tTest} (Welch's by default, pooled with `varEqual`, paired with `paired`), with tTest's checks and
58
+ * errors. Used on 0/1 data it compares two proportions with a t approximation; for counts
59
+ * {@link binomDiffEquivalenceTest} is the better test.
60
+ *
61
+ * Unlike R, a level of 0.5 or less (`confLevel`) or of 0.5 or more (`alpha`) is an error (the interval would be empty),
62
+ * and so is a margin that is not positive.
63
+ *
64
+ * @param x Sample.
65
+ * @param y Second sample.
66
+ * @param options See {@link TostOptions}.
67
+ * @returns See {@link TostResult}.
68
+ * @throws RangeError for a margin that is not positive and finite or a level out of range; Error where tTest has
69
+ * too few observations or the data are essentially constant.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const r = tost([5.1, 4.9, 5.6, 5.8, 6.0, 5.4], [5.3, 5.0, 5.5, 5.7, 5.9, 5.2], { epsilon: 0.5 });
74
+ * r.pValue; // 0.029694342816029128
75
+ * r.confInt; // [-0.36394177233776226, 0.4306084390044287] (a 90% interval)
76
+ * r.result; // "rejected"
77
+ * ```
78
+ *
79
+ * @category Hypothesis tests
80
+ */
81
+ export declare function tost(x: Sample, y: Sample, options?: TostOptions): TostResult;
82
+ /**
83
+ * Statistics of {@link binomDiffEquivalenceTest}.
84
+ *
85
+ * @category Hypothesis tests
86
+ */
87
+ export type BinomDiffEquivalenceMethod = "mn" | "mee" | "wald";
88
+ /**
89
+ * Options for {@link binomDiffEquivalenceTest}.
90
+ *
91
+ * @category Hypothesis tests
92
+ */
93
+ export interface BinomDiffEquivalenceTestOptions {
94
+ /** The equivalence margin epsilon, in (0, 1): equivalence means -epsilon < p1 - p2 < epsilon. Required. */
95
+ margin?: number;
96
+ /** The statistic: `"mn"` (Miettinen-Nurminen score, the default), `"mee"` (Farrington-Manning score) or `"wald"`.
97
+ * Unambiguous abbreviations are accepted. */
98
+ method?: BinomDiffEquivalenceMethod | (string & {});
99
+ /** The level of each one-sided test, in (0, 0.5). Default `0.05`. */
100
+ alpha?: number;
101
+ }
102
+ /**
103
+ * Result of {@link binomDiffEquivalenceTest}.
104
+ *
105
+ * @category Hypothesis tests
106
+ */
107
+ export interface BinomDiffEquivalenceTestResult {
108
+ /** The statistic, in full (`"mn"`, `"mee"` or `"wald"`). */
109
+ method: BinomDiffEquivalenceMethod;
110
+ /** The estimate p1 - p2. */
111
+ estimate: number;
112
+ /** The margin epsilon. */
113
+ margin: number;
114
+ /** The level of each one-sided test. */
115
+ alpha: number;
116
+ /**
117
+ * `[z(-margin), z(margin)]`, z(delta0) = (p1 - p2 - delta0) / sqrt(var(delta0)): the statistics of H01: p1 - p2 <=
118
+ * -margin (large values reject) and of H02: p1 - p2 >= margin (small values reject).
119
+ */
120
+ statistic: [number, number];
121
+ /** `"z"`. */
122
+ statisticName: string;
123
+ /** `[P(Z > z(-margin)), P(Z < z(margin))]`: the one-sided p-values of H01 and H02. */
124
+ pValues: [number, number];
125
+ /** The larger of `pValues`: the p-value of the test of equivalence. */
126
+ pValue: number;
127
+ /** `"rejected"` (equivalence shown: both p-values below alpha) or `"not rejected"`, as {@link tost}'s `result`. */
128
+ result: "rejected" | "not rejected";
129
+ /** The 1 - 2 alpha interval of p1 - p2 of {@link binomDiffCI} with the same method; equivalence is shown exactly when
130
+ * it lies inside (-margin, margin). */
131
+ confInt: [number, number];
132
+ /** `1 - 2 alpha`. */
133
+ confLevel: number;
134
+ /** Warnings (none: input without a defined result is an error). */
135
+ warnings: string[];
136
+ }
137
+ /**
138
+ * Test of equivalence of two independent proportions x1/n1 and x2/n2 within a margin. Two one-sided tests of
139
+ * H01: p1 - p2 <= -margin and H02: p1 - p2 >= margin, each at level `alpha`; equivalence is shown when both reject.
140
+ * Not an R function. (The R packages in scope give the dual intervals, `DescTools::BinomDiffCI`, or test one bound at
141
+ * a time.)
142
+ *
143
+ * The statistic at a bound delta0 is z = (p1 - p2 - delta0) / sqrt(var), with var the variance of p1 - p2 at the
144
+ * maximum likelihood estimate of (p1, p2) under p1 - p2 = delta0 (Farrington and Manning 1990, `"mee"`), the same times
145
+ * N/(N - 1) (Miettinen and Nurminen 1985, `"mn"`, the default), or at the observed proportions (`"wald"`). The
146
+ * p-values are normal tails. The test is dual to {@link binomDiffCI} with the same method at the level 1 - 2 alpha:
147
+ * equivalence is shown exactly when that interval, returned as `confInt`, lies inside (-margin, margin).
148
+ *
149
+ * The Wald variance is 0 when both proportions are 0 or 1: the statistics are then infinite and the p-values 0 or 1,
150
+ * as binomDiffCI's Wald interval is a point there.
151
+ *
152
+ * @param x1 Successes in group 1.
153
+ * @param n1 Trials in group 1.
154
+ * @param x2 Successes in group 2.
155
+ * @param n2 Trials in group 2.
156
+ * @param options See {@link BinomDiffEquivalenceTestOptions}; `margin` is required.
157
+ * @returns See {@link BinomDiffEquivalenceTestResult}.
158
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a margin outside (0, 1), alpha
159
+ * outside (0, 0.5), or an unknown method.
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * const r = binomDiffEquivalenceTest(80, 100, 78, 100, { margin: 0.15 });
164
+ * r.pValues; // [0.0018937433499954864, 0.012899725361675841]
165
+ * r.pValue; // 0.012899725361675841
166
+ * r.confInt; // [-0.07557697533608577, 0.11553638647686569] (binomDiffCI, method "mn", 90%)
167
+ * r.result; // "rejected"
168
+ * ```
169
+ *
170
+ * @category Hypothesis tests
171
+ */
172
+ export declare function binomDiffEquivalenceTest(x1: number, n1: number, x2: number, n2: number, options?: BinomDiffEquivalenceTestOptions): BinomDiffEquivalenceTestResult;
@@ -0,0 +1,189 @@
1
+ // Tests of equivalence: the two one-sided t tests (TOST) of the package equivalence's tost, and a test of equivalence
2
+ // of two proportions on counts with the score statistics of the difference.
3
+ //
4
+ // Written for rStats.js from the published methods and the package's documented behaviour (no R or package code):
5
+ // - TOST (Schuirmann, Journal of Pharmacokinetics and Biopharmaceutics 15, 1987): equivalence of the means within
6
+ // (-epsilon, epsilon) is shown at level alpha when both H01: d <= -epsilon and H02: d >= epsilon are rejected by
7
+ // one-sided t tests at alpha; the larger one-sided p-value is P(T > (epsilon - |d|)/se) on the df of the t test, and
8
+ // the dual interval is d -+ qt(1 - alpha, df) se, a 1 - 2 alpha interval. The mean difference, its standard error
9
+ // and the df are tTest's (Welch's, pooled or paired).
10
+ // - Two proportions: the same pair of one-sided hypotheses about p1 - p2, tested with the score statistic
11
+ // z(delta0) = (p1 - p2 - delta0) / sqrt(var(delta0)) at delta0 = -epsilon and +epsilon, var at the maximum likelihood
12
+ // estimate under p1 - p2 = delta0 (Farrington and Manning, Statistics in Medicine 9, 1990, 1447-1454), times
13
+ // N/(N - 1) for Miettinen and Nurminen (Statistics in Medicine 4, 1985, 213-226), or at the observed proportions
14
+ // (Wald). The statistics and the restricted MLE are those of src/htest/core/twoProportions.ts; the dual 1 - 2 alpha
15
+ // interval is binomDiffCI's with the same method.
16
+ import { pnorm } from "../distributions/normal.js";
17
+ import { pt1, qt1 } from "../distributions/t.js";
18
+ import { reported, unreported } from "../internal/warnings.js";
19
+ import { checkTrials, levelOfAlpha } from "./binomCI.js";
20
+ import { diffDeviation, diffVariance } from "./core/twoProportions.js";
21
+ import { matchChoice } from "./power.js";
22
+ import { tTest } from "./tTest.js";
23
+ import { checkConfLevelOpen } from "./types.js";
24
+ import { binomDiffLimits } from "./twoByTwo.js";
25
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
26
+ import { checkOptions } from "../internal/checkOptions.js";
27
+ const TOST_KEYS = ["epsilon", "paired", "varEqual", "confLevel", "alpha"];
28
+ const BINOM_DIFF_EQUIVALENCE_TEST_KEYS = ["margin", "method", "alpha"];
29
+ // Generated by `node scripts/option-keys.mjs --write` (end)
30
+ /** The level of a TOST: alpha in (0, 0.5), so that the 1 - 2 alpha interval is an interval */
31
+ function checkAlpha(alpha, name) {
32
+ if (!(typeof alpha === "number" && alpha > 0 && alpha < 0.5))
33
+ throw new RangeError(`'${name}' must be a single number in (0, 0.5)`);
34
+ }
35
+ /**
36
+ * Two one-sided t tests (TOST) of equivalence of two means. Equivalent to `equivalence::tost()` in R.
37
+ *
38
+ * Equivalence, |mean(x) - mean(y)| < epsilon, is shown at level alpha = 1 - confLevel when both one-sided t tests of
39
+ * H01: d <= -epsilon and H02: d >= epsilon reject; the p-value is the larger of their p-values and `confInt` the dual
40
+ * 1 - 2 alpha interval (90% for the default `confLevel` 0.95). The difference, standard error and degrees of freedom are
41
+ * those of {@link tTest} (Welch's by default, pooled with `varEqual`, paired with `paired`), with tTest's checks and
42
+ * errors. Used on 0/1 data it compares two proportions with a t approximation; for counts
43
+ * {@link binomDiffEquivalenceTest} is the better test.
44
+ *
45
+ * Unlike R, a level of 0.5 or less (`confLevel`) or of 0.5 or more (`alpha`) is an error (the interval would be empty),
46
+ * and so is a margin that is not positive.
47
+ *
48
+ * @param x Sample.
49
+ * @param y Second sample.
50
+ * @param options See {@link TostOptions}.
51
+ * @returns See {@link TostResult}.
52
+ * @throws RangeError for a margin that is not positive and finite or a level out of range; Error where tTest has
53
+ * too few observations or the data are essentially constant.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const r = tost([5.1, 4.9, 5.6, 5.8, 6.0, 5.4], [5.3, 5.0, 5.5, 5.7, 5.9, 5.2], { epsilon: 0.5 });
58
+ * r.pValue; // 0.029694342816029128
59
+ * r.confInt; // [-0.36394177233776226, 0.4306084390044287] (a 90% interval)
60
+ * r.result; // "rejected"
61
+ * ```
62
+ *
63
+ * @category Hypothesis tests
64
+ */
65
+ export function tost(x, y, options = {}) {
66
+ checkOptions(options, TOST_KEYS, "tost"); // generated: option-keys.mjs
67
+ const epsilon = options.epsilon ?? 1;
68
+ if (!(typeof epsilon === "number" && epsilon > 0 && epsilon < Infinity))
69
+ throw new RangeError("'epsilon' must be a positive number");
70
+ let confLevel;
71
+ // the upper tail probability of the t quantile: alpha itself where given (1 - confLevel would lose its digits)
72
+ let tail;
73
+ if (options.alpha !== undefined) {
74
+ // as R, alpha overrides conf.level
75
+ checkAlpha(options.alpha, "alpha");
76
+ confLevel = 1 - options.alpha;
77
+ tail = options.alpha;
78
+ }
79
+ else {
80
+ confLevel = options.confLevel ?? 0.95;
81
+ checkConfLevelOpen(confLevel);
82
+ if (!(confLevel > 0.5))
83
+ throw new RangeError("'confLevel' must be greater than 0.5");
84
+ tail = 1 - confLevel;
85
+ }
86
+ if (y === undefined)
87
+ throw new TypeError("'y' is required");
88
+ const paired = options.paired ?? false;
89
+ const varEqual = options.varEqual ?? false;
90
+ const t = unreported(() => tTest(x, y, { paired, varEqual }));
91
+ const se = t.stdErr;
92
+ const df = t.parameter;
93
+ const d = typeof t.estimate === "number" ? t.estimate : t.estimate[0] - t.estimate[1];
94
+ const pValue = pt1((epsilon - Math.abs(d)) / se, df, false, false);
95
+ // (rule 10: for a tail below 1e-8 the upper tail itself; at alpha = 1e-12 and 8 df the quantile from 1 - alpha was
96
+ // 69.69523624766852 for 69.69504323785972, as 1 - alpha has lost its digits)
97
+ const q = tail < 1e-8 ? qt1(tail, df, false, false) : qt1(confLevel, df, true, false);
98
+ const confInt = [d - q * se, d + q * se];
99
+ return reported("tost", {
100
+ method: t.method.replace("t-test", "TOST"),
101
+ parameter: df,
102
+ parameterName: "df",
103
+ pValue,
104
+ result: confInt[0] > -epsilon && confInt[1] < epsilon ? "rejected" : "not rejected",
105
+ confInt,
106
+ confLevel,
107
+ estimate: t.estimate,
108
+ // equivalence::tost names a paired estimate "mean of the differences" (tTest, as R's t.test, "mean difference")
109
+ estimateNames: paired ? "mean of the differences" : t.estimateNames,
110
+ epsilon,
111
+ seDiff: se,
112
+ warnings: [],
113
+ });
114
+ }
115
+ const EQUIVALENCE_METHODS = ["mn", "mee", "wald"];
116
+ /**
117
+ * Test of equivalence of two independent proportions x1/n1 and x2/n2 within a margin. Two one-sided tests of
118
+ * H01: p1 - p2 <= -margin and H02: p1 - p2 >= margin, each at level `alpha`; equivalence is shown when both reject.
119
+ * Not an R function. (The R packages in scope give the dual intervals, `DescTools::BinomDiffCI`, or test one bound at
120
+ * a time.)
121
+ *
122
+ * The statistic at a bound delta0 is z = (p1 - p2 - delta0) / sqrt(var), with var the variance of p1 - p2 at the
123
+ * maximum likelihood estimate of (p1, p2) under p1 - p2 = delta0 (Farrington and Manning 1990, `"mee"`), the same times
124
+ * N/(N - 1) (Miettinen and Nurminen 1985, `"mn"`, the default), or at the observed proportions (`"wald"`). The
125
+ * p-values are normal tails. The test is dual to {@link binomDiffCI} with the same method at the level 1 - 2 alpha:
126
+ * equivalence is shown exactly when that interval, returned as `confInt`, lies inside (-margin, margin).
127
+ *
128
+ * The Wald variance is 0 when both proportions are 0 or 1: the statistics are then infinite and the p-values 0 or 1,
129
+ * as binomDiffCI's Wald interval is a point there.
130
+ *
131
+ * @param x1 Successes in group 1.
132
+ * @param n1 Trials in group 1.
133
+ * @param x2 Successes in group 2.
134
+ * @param n2 Trials in group 2.
135
+ * @param options See {@link BinomDiffEquivalenceTestOptions}; `margin` is required.
136
+ * @returns See {@link BinomDiffEquivalenceTestResult}.
137
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a margin outside (0, 1), alpha
138
+ * outside (0, 0.5), or an unknown method.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const r = binomDiffEquivalenceTest(80, 100, 78, 100, { margin: 0.15 });
143
+ * r.pValues; // [0.0018937433499954864, 0.012899725361675841]
144
+ * r.pValue; // 0.012899725361675841
145
+ * r.confInt; // [-0.07557697533608577, 0.11553638647686569] (binomDiffCI, method "mn", 90%)
146
+ * r.result; // "rejected"
147
+ * ```
148
+ *
149
+ * @category Hypothesis tests
150
+ */
151
+ export function binomDiffEquivalenceTest(x1, n1, x2, n2, options = {}) {
152
+ checkOptions(options, BINOM_DIFF_EQUIVALENCE_TEST_KEYS, "binomDiffEquivalenceTest"); // generated: option-keys.mjs
153
+ const method = matchChoice(options.method, EQUIVALENCE_METHODS);
154
+ const margin = options.margin;
155
+ if (margin === undefined)
156
+ throw new TypeError("'margin' is required");
157
+ if (!(typeof margin === "number" && margin > 0 && margin < 1))
158
+ throw new RangeError("'margin' must be a single number in (0, 1)");
159
+ const alpha = options.alpha ?? 0.05;
160
+ checkAlpha(alpha, "alpha");
161
+ const [a1, m1] = checkTrials(x1, n1, "x1", "n1");
162
+ const [a2, m2] = checkTrials(x2, n2, "x2", "n2");
163
+ const est = a1 / m1 - a2 / m2;
164
+ // z at delta0 = -+margin, written as diffStatistic's deviation (p1 - p2 - delta0); the variance is positive for the
165
+ // score methods (the restricted MLE cannot put both proportions at 0 or 1 when 0 < |delta0| < 1)
166
+ const z = (delta0) => diffDeviation(a1, m1, a2, m2, delta0) / Math.sqrt(diffVariance(a1, m1, a2, m2, delta0, method));
167
+ const zLower = z(-margin);
168
+ const zUpper = z(margin);
169
+ const pValues = [pnorm(zLower, { lowerTail: false }), pnorm(zUpper)];
170
+ const pValue = Math.max(pValues[0], pValues[1]);
171
+ const confLevel = 1 - 2 * alpha;
172
+ // binomDiffCI's interval at 1 - 2 alpha, from 2 alpha itself (alpha taken back as 1 - confLevel is about
173
+ // eps / (2 alpha) relative off, and loses the level's digits for tiny alpha)
174
+ const confInt = binomDiffLimits(a1, m1, a2, m2, method, levelOfAlpha(2 * alpha, confLevel));
175
+ return reported("binomDiffEquivalenceTest", {
176
+ method,
177
+ estimate: est,
178
+ margin,
179
+ alpha,
180
+ statistic: [zLower, zUpper],
181
+ statisticName: "z",
182
+ pValues,
183
+ pValue,
184
+ result: pValues[0] < alpha && pValues[1] < alpha ? "rejected" : "not rejected",
185
+ confInt,
186
+ confLevel,
187
+ warnings: [],
188
+ });
189
+ }
@@ -24,6 +24,13 @@ export interface FisherTestOptions {
24
24
  simulatePValue?: boolean;
25
25
  /** Number of replicates for `simulatePValue`. Default `2000`. */
26
26
  B?: number;
27
+ /**
28
+ * The mid-p version of the test of a 2 x 2 table (as `exact2x2::fisher.exact(x, midp = TRUE)`): the p-value and the
29
+ * confidence limits from the mid-p tails P(X < x) + P(X = x)/2 and P(X > x) + P(X = x)/2 of the (1, 1) cell; the
30
+ * two-sided p-value is twice the smaller tail (the central test) and the estimate stays the conditional MLE. An error
31
+ * for larger tables. Default `false`.
32
+ */
33
+ midp?: boolean;
27
34
  }
28
35
  /**
29
36
  * Result of {@link fisherTest}. Has no `statistic` or `statisticName`, because R's
@@ -49,6 +56,11 @@ export interface FisherTestResult extends Omit<HTest, "statistic" | "statisticNa
49
56
  * With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
50
57
  * observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
51
58
  *
59
+ * With `midp: true` (2 x 2 only), the mid-p version of exact2x2's `fisher.exact()`: the p-value and the interval come
60
+ * from the mid-p tails (two-sided: the central test, twice the smaller tail, at most 1), the limits are the roots of
61
+ * the mid-p tails to the precision of the doubles (exact2x2's search stops up to 1% from them), and `method` is
62
+ * `"Central Fisher's Exact Test (mid-p version)"` or `"One-sided Fisher's Exact Test (mid-p version)"`.
63
+ *
52
64
  * Not implemented: R's `hybrid` option.
53
65
  *
54
66
  * @param x Contingency table as an array of rows (at least 2 x 2).
@@ -61,8 +73,45 @@ export interface FisherTestResult extends Omit<HTest, "statistic" | "statisticNa
61
73
  * r.pValue; // 0.4857142857142857
62
74
  * r.estimate; // 6.408319658199675 (conditional MLE of the odds ratio; R: 6.408309)
63
75
  * r.confInt; // [0.2117355954465785, 626.2435305888127] (R: 0.2117329, 621.93)
76
+ * const m = fisherTest([[3, 1], [1, 3]], { midp: true });
77
+ * m.pValue; // 0.2571428571428571
78
+ * m.confInt; // [0.31005488171907974, 308.5567715811547] (exact2x2: 0.3100451, 311.4363)
64
79
  * ```
65
80
  *
66
81
  * @category Hypothesis tests
67
82
  */
68
83
  export declare function fisherTest(x: readonly Counts[], options?: FisherTestOptions): FisherTestResult;
84
+ /**
85
+ * Fisher's noncentral hypergeometric distribution of the (1, 1) cell of a 2 x 2 table with margins fixed:
86
+ * P(X = i; psi) proportional to dhyper(i; m, n, k) psi^i on lo..hi
87
+ */
88
+ export declare class OddsRatioDistribution {
89
+ private readonly m;
90
+ private readonly n;
91
+ private readonly k;
92
+ readonly lo: number;
93
+ readonly hi: number;
94
+ /** log dhyper(i; m, n, k) for i = lo..hi */
95
+ private readonly logCentral;
96
+ constructor(m: number, n: number, k: number);
97
+ /** Normalised density on lo..hi for 0 < psi < Infinity */
98
+ density(psi: number): Float64Array;
99
+ /** E[X; psi] */
100
+ mean(psi: number): number;
101
+ /** P(X <= q; psi), or P(X >= q; psi) when upper */
102
+ tail(q: number, psi: number, upper: boolean): number;
103
+ /** The mid-p tail P(X < q; psi) + P(X = q; psi)/2, or P(X > q; psi) + P(X = q; psi)/2 when upper (lo <= q <= hi) */
104
+ midTail(q: number, psi: number, upper: boolean): number;
105
+ }
106
+ /**
107
+ * The two-sided p-value of the count x at the odds ratio psi (0 < psi < Infinity): the sum of the probabilities at
108
+ * most P(X = x) (1 + 1e-7), as R
109
+ */
110
+ export declare function twoSidedPValue(dist: OddsRatioDistribution, x: number, psi: number): number;
111
+ /**
112
+ * Fisher's two-sided p-value of the 2 x 2 table with the (1, 1) cell x and the margins m (column 1), n (column 2) and
113
+ * k (row 1), at the odds ratio 1, without the array of the support: the hypergeometric density is unimodal, so the
114
+ * values at most P(X = x) (1 + 1e-7) are the two tails below and above two cut points, found by bisection and summed
115
+ * by phyper. For supports beyond what twoSidedPValue allocates (oddsRatio's p-value of tables with counts of 1e9)
116
+ */
117
+ export declare function twoSidedPValueUnimodal(x: number, m: number, n: number, k: number): number;