@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
+ /**
2
+ * Which limits of a proportion's interval are kept (DescTools' `sides`): `"two.sided"` both, `"left"` the lower one
3
+ * (the upper is the end of the range), `"right"` the upper one.
4
+ *
5
+ * @category Hypothesis tests
6
+ */
7
+ export type CISides = "two.sided" | "left" | "right";
8
+ /**
9
+ * Methods of {@link binomCI}.
10
+ *
11
+ * @category Hypothesis tests
12
+ */
13
+ export type BinomCIMethod = "wilson" | "wald" | "wilsoncc" | "agresti-coull" | "jeffreys" | "clopper-pearson" | "midp";
14
+ /**
15
+ * Options for {@link binomCI}.
16
+ *
17
+ * @category Hypothesis tests
18
+ */
19
+ export interface BinomCIOptions {
20
+ /** The interval: `"wilson"` (default), `"wald"`, `"wilsoncc"`, `"agresti-coull"`, `"jeffreys"`,
21
+ * `"clopper-pearson"` or `"midp"`. Unambiguous abbreviations are accepted. */
22
+ method?: BinomCIMethod | (string & {});
23
+ /** Confidence level, in (0, 1). Default `0.95`. */
24
+ confLevel?: number;
25
+ /** `"two.sided"` (default), `"left"` (lower limit only) or `"right"` (upper limit only); abbreviations accepted. */
26
+ sides?: CISides | (string & {});
27
+ }
28
+ /**
29
+ * A confidence interval for a proportion, a difference or a ratio of proportions.
30
+ *
31
+ * @category Hypothesis tests
32
+ */
33
+ export interface ProportionCIResult<M extends string = string> {
34
+ /** The point estimate. */
35
+ estimate: number;
36
+ /** `[lower, upper]`; with `sides: "left"` the upper end of the range, with `"right"` the lower end. */
37
+ confInt: [number, number];
38
+ /** The confidence level given (of the one-sided limit, for `sides` other than `"two.sided"`). */
39
+ confLevel: number;
40
+ /** The method, in full. */
41
+ method: M;
42
+ /** The sides, in full. */
43
+ sides: CISides;
44
+ /** Warnings (none so far: input without a defined result is an error). */
45
+ warnings: string[];
46
+ }
47
+ /**
48
+ * Result of {@link binomCI}.
49
+ *
50
+ * @category Hypothesis tests
51
+ */
52
+ export type BinomCIResult = ProportionCIResult<BinomCIMethod>;
53
+ /** The level, alpha and kappa = qnorm(1 - alpha/2) of an interval, from the level given and the sides */
54
+ export interface IntervalLevel {
55
+ sides: CISides;
56
+ /** The two-sided level actually used: confLevel, or 1 - 2(1 - confLevel) for one side */
57
+ level: number;
58
+ alpha: number;
59
+ kappa: number;
60
+ /**
61
+ * qchisq(level, 1), the bound of the score statistics. Not kappa^2: 1 - alpha/2 rounds, which moves kappa^2 by up to
62
+ * 1e-11 relative at alpha = 1e-6 (the score intervals of DescTools and epiR use qchisq or solve for alpha itself)
63
+ */
64
+ chisq: number;
65
+ }
66
+ /** Checks the level and sides, and the two-sided level that a one-sided limit is computed at (as DescTools) */
67
+ export declare function intervalLevel(confLevel: number | undefined, sides: string | undefined): IntervalLevel;
68
+ /**
69
+ * The two-sided interval level of a given alpha, for callers that hold alpha itself (a test at 1 - 2 alpha: alpha
70
+ * taken back as 1 - level is about eps / alpha relative off). `level` is 1 - alpha unless given
71
+ */
72
+ export declare function levelOfAlpha(alpha: number, level?: number): IntervalLevel;
73
+ /** A count: a nonnegative integer (within the slack of isCount), returned rounded */
74
+ export declare function checkCount(v: number, name: string): number;
75
+ /** Successes and trials: integers with 0 <= x <= n and n > 0 */
76
+ export declare function checkTrials(x: number, n: number, xName: string, nName: string): [number, number];
77
+ /**
78
+ * Wilson's score limits of x/n at kappa. At x = 0 the lower limit and at x = n the upper are exactly 0 and 1 (the
79
+ * formula gives them up to rounding: DescTools' upper limit of 10/10 at the 50% level is 0.99999999999999989).
80
+ * The limits are the roots of (n + kappa^2) p^2 - (2x + kappa^2) p + x^2/n = 0. Where centre - half cancels (more than
81
+ * half of the centre, small x or a level close to 1) the lower limit is taken from the product of the roots,
82
+ * x^2 / (n (n + kappa^2)), divided by the upper: centre - half loses digits in proportion to centre / lower (350 eps
83
+ * at 1/1e15 and the level 1 - 2^-53, 28 eps for wilsoncc at 1/1000 and 95%; DescTools has the same digits)
84
+ */
85
+ export declare function wilsonLimits(x: number, n: number, kappa: number): [number, number];
86
+ /**
87
+ * Confidence interval for a binomial proportion x/n. Equivalent to `DescTools::BinomCI()` in R.
88
+ *
89
+ * Methods (`method`): `"wilson"` (the default, Wilson's score interval), `"wald"`, `"wilsoncc"` (with continuity
90
+ * correction), `"agresti-coull"`, `"jeffreys"`, `"clopper-pearson"` (the exact interval) and `"midp"` (the mid-p exact
91
+ * interval). With `sides: "left"` or `"right"` only the lower or the upper limit is kept, at the one-sided level
92
+ * `confLevel` (the two-sided interval at `1 - 2 (1 - confLevel)`), and the other end is 0 or 1. Limits are clipped to
93
+ * [0, 1].
94
+ *
95
+ * The mid-p limits are the roots of their equations to the precision of the doubles; DescTools stops its search at
96
+ * an absolute 1.22e-4, which leaves its limits up to 1e-4 off and gives 0 for lower limits below that. Unlike
97
+ * DescTools, which returns NaN or numbers, x > n, a negative or non-integer count, n = 0 and a level outside (0, 1)
98
+ * are errors.
99
+ *
100
+ * @param x Number of successes.
101
+ * @param n Number of trials.
102
+ * @param options See {@link BinomCIOptions}.
103
+ * @returns The estimate x/n and the interval; see {@link BinomCIResult}.
104
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a level outside (0, 1) (at least 0.5
105
+ * one-sided), or an unknown method or sides.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * binomCI(37, 100).confInt; // [0.28182360534324535, 0.4677947041905709]
110
+ * binomCI(37, 100, { method: "clopper-pearson" }).confInt; // [0.27556657961455155, 0.4723516405516831]
111
+ * binomCI(1, 1000, { method: "midp", sides: "right" }).confInt; // [0, 0.004106205924199768]
112
+ * ```
113
+ *
114
+ * @category Hypothesis tests
115
+ */
116
+ export declare function binomCI(x: number, n: number, options?: BinomCIOptions): BinomCIResult;
@@ -0,0 +1,252 @@
1
+ // Confidence intervals for one binomial proportion (DescTools' BinomCI), for one case per call.
2
+ //
3
+ // Written for rStats.js from the published intervals and DescTools' documented behaviour (no R or package code): the
4
+ // level of a one-sided interval ("left": [lower, 1], "right": [0, upper]) is that of the two-sided interval at
5
+ // 1 - 2(1 - confLevel); kappa = qnorm(1 - alpha/2).
6
+ // - wald: p ∓ kappa sqrt(p q / n)
7
+ // - wilson (Wilson, JASA 22, 1927): (x + kappa^2/2)/(n + kappa^2) ∓ kappa sqrt(n)/(n + kappa^2) sqrt(p q + kappa^2/(4n))
8
+ // - wilsoncc: Wilson's interval with continuity correction (Newcombe, Statistics in Medicine 17, 1998, method 4)
9
+ // - agresti-coull (Agresti and Coull, The American Statistician 52, 1998): the Wald interval of
10
+ // (x + kappa^2/2)/(n + kappa^2) with n + kappa^2 trials
11
+ // - jeffreys: the equal-tailed interval of the Beta(x + 1/2, n - x + 1/2) posterior (Brown, Cai and DasGupta,
12
+ // Statistical Science 16, 2001), 0 at x = 0 and 1 at x = n
13
+ // - clopper-pearson (Clopper and Pearson, Biometrika 26, 1934): beta quantiles of the exact binomial tails
14
+ // - midp: the p with 1/2 P(X = x) + P(X > x) = alpha/2 (lower) and 1/2 P(X = x) + P(X < x) = alpha/2 (upper) (Lancaster,
15
+ // JASA 56, 1961; Agresti and Gottard, Statistical Science 20, 2005), solved on the log scale of p to the precision of
16
+ // the doubles; closed forms alpha^(1/n) and 1 - alpha^(1/n) at x = n and x = 0. DescTools solves with uniroot's
17
+ // tolerance 1.22e-4 (absolute), which leaves its limits 1e-6 to 1e-4 off and those below 1e-4 grossly wrong.
18
+ // Limits are clipped to [0, 1]. Counts must be integers with 0 <= x <= n, n > 0; the level must lie in (0, 1) and,
19
+ // one-sided, give a two-sided level 1 - 2(1 - confLevel) >= 0.
20
+ import { dbinom1, pbinom1 } from "../distributions/binomial.js";
21
+ import { qbeta1 } from "../distributions/beta.js";
22
+ import { qchisq } from "../distributions/chisq.js";
23
+ import { qnorm } from "../distributions/normal.js";
24
+ import { uniroot } from "../internal/uniroot.js";
25
+ import { reported } from "../internal/warnings.js";
26
+ import { matchChoice } from "./power.js";
27
+ import { isCount } from "./types.js";
28
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
29
+ import { checkOptions } from "../internal/checkOptions.js";
30
+ const BINOM_CI_KEYS = ["method", "confLevel", "sides"];
31
+ const BINOM_CI_METHODS = ["wilson", "wald", "wilsoncc", "agresti-coull", "jeffreys", "clopper-pearson", "midp"];
32
+ const SIDES = ["two.sided", "left", "right"];
33
+ /** Checks the level and sides, and the two-sided level that a one-sided limit is computed at (as DescTools) */
34
+ export function intervalLevel(confLevel, sides) {
35
+ const s = matchChoice(sides, SIDES);
36
+ const c = confLevel ?? 0.95;
37
+ if (!(typeof c === "number" && c > 0 && c < 1))
38
+ throw new RangeError("'confLevel' must be a single number in (0, 1)");
39
+ const level = s === "two.sided" ? c : 1 - 2 * (1 - c);
40
+ if (!(level >= 0))
41
+ throw new RangeError("a one-sided 'confLevel' must be at least 0.5");
42
+ // one-sided with alpha/2 below 1e-8 (rule 10), alpha from c (1 - c is exact for c >= 1/2), not from the rounded
43
+ // level; otherwise 1 - level as DescTools
44
+ const alpha = s !== "two.sided" && 1 - c < 1e-8 ? 2 * (1 - c) : 1 - level;
45
+ return { ...levelOfAlpha(alpha, level), sides: s };
46
+ }
47
+ /**
48
+ * The two-sided interval level of a given alpha, for callers that hold alpha itself (a test at 1 - 2 alpha: alpha
49
+ * taken back as 1 - level is about eps / alpha relative off). `level` is 1 - alpha unless given
50
+ */
51
+ export function levelOfAlpha(alpha, level = 1 - alpha) {
52
+ // (rule 10: for alpha/2 below 1e-8 the upper tails themselves, as 1 - alpha/2 and the level have lost their digits)
53
+ const small = alpha / 2 < 1e-8;
54
+ const kappa = small ? qnorm(alpha / 2, { lowerTail: false }) : qnorm(1 - alpha / 2);
55
+ const chisq = small ? qchisq(alpha, 1, { lowerTail: false }) : qchisq(level, 1);
56
+ return { sides: "two.sided", level, alpha, kappa, chisq };
57
+ }
58
+ /** A count: a nonnegative integer (within the slack of isCount), returned rounded */
59
+ export function checkCount(v, name) {
60
+ if (typeof v !== "number")
61
+ throw new TypeError(`'${name}' must be a number`);
62
+ if (!isCount(v))
63
+ throw new RangeError(`'${name}' must be a nonnegative integer`);
64
+ // (+ 0 turns -0 into 0, which would otherwise reach an estimate or a limit as -0)
65
+ return Math.round(v) + 0;
66
+ }
67
+ /** Successes and trials: integers with 0 <= x <= n and n > 0 */
68
+ export function checkTrials(x, n, xName, nName) {
69
+ const xs = checkCount(x, xName);
70
+ const ns = checkCount(n, nName);
71
+ if (ns === 0)
72
+ throw new RangeError(`'${nName}' must be positive`);
73
+ if (ns > 2 ** 53)
74
+ throw new RangeError(`'${nName}' must be at most 2^53`);
75
+ if (xs > ns)
76
+ throw new RangeError(`'${xName}' must not be greater than '${nName}'`);
77
+ return [xs, ns];
78
+ }
79
+ /**
80
+ * Wilson's score limits of x/n at kappa. At x = 0 the lower limit and at x = n the upper are exactly 0 and 1 (the
81
+ * formula gives them up to rounding: DescTools' upper limit of 10/10 at the 50% level is 0.99999999999999989).
82
+ * The limits are the roots of (n + kappa^2) p^2 - (2x + kappa^2) p + x^2/n = 0. Where centre - half cancels (more than
83
+ * half of the centre, small x or a level close to 1) the lower limit is taken from the product of the roots,
84
+ * x^2 / (n (n + kappa^2)), divided by the upper: centre - half loses digits in proportion to centre / lower (350 eps
85
+ * at 1/1e15 and the level 1 - 2^-53, 28 eps for wilsoncc at 1/1000 and 95%; DescTools has the same digits)
86
+ */
87
+ export function wilsonLimits(x, n, kappa) {
88
+ const p = x / n;
89
+ const q = 1 - p;
90
+ const k2 = kappa * kappa;
91
+ const centre = (x + k2 / 2) / (n + k2);
92
+ const half = ((kappa * Math.sqrt(n)) / (n + k2)) * Math.sqrt(p * q + k2 / (4 * n));
93
+ const up = centre + half;
94
+ let lower = centre - half;
95
+ if (x === 0)
96
+ lower = 0;
97
+ else if (lower < centre / 2)
98
+ lower = (p * (x / (n + k2))) / up;
99
+ return [lower, x === n ? 1 : up];
100
+ }
101
+ /** qbeta at alpha/2 in the lower or the upper tail (from the upper tail itself where alpha/2 < 1e-8, rule 10) */
102
+ function betaLimit(alpha, a, b, upper) {
103
+ if (!upper)
104
+ return qbeta1(alpha / 2, a, b, true, false);
105
+ return alpha / 2 < 1e-8 ? qbeta1(alpha / 2, a, b, false, false) : qbeta1(1 - alpha / 2, a, b, true, false);
106
+ }
107
+ /**
108
+ * The mid-p limit of x/n (0 < x < n): for the lower limit the p with 1/2 P(X = x) + P(X > x) = alpha/2 (increasing in
109
+ * p), for the upper the p with 1/2 P(X = x) + P(X < x) = alpha/2 (decreasing). Solved in u = log p by Brent's method,
110
+ * from a bracket widened from the estimate x/n
111
+ */
112
+ function midpLimit(x, n, alpha, upper) {
113
+ const half = alpha / 2;
114
+ const g = upper
115
+ ? (u) => {
116
+ const p = Math.exp(u);
117
+ return 0.5 * dbinom1(x, n, p, false) + pbinom1(x - 1, n, p, true, false) - half;
118
+ }
119
+ : (u) => {
120
+ const p = Math.exp(u);
121
+ return 0.5 * dbinom1(x, n, p, false) + pbinom1(x, n, p, false, false) - half;
122
+ };
123
+ // g increases in u for the lower limit and decreases for the upper; sign s makes it increasing
124
+ const s = upper ? -1 : 1;
125
+ const u0 = Math.log(x / n);
126
+ const g0 = s * g(u0);
127
+ if (g0 === 0)
128
+ return x / n;
129
+ if (g0 > 0) {
130
+ // the root lies below u0: widen downwards
131
+ let hi = u0;
132
+ let gHi = g0;
133
+ let step = 1;
134
+ for (;;) {
135
+ const lo = u0 - step;
136
+ if (lo < -745)
137
+ return 0;
138
+ const gLo = s * g(lo);
139
+ if (gLo <= 0) {
140
+ if (gLo === 0)
141
+ return Math.exp(lo);
142
+ return Math.exp(uniroot((u) => s * g(u), lo, hi, { tol: 2 ** -60, fLower: gLo, fUpper: gHi }));
143
+ }
144
+ hi = lo;
145
+ gHi = gLo;
146
+ step *= 2;
147
+ }
148
+ }
149
+ // the root lies between u0 and 0 (p = 1, where s g > 0 for 0 < x < n)
150
+ const g1 = s * g(0);
151
+ if (g1 <= 0)
152
+ return 1;
153
+ return Math.exp(uniroot((u) => s * g(u), u0, 0, { tol: 2 ** -60, fLower: g0, fUpper: g1 }));
154
+ }
155
+ /**
156
+ * Confidence interval for a binomial proportion x/n. Equivalent to `DescTools::BinomCI()` in R.
157
+ *
158
+ * Methods (`method`): `"wilson"` (the default, Wilson's score interval), `"wald"`, `"wilsoncc"` (with continuity
159
+ * correction), `"agresti-coull"`, `"jeffreys"`, `"clopper-pearson"` (the exact interval) and `"midp"` (the mid-p exact
160
+ * interval). With `sides: "left"` or `"right"` only the lower or the upper limit is kept, at the one-sided level
161
+ * `confLevel` (the two-sided interval at `1 - 2 (1 - confLevel)`), and the other end is 0 or 1. Limits are clipped to
162
+ * [0, 1].
163
+ *
164
+ * The mid-p limits are the roots of their equations to the precision of the doubles; DescTools stops its search at
165
+ * an absolute 1.22e-4, which leaves its limits up to 1e-4 off and gives 0 for lower limits below that. Unlike
166
+ * DescTools, which returns NaN or numbers, x > n, a negative or non-integer count, n = 0 and a level outside (0, 1)
167
+ * are errors.
168
+ *
169
+ * @param x Number of successes.
170
+ * @param n Number of trials.
171
+ * @param options See {@link BinomCIOptions}.
172
+ * @returns The estimate x/n and the interval; see {@link BinomCIResult}.
173
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a level outside (0, 1) (at least 0.5
174
+ * one-sided), or an unknown method or sides.
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * binomCI(37, 100).confInt; // [0.28182360534324535, 0.4677947041905709]
179
+ * binomCI(37, 100, { method: "clopper-pearson" }).confInt; // [0.27556657961455155, 0.4723516405516831]
180
+ * binomCI(1, 1000, { method: "midp", sides: "right" }).confInt; // [0, 0.004106205924199768]
181
+ * ```
182
+ *
183
+ * @category Hypothesis tests
184
+ */
185
+ export function binomCI(x, n, options = {}) {
186
+ checkOptions(options, BINOM_CI_KEYS, "binomCI"); // generated: option-keys.mjs
187
+ const method = matchChoice(options.method, BINOM_CI_METHODS);
188
+ const lv = intervalLevel(options.confLevel, options.sides);
189
+ const [xs, ns] = checkTrials(x, n, "x", "n");
190
+ const { alpha, kappa } = lv;
191
+ const p = xs / ns;
192
+ const q = 1 - p;
193
+ let lower;
194
+ let upper;
195
+ switch (method) {
196
+ case "wald": {
197
+ const half = kappa * Math.sqrt((p * q) / ns);
198
+ [lower, upper] = [p - half, p + half];
199
+ break;
200
+ }
201
+ case "wilson":
202
+ [lower, upper] = wilsonLimits(xs, ns, kappa);
203
+ break;
204
+ case "wilsoncc": {
205
+ const k2 = kappa * kappa;
206
+ const den = 2 * (ns + k2);
207
+ // the lower limit is the smaller root of (n + kappa^2) L^2 - (2x + kappa^2 - 1) L + (2x - 1)^2 / (4n) = 0;
208
+ // where the difference cancels (more than half of the larger term) it is taken from the product of the roots
209
+ // as (2x - 1)^2 / (2n (2x + kappa^2 - 1 + kappa sqrt(...))), without cancellation (as wilsonLimits)
210
+ const bl = 2 * xs + k2 - 1;
211
+ const rl = kappa * Math.sqrt(k2 - 2 - 1 / ns + 4 * p * (ns * q + 1));
212
+ lower = p === 0 ? 0 : bl - rl < bl / 2 ? (((2 * xs - 1) / (2 * ns)) * (2 * xs - 1)) / (bl + rl) : (bl - rl) / den;
213
+ upper = p === 1 ? 1 : (2 * xs + k2 + 1 + kappa * Math.sqrt(k2 + 2 - 1 / ns + 4 * p * (ns * q - 1))) / den;
214
+ break;
215
+ }
216
+ case "agresti-coull": {
217
+ const k2 = kappa * kappa;
218
+ const nt = ns + k2;
219
+ const pt = (xs + k2 / 2) / nt;
220
+ const half = kappa * Math.sqrt((pt * (1 - pt)) / nt);
221
+ [lower, upper] = [pt - half, pt + half];
222
+ break;
223
+ }
224
+ case "jeffreys":
225
+ lower = xs === 0 ? 0 : betaLimit(alpha, xs + 0.5, ns - xs + 0.5, false);
226
+ upper = xs === ns ? 1 : betaLimit(alpha, xs + 0.5, ns - xs + 0.5, true);
227
+ break;
228
+ case "clopper-pearson":
229
+ lower = xs === 0 ? 0 : betaLimit(alpha, xs, ns - xs + 1, false);
230
+ upper = xs === ns ? 1 : betaLimit(alpha, xs + 1, ns - xs, true);
231
+ break;
232
+ case "midp":
233
+ // closed forms at the ends: 1/2 p^n = alpha/2 and 1/2 (1 - p)^n = alpha/2
234
+ lower = xs === 0 ? 0 : xs === ns ? Math.exp(Math.log(alpha) / ns) : midpLimit(xs, ns, alpha, false);
235
+ upper = xs === ns ? 1 : xs === 0 ? -Math.expm1(Math.log(alpha) / ns) : midpLimit(xs, ns, alpha, true);
236
+ break;
237
+ }
238
+ lower = Math.max(0, lower);
239
+ upper = Math.min(1, upper);
240
+ if (lv.sides === "left")
241
+ upper = 1;
242
+ else if (lv.sides === "right")
243
+ lower = 0;
244
+ return reported("binomCI", {
245
+ estimate: p,
246
+ confInt: [lower, upper],
247
+ confLevel: options.confLevel ?? 0.95,
248
+ method,
249
+ sides: lv.sides,
250
+ warnings: [],
251
+ });
252
+ }
@@ -0,0 +1,100 @@
1
+ import { type Sample } from "./types.js";
2
+ /**
3
+ * Interval of the limits of agreement in {@link blandAltman}.
4
+ *
5
+ * @category Agreement, reliability and factor analysis
6
+ */
7
+ export type BlandAltmanCiMethod = "package" | "exact";
8
+ /**
9
+ * Options for {@link blandAltman}.
10
+ *
11
+ * @category Agreement, reliability and factor analysis
12
+ */
13
+ export interface BlandAltmanOptions {
14
+ /** The multiple of the standard deviation of the differences in the limits of agreement, positive. Default `1.96`. */
15
+ two?: number;
16
+ /** `1` for the differences `x - y` (the default), `2` for `y - x`. */
17
+ mode?: 1 | 2;
18
+ /** Level of the confidence intervals, in [0, 1] (two-sided). Default `0.95`. */
19
+ confLevel?: number;
20
+ /**
21
+ * Interval of the two limits of agreement: `"package"` (the default), BlandAltmanLeh's `limit ± t sqrt(3 s²/n)` with
22
+ * t quantiles on n - 1 degrees of freedom (Bland and Altman 1986's approximation), or `"exact"`, the exact interval
23
+ * from the noncentral t distribution (Carkeet 2015), wider for small n. Unambiguous abbreviations are accepted.
24
+ */
25
+ ciMethod?: BlandAltmanCiMethod | (string & {});
26
+ }
27
+ /**
28
+ * Result of {@link blandAltman}.
29
+ *
30
+ * @category Agreement, reliability and factor analysis
31
+ */
32
+ export interface BlandAltmanResult {
33
+ /** The mean of each complete pair, `(x + y)/2` (R's `means`). */
34
+ means: number[];
35
+ /** The difference of each complete pair, `x - y` (mode 1) or `y - x` (mode 2) (R's `diffs`). */
36
+ diffs: number[];
37
+ /** Number of complete pairs (R's `based.on`). */
38
+ n: number;
39
+ /** Mean of the differences d̄ (R's `mean.diffs`). */
40
+ meanDiff: number;
41
+ /** Lower limit of agreement `d̄ - two s` (R's `lower.limit`). */
42
+ lowerLimit: number;
43
+ /** Upper limit of agreement `d̄ + two s` (R's `upper.limit`). */
44
+ upperLimit: number;
45
+ /** `two s`, s the standard deviation of the differences (R's `critical.diff`). */
46
+ criticalDiff: number;
47
+ /** t interval of the mean difference, `d̄ ± t s/sqrt(n)` (R's `mean.diff.ci.lower`, `.upper`). */
48
+ meanDiffConfInt: [number, number];
49
+ /** Interval of the lower limit of agreement (R's `lower.limit.ci.lower`, `.upper` for `ciMethod: "package"`). */
50
+ lowerLimitConfInt: [number, number];
51
+ /** Interval of the upper limit of agreement (R's `upper.limit.ci.lower`, `.upper` for `ciMethod: "package"`). */
52
+ upperLimitConfInt: [number, number];
53
+ /** The level of the intervals. */
54
+ confLevel: number;
55
+ /** The multiple of the standard deviation in the limits (R's `two`). */
56
+ two: number;
57
+ /** The direction of the differences, 1 or 2. */
58
+ mode: 1 | 2;
59
+ /** The interval of the limits, in full. */
60
+ ciMethod: BlandAltmanCiMethod;
61
+ /** Warnings (none: input without a defined result is an error). */
62
+ warnings: string[];
63
+ }
64
+ /**
65
+ * Bland-Altman analysis of two methods of measurement: the mean difference, the limits of agreement and their
66
+ * confidence intervals. Equivalent to `BlandAltmanLeh::bland.altman.stats()` in R.
67
+ *
68
+ * With d the differences of the complete pairs (pairs with `NaN` in either sample are dropped), d̄ their mean and s
69
+ * their standard deviation, the limits of agreement are `d̄ ± two s`. The mean difference has the t interval `d̄ ± t
70
+ * s/sqrt(n)` with t quantiles on n - 1 degrees of freedom. The interval of each limit is, by default, BlandAltmanLeh's
71
+ * `limit ± t sqrt(3 s²/n)` (Bland and Altman 1986); `ciMethod: "exact"` gives the exact interval (Carkeet 2015):
72
+ * `d̄ + s q/sqrt(n)` for the upper limit with q the quantiles (1 ∓ confLevel)/2 of the noncentral t distribution with
73
+ * n - 1 degrees of freedom and noncentrality `two sqrt(n)`, and its mirror image for the lower limit.
74
+ *
75
+ * Unlike R, fewer than 2 complete pairs, infinite values and a level outside [0, 1] are errors (R gives NA or NaN
76
+ * limits); `confLevel` 0 gives intervals of width 0 and 1 infinite ones, as R. Identical methods (s = 0) give every
77
+ * limit and interval equal to d̄.
78
+ *
79
+ * @param x Measurements by the first method.
80
+ * @param y Measurements by the second method, paired with `x`.
81
+ * @param options See {@link BlandAltmanOptions}.
82
+ * @returns See {@link BlandAltmanResult}.
83
+ * @throws TypeError if `x` and `y` differ in length; RangeError for fewer than 2 complete pairs, infinite values, a
84
+ * `two` that is not positive and finite, a `mode` other than 1 or 2, a level outside [0, 1] or an unknown
85
+ * `ciMethod`.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * const x = [10.1, 12.3, 9.8, 15.2, 11.1, 13.4, 14.8, 9.9, 12.0, 16.3];
90
+ * const y = [10.6, 12.0, 10.4, 15.9, 11.0, 14.1, 15.3, 10.3, 12.9, 16.8];
91
+ * const r = blandAltman(x, y);
92
+ * r.meanDiff; // -0.44000000000000006
93
+ * [r.lowerLimit, r.upperLimit]; // [-1.1628122854517629, 0.28281228545176262]
94
+ * r.upperLimitConfInt; // [-0.17412106328886995, 0.73974563419239514]
95
+ * blandAltman(x, y, { ciMethod: "exact" }).upperLimitConfInt; // [-0.011029811389107025, 0.961726537758047]
96
+ * ```
97
+ *
98
+ * @category Agreement, reliability and factor analysis
99
+ */
100
+ export declare function blandAltman(x: Sample, y: Sample, options?: BlandAltmanOptions): BlandAltmanResult;
@@ -0,0 +1,159 @@
1
+ // Bland-Altman analysis of the agreement of two methods of measurement: the mean difference, the limits of agreement
2
+ // d̄ ± two·s and their confidence intervals, as BlandAltmanLeh's bland.altman.stats, with the exact interval of the
3
+ // limits as an alternative.
4
+ //
5
+ // Written for rStats.js from oracle/methodcomparison-behaviour.md (section 1) and the published methods (no R or
6
+ // package code was read):
7
+ // - Bland JM, Altman DG (1986), Statistical methods for assessing agreement between two methods of clinical
8
+ // measurement, Lancet i:307-310: the limits d̄ ± 1.96 s, the t interval of the mean difference, and the standard
9
+ // error sqrt(3 s²/n) of a limit (an approximation of s² (1/n + z²/(2(n - 1))) for z = 1.96 and large n), used with
10
+ // t quantiles ("package", BlandAltmanLeh's interval).
11
+ // - Carkeet A (2015), Exact parametric confidence intervals for Bland-Altman limits of agreement, Optometry and Vision
12
+ // Science 92:e71-e80: sqrt(n) (μ + zσ - d̄)/s has the noncentral t distribution with n - 1 degrees of freedom and
13
+ // noncentrality z sqrt(n), so the exact interval of the upper limit is d̄ + s q/sqrt(n) at the quantiles q of that
14
+ // distribution, and that of the lower limit its mirror image ("exact").
15
+ //
16
+ // The differences are scaled by a power of 2 of their own (src/internal/summary.ts), so that the squares of the
17
+ // standard deviation neither over- nor underflow; results with units are scaled back at the end (exact), so in the
18
+ // ordinary range they are those of the unscaled formulas.
19
+ import { qnt1 } from "../distributions/nt.js";
20
+ import { qt1 } from "../distributions/t.js";
21
+ import { ldexp, mean, scaleToUnit, standardDeviation } from "../internal/summary.js";
22
+ import { reported } from "../internal/warnings.js";
23
+ import { matchChoice } from "./power.js";
24
+ import { checkConfLevel } from "./types.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 BLAND_ALTMAN_KEYS = ["two", "mode", "confLevel", "ciMethod"];
28
+ const CI_METHODS = ["package", "exact"];
29
+ /** t s, with 0 for s = 0 (identical methods: the intervals are points, also at the level 1 where t is infinite) */
30
+ const times = (t, s) => (s === 0 ? 0 : t * s);
31
+ /**
32
+ * Bland-Altman analysis of two methods of measurement: the mean difference, the limits of agreement and their
33
+ * confidence intervals. Equivalent to `BlandAltmanLeh::bland.altman.stats()` in R.
34
+ *
35
+ * With d the differences of the complete pairs (pairs with `NaN` in either sample are dropped), d̄ their mean and s
36
+ * their standard deviation, the limits of agreement are `d̄ ± two s`. The mean difference has the t interval `d̄ ± t
37
+ * s/sqrt(n)` with t quantiles on n - 1 degrees of freedom. The interval of each limit is, by default, BlandAltmanLeh's
38
+ * `limit ± t sqrt(3 s²/n)` (Bland and Altman 1986); `ciMethod: "exact"` gives the exact interval (Carkeet 2015):
39
+ * `d̄ + s q/sqrt(n)` for the upper limit with q the quantiles (1 ∓ confLevel)/2 of the noncentral t distribution with
40
+ * n - 1 degrees of freedom and noncentrality `two sqrt(n)`, and its mirror image for the lower limit.
41
+ *
42
+ * Unlike R, fewer than 2 complete pairs, infinite values and a level outside [0, 1] are errors (R gives NA or NaN
43
+ * limits); `confLevel` 0 gives intervals of width 0 and 1 infinite ones, as R. Identical methods (s = 0) give every
44
+ * limit and interval equal to d̄.
45
+ *
46
+ * @param x Measurements by the first method.
47
+ * @param y Measurements by the second method, paired with `x`.
48
+ * @param options See {@link BlandAltmanOptions}.
49
+ * @returns See {@link BlandAltmanResult}.
50
+ * @throws TypeError if `x` and `y` differ in length; RangeError for fewer than 2 complete pairs, infinite values, a
51
+ * `two` that is not positive and finite, a `mode` other than 1 or 2, a level outside [0, 1] or an unknown
52
+ * `ciMethod`.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * const x = [10.1, 12.3, 9.8, 15.2, 11.1, 13.4, 14.8, 9.9, 12.0, 16.3];
57
+ * const y = [10.6, 12.0, 10.4, 15.9, 11.0, 14.1, 15.3, 10.3, 12.9, 16.8];
58
+ * const r = blandAltman(x, y);
59
+ * r.meanDiff; // -0.44000000000000006
60
+ * [r.lowerLimit, r.upperLimit]; // [-1.1628122854517629, 0.28281228545176262]
61
+ * r.upperLimitConfInt; // [-0.17412106328886995, 0.73974563419239514]
62
+ * blandAltman(x, y, { ciMethod: "exact" }).upperLimitConfInt; // [-0.011029811389107025, 0.961726537758047]
63
+ * ```
64
+ *
65
+ * @category Agreement, reliability and factor analysis
66
+ */
67
+ export function blandAltman(x, y, options = {}) {
68
+ checkOptions(options, BLAND_ALTMAN_KEYS, "blandAltman"); // generated: option-keys.mjs
69
+ if (x.length !== y.length)
70
+ throw new TypeError("'x' and 'y' must have the same length");
71
+ const two = options.two ?? 1.96;
72
+ if (!(typeof two === "number" && two > 0 && two < Infinity))
73
+ throw new RangeError("'two' must be a positive number");
74
+ const mode = options.mode ?? 1;
75
+ if (mode !== 1 && mode !== 2)
76
+ throw new RangeError("'mode' must be 1 or 2");
77
+ const confLevel = options.confLevel ?? 0.95;
78
+ checkConfLevel(confLevel);
79
+ const ciMethod = matchChoice(options.ciMethod, CI_METHODS);
80
+ // the complete pairs (NaN counts as missing, as R's na.omit)
81
+ const a = [];
82
+ const b = [];
83
+ for (let i = 0; i < x.length; i++) {
84
+ const u = x[i];
85
+ const v = y[i];
86
+ if (typeof u !== "number" || typeof v !== "number")
87
+ throw new TypeError("'x' and 'y' must be numeric");
88
+ if (Number.isNaN(u) || Number.isNaN(v))
89
+ continue;
90
+ if (!Number.isFinite(u) || !Number.isFinite(v))
91
+ throw new RangeError("'x' and 'y' must not contain infinite values");
92
+ a.push(u);
93
+ b.push(v);
94
+ }
95
+ const n = a.length;
96
+ if (n < 2)
97
+ throw new RangeError("fewer than 2 complete pairs");
98
+ const [first, second] = mode === 1 ? [a, b] : [b, a];
99
+ // (x + y)/2 as R; x/2 + y/2 only where the sum overflows
100
+ const means = a.map((u, i) => {
101
+ const m = (u + b[i]) / 2;
102
+ return Number.isFinite(m) ? m : u / 2 + b[i] / 2;
103
+ });
104
+ const diffs = first.map((u, i) => u - second[i]);
105
+ // everything below in the coordinates 2^-k of the differences themselves (not of the data, where small differences
106
+ // beside a large pair would underflow), scaled back by ldexp at the end; the differences of the halves (k + 1) only
107
+ // where a difference overflows
108
+ const half = !diffs.every(Number.isFinite);
109
+ const { groups, k: kd } = scaleToUnit([half ? first.map((u, i) => u / 2 - second[i] / 2) : diffs]);
110
+ const d = groups[0];
111
+ const k = kd + (half ? 1 : 0);
112
+ const m = mean(d);
113
+ const s = standardDeviation(d);
114
+ const crit = two * s;
115
+ const lower = m - crit;
116
+ const upper = m + crit;
117
+ const df = n - 1;
118
+ const tail = (1 - confLevel) / 2;
119
+ const t1 = qt1(tail, df, true, false);
120
+ // (rule 10: the upper tail itself for a tail below 1e-8)
121
+ const t2 = tail < 1e-8 ? qt1(tail, df, false, false) : qt1((confLevel + 1) / 2, df, true, false);
122
+ const meanDiffConfInt = [m + times(t1, s) / Math.sqrt(n), m + times(t2, s) / Math.sqrt(n)];
123
+ let lowerLimitConfInt;
124
+ let upperLimitConfInt;
125
+ if (ciMethod === "package") {
126
+ // (s sqrt(3/n) where 3 s²/n would leave the normal range)
127
+ const v3 = (3 * s * s) / n;
128
+ const se = v3 >= 2 ** -1022 || v3 === 0 ? Math.sqrt(v3) : s * Math.sqrt(3 / n);
129
+ lowerLimitConfInt = [lower + times(t1, se), lower + times(t2, se)];
130
+ upperLimitConfInt = [upper + times(t1, se), upper + times(t2, se)];
131
+ }
132
+ else {
133
+ // Carkeet (2015): the quantiles of the noncentral t with noncentrality two sqrt(n), each from its own tail
134
+ const ncp = two * Math.sqrt(n);
135
+ const qLo = qnt1(tail, df, ncp, true, false) / Math.sqrt(n);
136
+ const qHi = qnt1(tail, df, ncp, false, false) / Math.sqrt(n);
137
+ lowerLimitConfInt = [m - times(qHi, s), m - times(qLo, s)];
138
+ upperLimitConfInt = [m + times(qLo, s), m + times(qHi, s)];
139
+ }
140
+ const back = (v) => ldexp(v, k);
141
+ const pair = (p) => [back(p[0]), back(p[1])];
142
+ return reported("blandAltman", {
143
+ means,
144
+ diffs,
145
+ n,
146
+ meanDiff: back(m),
147
+ lowerLimit: back(lower),
148
+ upperLimit: back(upper),
149
+ criticalDiff: back(crit),
150
+ meanDiffConfInt: pair(meanDiffConfInt),
151
+ lowerLimitConfInt: pair(lowerLimitConfInt),
152
+ upperLimitConfInt: pair(upperLimitConfInt),
153
+ confLevel,
154
+ two,
155
+ mode,
156
+ ciMethod,
157
+ warnings: [],
158
+ });
159
+ }