@numero-uno-jpn/rstats 1.2.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 (78) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.ja.md +27 -10
  3. package/README.md +26 -9
  4. package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-F3EQLL4F.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-L23RSC2N.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-IAWXF73N.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-5SGTWSCB.js → chunk-BNTBZ5W3.js} +2 -2
  10. package/dist/chunks/{chunk-EEU7D4RU.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-IMPRIQE5.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-73LNRWU3.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-RRO4LMCB.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-VERBXW6E.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-6FZHTD5G.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-JWBSEL3V.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-A66M3ZEA.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-HBHMEPGY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/{chunk-7WG7X2UI.js → chunk-P7ZHH2SF.js} +2 -2
  23. package/dist/chunks/{chunk-TNETWBF5.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-4AOTAT3O.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-NSU6U3ET.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-T5DRIITM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-BI7NYJWP.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7INBXTVV.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-BKV3FINA.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 +9 -0
  33. package/dist/entries/tests.js +9 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/blandAltman.d.ts +100 -0
  36. package/dist/htest/blandAltman.js +159 -0
  37. package/dist/htest/diagnosticTests.d.ts +91 -0
  38. package/dist/htest/diagnosticTests.js +116 -0
  39. package/dist/htest/iccPsych.d.ts +106 -0
  40. package/dist/htest/iccPsych.js +332 -0
  41. package/dist/htest/ksTest.d.ts +1 -1
  42. package/dist/htest/mcreg.d.ts +209 -0
  43. package/dist/htest/mcreg.js +735 -0
  44. package/dist/htest/roc.d.ts +287 -0
  45. package/dist/htest/roc.js +635 -0
  46. package/dist/htest/rocTest.d.ts +139 -0
  47. package/dist/htest/rocTest.js +444 -0
  48. package/dist/htest/tTOST.d.ts +202 -0
  49. package/dist/htest/tTOST.js +558 -0
  50. package/dist/htest/trendTests.d.ts +1 -1
  51. package/dist/htest/trendTests.js +1 -1
  52. package/dist/internal/summary.js +5 -0
  53. package/dist/linalg/qr.d.ts +3 -0
  54. package/dist/linalg/qr.js +3 -0
  55. package/dist/linalg.js +2 -2
  56. package/dist/mixed.js +2 -2
  57. package/dist/models/coeftest.d.ts +139 -0
  58. package/dist/models/coeftest.js +237 -0
  59. package/dist/models/coxph.d.ts +60 -9
  60. package/dist/models/coxph.js +367 -38
  61. package/dist/models/glm.d.ts +11 -1
  62. package/dist/models/glm.js +19 -2
  63. package/dist/models/inputRows.d.ts +10 -0
  64. package/dist/models/inputRows.js +23 -0
  65. package/dist/models/lm.d.ts +8 -0
  66. package/dist/models/lm.js +14 -2
  67. package/dist/models/sandwich.d.ts +177 -0
  68. package/dist/models/sandwich.js +923 -0
  69. package/dist/numerics.js +2 -2
  70. package/dist/random/rng.d.ts +8 -1
  71. package/dist/random/rng.js +14 -1
  72. package/dist/rstats.js +16 -16
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +13 -13
  75. package/llms.txt +17 -0
  76. package/package.json +1 -1
  77. package/dist/chunks/chunk-47IIPUFN.js +0 -2
  78. package/dist/chunks/chunk-CQB4BJBR.js +0 -2
@@ -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
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Options for {@link diagnosticTests}.
3
+ *
4
+ * @category Hypothesis tests
5
+ */
6
+ export interface DiagnosticTestsOptions {
7
+ /**
8
+ * The interval of the proportions: `"exact"` (default; Clopper-Pearson), `"wilson"` or `"jeffreys"`;
9
+ * abbreviations are accepted.
10
+ */
11
+ method?: "exact" | "wilson" | "jeffreys" | (string & {});
12
+ /** Confidence level, in (0, 1). Default `0.95`. */
13
+ confLevel?: number;
14
+ /** A prevalence in (0, 1) at which to give the predictive values as well (`ppvAtPrevalence`, `npvAtPrevalence`). */
15
+ prevalence?: number;
16
+ }
17
+ /**
18
+ * An estimate with its confidence interval.
19
+ *
20
+ * @category Hypothesis tests
21
+ */
22
+ export interface DiagnosticMeasure {
23
+ /** The estimate. */
24
+ estimate: number;
25
+ /** The interval `[lower, upper]`. */
26
+ confInt: [number, number];
27
+ }
28
+ /**
29
+ * Result of {@link diagnosticTests}.
30
+ *
31
+ * @category Hypothesis tests
32
+ */
33
+ export interface DiagnosticTestsResult {
34
+ /** Sensitivity a/(a + c). */
35
+ sensitivity: DiagnosticMeasure;
36
+ /** Specificity d/(b + d). */
37
+ specificity: DiagnosticMeasure;
38
+ /** Positive predictive value a/(a + b). */
39
+ ppv: DiagnosticMeasure;
40
+ /** Negative predictive value d/(c + d). */
41
+ npv: DiagnosticMeasure;
42
+ /** Positive likelihood ratio se/(1 − sp), with the log interval. */
43
+ lrPos: DiagnosticMeasure;
44
+ /** Negative likelihood ratio (1 − se)/sp, with the log interval. */
45
+ lrNeg: DiagnosticMeasure;
46
+ /** Diagnostic accuracy (a + d)/total. */
47
+ accuracy: DiagnosticMeasure;
48
+ /** Diagnostic odds ratio ad/(bc), with Woolf's interval. */
49
+ diagnosticOR: DiagnosticMeasure;
50
+ /** True prevalence (a + c)/total (epiR's "tp"). */
51
+ prevalence: DiagnosticMeasure;
52
+ /** Apparent prevalence (a + b)/total (epiR's "ap"). */
53
+ apparentPrevalence: DiagnosticMeasure;
54
+ /** The positive predictive value at the prevalence given in the options (absent without it). */
55
+ ppvAtPrevalence?: number;
56
+ /** The negative predictive value at the prevalence given in the options (absent without it). */
57
+ npvAtPrevalence?: number;
58
+ /** The method of the proportions' intervals, in full. */
59
+ method: "exact" | "wilson" | "jeffreys";
60
+ /** The confidence level. */
61
+ confLevel: number;
62
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
63
+ warnings: string[];
64
+ }
65
+ /**
66
+ * Sensitivity, specificity, predictive values, likelihood ratios, accuracy, the diagnostic odds ratio and the true and
67
+ * apparent prevalence of a binary test, each with a confidence interval, from its 2 × 2 table. Equivalent to
68
+ * `epiR::epi.tests()` in R.
69
+ *
70
+ * The table is epiR's: rows test positive and negative, columns disease present and absent, `[[a, b], [c, d]]` with
71
+ * a the true positives, b the false positives, c the false negatives and d the true negatives. The proportions'
72
+ * intervals are those of {@link binomCI}: `"exact"` is Clopper-Pearson's, computed directly (epiR computes it as 1 −
73
+ * qbeta(...), which loses digits for small limits); `"jeffreys"` gives 0 and 1 at the ends, as binomCI (epiR the
74
+ * beta quantiles). The likelihood ratios have the log interval (Simel, Samsa and Matchar 1991) and the odds ratio
75
+ * Woolf's. Zero cells give infinite ratios and NaN limits, as epiR; a zero row or column total is an error.
76
+ *
77
+ * @param table The 2 × 2 table of counts (an array of two rows).
78
+ * @param options See {@link DiagnosticTestsOptions}.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const r = diagnosticTests([[670, 202], [74, 640]]);
83
+ * r.sensitivity.estimate; // 0.9005376344086021
84
+ * r.sensitivity.confInt; // [0.8767461767957109, 0.9210922995836943]
85
+ * r.lrPos.estimate; // 3.7537261790695196
86
+ * diagnosticTests([[670, 202], [74, 640]], { prevalence: 0.1 }).ppvAtPrevalence; // 0.2943238804381625
87
+ * ```
88
+ *
89
+ * @category Hypothesis tests
90
+ */
91
+ export declare function diagnosticTests(table: readonly (readonly number[])[], options?: DiagnosticTestsOptions): DiagnosticTestsResult;
@@ -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,106 @@
1
+ /**
2
+ * Options for {@link ICC}.
3
+ *
4
+ * @category Agreement, reliability and factor analysis
5
+ */
6
+ export interface ICCOptions {
7
+ /** One minus the confidence level of the intervals, in (0, 1) (psych's `alpha`). Default `0.05`; overrides
8
+ * `confLevel`. */
9
+ alpha?: number;
10
+ /** Confidence level of the intervals, in (0, 1). Default `0.95`. */
11
+ confLevel?: number;
12
+ /**
13
+ * `true` (default, as psych): the mean squares from the REML estimates of the variance components, which are not
14
+ * negative (where a component would be negative, it is 0 and the coefficients that depend on it are 0, F 1);
15
+ * `false`: the ANOVA mean squares (coefficients may be negative).
16
+ */
17
+ lmer?: boolean;
18
+ }
19
+ /**
20
+ * One of the six forms in {@link ICCResult}.
21
+ *
22
+ * @category Agreement, reliability and factor analysis
23
+ */
24
+ export interface ICCRow {
25
+ /** `"ICC1"`, `"ICC2"`, `"ICC3"`, `"ICC1k"`, `"ICC2k"` or `"ICC3k"`. */
26
+ type: "ICC1" | "ICC2" | "ICC3" | "ICC1k" | "ICC2k" | "ICC3k";
27
+ /** psych's row name: `"Single_raters_absolute"`, `"Single_random_raters"`, ... */
28
+ name: string;
29
+ /** The intraclass correlation. */
30
+ ICC: number;
31
+ /** F statistic of the test of ICC = 0. */
32
+ F: number;
33
+ /** Numerator degrees of freedom. */
34
+ df1: number;
35
+ /** Denominator degrees of freedom. */
36
+ df2: number;
37
+ /** Upper-tail p-value of the F test. */
38
+ pValue: number;
39
+ /** Lower confidence limit. */
40
+ lower: number;
41
+ /** Upper confidence limit. */
42
+ upper: number;
43
+ }
44
+ /**
45
+ * Result of {@link ICC}.
46
+ *
47
+ * @category Agreement, reliability and factor analysis
48
+ */
49
+ export interface ICCResult {
50
+ /** The six forms, in psych's order ICC1, ICC2, ICC3, ICC1k, ICC2k, ICC3k. */
51
+ results: ICCRow[];
52
+ /** Mean square of subjects (REML: `k σ²_subject + σ²_e`). */
53
+ MSB: number;
54
+ /** Mean square of raters (REML: `n σ²_rater + σ²_e`). */
55
+ MSJ: number;
56
+ /** Residual mean square (REML: `σ²_e`). */
57
+ MSE: number;
58
+ /** Mean square within subjects, used by ICC1 and ICC1k (REML: `σ²_e + σ²_rater`). */
59
+ MSW: number;
60
+ /** Number of subjects (rows). */
61
+ n: number;
62
+ /** Number of raters (columns). */
63
+ k: number;
64
+ /** Confidence level of the intervals, `1 - alpha`. */
65
+ confLevel: number;
66
+ /** Whether the REML path was used. */
67
+ lmer: boolean;
68
+ /** R's warnings (aov's `essentially perfect fit` where the residual mean square is 0 on the ANOVA path). */
69
+ warnings: string[];
70
+ }
71
+ /**
72
+ * The six intraclass correlations of Shrout and Fleiss (1979), with their F tests and confidence intervals.
73
+ * Equivalent to `psych::ICC(x, alpha, lmer)` in R. Only complete data are accepted.
74
+ *
75
+ * `x` is an n × k matrix (an array of rows): the ratings of the k raters for each of the n subjects. The forms are
76
+ * ICC1 = (MSB − MSW)/(MSB + (k − 1)MSW) (one-way), ICC2 = (MSB − MSE)/(MSB + (k − 1)MSE + k(MSJ − MSE)/n) (two-way
77
+ * random raters, absolute agreement), ICC3 = (MSB − MSE)/(MSB + (k − 1)MSE) (two-way fixed raters, consistency), and
78
+ * their averages over k raters ICC1k, ICC2k, ICC3k. With `lmer: true` (the default, as psych) the mean squares are
79
+ * rebuilt from the REML estimates of the variance components of the two-way random model, which are not negative;
80
+ * where both ANOVA components are not negative they equal the ANOVA mean squares. psych fits that model with lme4,
81
+ * whose optimiser stops early (results about 1e-5 relative off); here the REML estimates are computed exactly, in
82
+ * closed form.
83
+ *
84
+ * ICC1, ICC3, ICC1k and ICC3k agree with {@link icc} (irr's forms); the interval of ICC2k is psych's (ICC2's bounds
85
+ * transformed by Spearman-Brown), not irr's (McGraw and Wong's average-agreement interval).
86
+ *
87
+ * Where the residual mean square is 0 (ratings that differ between raters by constants), the F statistics of ICC2 and
88
+ * ICC3 are Infinity with p-value 0, and ICC3, ICC3k and their bounds are 1.
89
+ *
90
+ * @param x An n × k matrix of ratings (array of rows), without missing values.
91
+ * @param options See {@link ICCOptions}.
92
+ * @returns See {@link ICCResult}.
93
+ * @throws TypeError if x is not a matrix of numbers; RangeError for missing or infinite ratings (psych's REML path
94
+ * accepts missing ratings; here they are an error), fewer than 2 subjects or raters, ratings that are all equal or
95
+ * identical for every subject, or a level out of range.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const r = ICC([[9, 2, 5, 8], [6, 1, 3, 2], [8, 4, 6, 8], [7, 1, 2, 6], [10, 5, 6, 9], [6, 2, 4, 7]]);
100
+ * r.results[1]!.ICC; // 0.28976377952755905 (ICC2)
101
+ * r.results[4]!.lower; // 0.07113681530250335 (ICC2k)
102
+ * ```
103
+ *
104
+ * @category Agreement, reliability and factor analysis
105
+ */
106
+ export declare function ICC(x: readonly (readonly number[])[], options?: ICCOptions): ICCResult;