@numero-uno-jpn/rstats 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/README.ja.md +64 -12
- package/README.md +63 -11
- package/THIRD_PARTY_NOTICES.md +7 -2
- package/dist/chunks/chunk-5WDJPHYY.js +2 -0
- package/dist/chunks/chunk-7GQMKH3Z.js +2 -0
- package/dist/chunks/chunk-AHHS6AC4.js +3 -0
- package/dist/chunks/chunk-ALM3VHFP.js +2 -0
- package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-C5XTWMGB.js} +1 -1
- package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
- package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-EZAFN5CD.js} +1 -1
- package/dist/chunks/{chunk-H2AP6TCR.js → chunk-EZWBRCJL.js} +1 -1
- package/dist/chunks/chunk-F5EDJFEO.js +2 -0
- package/dist/chunks/{chunk-FC2TLHZC.js → chunk-JWBO5WVN.js} +2 -2
- package/dist/chunks/{chunk-LE7TBHNI.js → chunk-TOGXTCZO.js} +2 -2
- package/dist/chunks/chunk-VJ4BDBMU.js +3 -0
- package/dist/chunks/chunk-Y5CNQ266.js +2 -0
- package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-Y5PYRAYP.js} +2 -2
- package/dist/chunks/{chunk-5K4PS7IV.js → chunk-YSWGDOWK.js} +2 -2
- package/dist/data/grouping.d.ts +79 -0
- package/dist/data/grouping.js +262 -0
- package/dist/descriptive/dataFrames.d.ts +110 -0
- package/dist/descriptive/dataFrames.js +392 -0
- package/dist/descriptive/factanal.d.ts +56 -0
- package/dist/descriptive/factanal.js +186 -0
- package/dist/descriptive/missing.d.ts +35 -0
- package/dist/descriptive/missing.js +50 -0
- package/dist/descriptive/omega.d.ts +56 -0
- package/dist/descriptive/omega.js +323 -0
- package/dist/descriptive/pivot.d.ts +89 -0
- package/dist/descriptive/pivot.js +343 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/bvnorm.d.ts +15 -0
- package/dist/distributions/bvnorm.js +131 -0
- package/dist/distributions/nbeta.js +34 -1
- package/dist/distributions/nchisq.d.ts +10 -0
- package/dist/distributions/nchisq.js +46 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +4 -0
- package/dist/entries/descriptive.js +4 -0
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +1 -0
- package/dist/entries/linalg.d.ts +2 -0
- package/dist/entries/linalg.js +2 -0
- package/dist/entries/numerics.d.ts +2 -0
- package/dist/entries/numerics.js +1 -0
- package/dist/entries/tests.d.ts +22 -1
- package/dist/entries/tests.js +19 -1
- package/dist/htest/agreement.d.ts +141 -0
- package/dist/htest/agreement.js +274 -0
- package/dist/htest/ansariTest.d.ts +12 -0
- package/dist/htest/ansariTest.js +5 -17
- package/dist/htest/aov.d.ts +19 -0
- package/dist/htest/aov.js +22 -15
- package/dist/htest/cor.d.ts +12 -0
- package/dist/htest/cor.js +9 -27
- package/dist/htest/core/simulate.d.ts +2 -0
- package/dist/htest/core/simulate.js +1 -1
- package/dist/htest/dunnett.d.ts +5 -0
- package/dist/htest/dunnett.js +89 -0
- package/dist/htest/effectSize.d.ts +112 -0
- package/dist/htest/effectSize.js +385 -0
- package/dist/htest/ksTest.d.ts +13 -0
- package/dist/htest/ksTest.js +5 -8
- package/dist/htest/leveneTest.d.ts +30 -0
- package/dist/htest/leveneTest.js +41 -0
- package/dist/htest/multipleComparisons.d.ts +147 -0
- package/dist/htest/multipleComparisons.js +369 -0
- package/dist/htest/normalityTests.d.ts +44 -0
- package/dist/htest/normalityTests.js +164 -0
- package/dist/htest/onewayTest.d.ts +14 -0
- package/dist/htest/onewayTest.js +5 -7
- package/dist/htest/polycor.d.ts +117 -0
- package/dist/htest/polycor.js +468 -0
- package/dist/htest/power.d.ts +132 -0
- package/dist/htest/power.js +227 -0
- package/dist/htest/pwr.d.ts +263 -0
- package/dist/htest/pwr.js +440 -0
- package/dist/htest/rankTests.d.ts +64 -0
- package/dist/htest/rankTests.js +27 -29
- package/dist/htest/tTest.d.ts +20 -0
- package/dist/htest/tTest.js +19 -24
- package/dist/htest/testFormula.d.ts +57 -0
- package/dist/htest/testFormula.js +171 -0
- package/dist/htest/trendTests.d.ts +57 -0
- package/dist/htest/trendTests.js +167 -0
- package/dist/htest/varTest.d.ts +23 -0
- package/dist/htest/varTest.js +11 -21
- package/dist/htest/wilcoxTest.d.ts +14 -0
- package/dist/htest/wilcoxTest.js +9 -24
- package/dist/linalg/eigen.d.ts +8 -0
- package/dist/linalg/eigen.js +5 -4
- package/dist/linalg/expm.d.ts +48 -0
- package/dist/linalg/expm.js +472 -0
- package/dist/linalg/ops.d.ts +13 -2
- package/dist/linalg/ops.js +20 -5
- package/dist/linalg/schur.d.ts +48 -0
- package/dist/linalg/schur.js +225 -0
- package/dist/linalg.js +2 -2
- package/dist/models/anovaSequential.d.ts +58 -0
- package/dist/models/anovaSequential.js +138 -0
- package/dist/models/aovEz.d.ts +64 -0
- package/dist/models/aovEz.js +332 -0
- package/dist/models/aovStrata.d.ts +32 -0
- package/dist/models/aovStrata.js +104 -0
- package/dist/models/carAnova.d.ts +30 -0
- package/dist/models/carAnova.js +121 -0
- package/dist/models/coxph.d.ts +101 -0
- package/dist/models/coxph.js +502 -0
- package/dist/models/ddLeastSquares.d.ts +30 -0
- package/dist/models/ddLeastSquares.js +90 -0
- package/dist/models/ddMatrix.d.ts +10 -0
- package/dist/models/ddMatrix.js +91 -0
- package/dist/models/formula.d.ts +83 -0
- package/dist/models/formula.js +333 -0
- package/dist/models/lm.d.ts +84 -3
- package/dist/models/lm.js +141 -44
- package/dist/models/mauchly.d.ts +48 -0
- package/dist/models/mauchly.js +123 -0
- package/dist/models/modelFrame.d.ts +40 -0
- package/dist/models/modelFrame.js +131 -0
- package/dist/models/modelMatrix.d.ts +88 -0
- package/dist/models/modelMatrix.js +170 -0
- package/dist/models/survival.d.ts +87 -0
- package/dist/models/survival.js +238 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/lbfgsb.d.ts +20 -0
- package/dist/optim/lbfgsb.js +1240 -0
- package/dist/optim/optim.d.ts +85 -0
- package/dist/optim/optim.js +610 -0
- package/dist/rstats.js +19 -4
- package/dist/special.js +2 -2
- package/dist/tests.js +17 -4
- package/llms.txt +114 -0
- package/package.json +3 -2
- package/dist/chunks/chunk-24U4DKRY.js +0 -2
- package/dist/chunks/chunk-IVOBWYLV.js +0 -2
- package/dist/chunks/chunk-JLSTEMSN.js +0 -2
- package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
- package/dist/chunks/chunk-MSAUU6PY.js +0 -2
- package/dist/chunks/chunk-YC4JWUKG.js +0 -2
- package/dist/chunks/chunk-ZRO446BP.js +0 -2
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// Agreement and reliability: Cohen's kappa for two raters (irr's kappa2, unweighted or weighted), Fleiss' kappa for
|
|
2
|
+
// several raters (irr's kappam.fleiss, with Conger's exact variant), the intraclass correlation (irr's icc) with its
|
|
3
|
+
// F test and confidence interval, Cronbach's alpha with Guttman's lambda 6 (psych's alpha), and the partial
|
|
4
|
+
// correlation of two variables given the others (psych's partial.r).
|
|
5
|
+
//
|
|
6
|
+
// Written for rStats.js from oracle/agreement-behaviour.md (no ported code; the source of irr and psych was not
|
|
7
|
+
// read). The p-values of the kappas are computed as 2 Φ(−|z|), which keeps small ones that irr's 2 (1 − Φ(|z|))
|
|
8
|
+
// loses to cancellation.
|
|
9
|
+
import { cor, cov } from "../descriptive/cov.js";
|
|
10
|
+
import { pf1, qf1 } from "../distributions/f.js";
|
|
11
|
+
import { pnorm } from "../distributions/normal.js";
|
|
12
|
+
import { mean, sum, variance } from "../internal/summary.js";
|
|
13
|
+
import { solve } from "../linalg/solve.js";
|
|
14
|
+
import { formatR } from "./core/simulate.js";
|
|
15
|
+
import { matchChoice } from "./power.js";
|
|
16
|
+
import { checkConfLevelOpen } from "./types.js";
|
|
17
|
+
/** Columns of a matrix given as an array of rows, after checking that it is rectangular */
|
|
18
|
+
function columnsOf(x, what) {
|
|
19
|
+
const k = x[0]?.length ?? 0;
|
|
20
|
+
if (x.some((r) => r.length !== k))
|
|
21
|
+
throw new TypeError(`'${what}' must be a matrix (rows of equal length)`);
|
|
22
|
+
return Array.from({ length: k }, (_, j) => x.map((r) => r[j]));
|
|
23
|
+
}
|
|
24
|
+
function requireComplete(x, what) {
|
|
25
|
+
if (x.some((r) => r.some(Number.isNaN)))
|
|
26
|
+
throw new RangeError(`'${what}' contains missing values`);
|
|
27
|
+
}
|
|
28
|
+
/** Two-sided normal p-value 2 Φ(−|z|) */
|
|
29
|
+
const twoSidedP = (z) => 2 * pnorm(-Math.abs(z));
|
|
30
|
+
/**
|
|
31
|
+
* Cohen's kappa for two raters, unweighted or weighted, with the z test of kappa = 0. Equivalent to irr's
|
|
32
|
+
* `kappa2(ratings, weight)` (numeric ratings).
|
|
33
|
+
*
|
|
34
|
+
* The levels are the distinct ratings of both raters sorted as R sorts their character forms (so 10 sorts before 2,
|
|
35
|
+
* which matters for the weighted kappas). Rows with a missing value (`NaN`) are dropped. The variance of the test is
|
|
36
|
+
* the one under the null hypothesis; the p-value is computed as 2 Φ(−|z|), so small p-values are more accurate than
|
|
37
|
+
* irr's.
|
|
38
|
+
*
|
|
39
|
+
* @param ratings - An n × 2 matrix (array of rows): the ratings of the two raters for each subject.
|
|
40
|
+
* @param options - See {@link Kappa2Options}.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* kappa2([[1, 1], [2, 2], [3, 2], [1, 1], [2, 3], [3, 3]]); // { value: 0.49999999999999994, statistic: 1.7320508075688772, pValue: 0.08326451666355043 }
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export function kappa2(ratings, options = {}) {
|
|
48
|
+
const weight = matchChoice(options.weight, ["unweighted", "equal", "squared"]);
|
|
49
|
+
if (ratings.some((r) => r.length !== 2))
|
|
50
|
+
throw new TypeError("'ratings' must be a matrix with two columns");
|
|
51
|
+
const rows = ratings.filter((r) => !r.some(Number.isNaN));
|
|
52
|
+
const n = rows.length;
|
|
53
|
+
const first = rows.map((r) => formatR(r[0]));
|
|
54
|
+
const second = rows.map((r) => formatR(r[1]));
|
|
55
|
+
// the levels of both raters together, sorted as strings (by code point, as in R's C locale)
|
|
56
|
+
const levels = [...new Set([...first, ...second])].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
57
|
+
const c = levels.length;
|
|
58
|
+
const index = new Map(levels.map((l, i) => [l, i]));
|
|
59
|
+
const T = Array.from({ length: c }, () => new Array(c).fill(0));
|
|
60
|
+
for (let i = 0; i < n; i++)
|
|
61
|
+
T[index.get(first[i])][index.get(second[i])]++;
|
|
62
|
+
const w = (d) => weight === "unweighted" ? (d === 0 ? 1 : 0) : weight === "equal" ? 1 - d / (c - 1) : 1 - (d * d) / ((c - 1) * (c - 1));
|
|
63
|
+
const W = Array.from({ length: c }, (_, r) => Array.from({ length: c }, (_, s) => w(Math.abs(r - s))));
|
|
64
|
+
const a = T.map((row) => sum(row) / n);
|
|
65
|
+
const b = Array.from({ length: c }, (_, s) => sum(T.map((row) => row[s])) / n);
|
|
66
|
+
const terms = (f) => {
|
|
67
|
+
const t = [];
|
|
68
|
+
for (let r = 0; r < c; r++)
|
|
69
|
+
for (let s = 0; s < c; s++)
|
|
70
|
+
t.push(f(r, s));
|
|
71
|
+
return sum(t);
|
|
72
|
+
};
|
|
73
|
+
const po = terms((r, s) => T[r][s] * W[r][s]) / n;
|
|
74
|
+
const pe = terms((r, s) => a[r] * b[s] * W[r][s]);
|
|
75
|
+
const value = (po - pe) / (1 - pe);
|
|
76
|
+
const u = Array.from({ length: c }, (_, r) => sum(b.map((bs, s) => bs * W[r][s])));
|
|
77
|
+
const v = Array.from({ length: c }, (_, s) => sum(a.map((ar, r) => ar * W[r][s])));
|
|
78
|
+
const variance0 = (terms((r, s) => a[r] * b[s] * (W[r][s] - (u[r] + v[s])) ** 2) - pe * pe) / (n * (1 - pe) ** 2);
|
|
79
|
+
const statistic = value / Math.sqrt(variance0);
|
|
80
|
+
return { value, statistic, pValue: twoSidedP(statistic) };
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Fleiss' kappa for several raters (or Conger's exact kappa), with the z test of kappa = 0 for Fleiss' kappa.
|
|
84
|
+
* Equivalent to irr's `kappam.fleiss(ratings, exact)` (numeric ratings, no missing values).
|
|
85
|
+
*
|
|
86
|
+
* The p-value is computed as 2 Φ(−|z|), so small p-values are more accurate than irr's.
|
|
87
|
+
*
|
|
88
|
+
* @param ratings - An n × m matrix (array of rows): the ratings of the m raters for each of the n subjects.
|
|
89
|
+
* @param options - See {@link KappamFleissOptions}.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* ```ts
|
|
93
|
+
* kappamFleiss([[1, 1, 2], [2, 2, 2], [3, 3, 2], [1, 1, 1], [2, 3, 3]]).value; // 0.3918918918918918
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export function kappamFleiss(ratings, options = {}) {
|
|
97
|
+
const exact = options.exact ?? false;
|
|
98
|
+
const cols = columnsOf(ratings, "ratings");
|
|
99
|
+
requireComplete(ratings, "ratings");
|
|
100
|
+
const n = ratings.length;
|
|
101
|
+
const m = cols.length;
|
|
102
|
+
const levels = [...new Set(ratings.flat())].sort((x, y) => x - y);
|
|
103
|
+
const index = new Map(levels.map((l, j) => [l, j]));
|
|
104
|
+
const L = levels.length;
|
|
105
|
+
// t[i][j]: raters giving subject i level j; q[r][j]: subjects that rater r put in level j
|
|
106
|
+
const t = ratings.map((row) => {
|
|
107
|
+
const counts = new Array(L).fill(0);
|
|
108
|
+
for (const x of row)
|
|
109
|
+
counts[index.get(x)]++;
|
|
110
|
+
return counts;
|
|
111
|
+
});
|
|
112
|
+
const po = sum(t.map((ti) => (sum(ti.map((x) => x * x)) - m) / (m * (m - 1)))) / n;
|
|
113
|
+
const p = Array.from({ length: L }, (_, j) => sum(t.map((ti) => ti[j])) / (n * m));
|
|
114
|
+
let pe = sum(p.map((pj) => pj * pj));
|
|
115
|
+
if (exact) {
|
|
116
|
+
const q = cols.map((col) => {
|
|
117
|
+
const counts = new Array(L).fill(0);
|
|
118
|
+
for (const x of col)
|
|
119
|
+
counts[index.get(x)]++;
|
|
120
|
+
return counts.map((cnt) => cnt / n);
|
|
121
|
+
});
|
|
122
|
+
const spread = Array.from({ length: L }, (_, j) => (variance(q.map((qr) => qr[j])) * (m - 1)) / m);
|
|
123
|
+
pe -= sum(spread) / (m - 1);
|
|
124
|
+
}
|
|
125
|
+
const value = (po - pe) / (1 - pe);
|
|
126
|
+
if (exact)
|
|
127
|
+
return { value };
|
|
128
|
+
const pq = sum(p.map((pj) => pj * (1 - pj)));
|
|
129
|
+
const skew = sum(p.map((pj) => pj * (1 - pj) * (1 - pj - pj)));
|
|
130
|
+
const variance0 = (2 / (pq * pq * n * m * (m - 1))) * (pq * pq - skew);
|
|
131
|
+
const statistic = value / Math.sqrt(variance0);
|
|
132
|
+
return { value, statistic, pValue: twoSidedP(statistic) };
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Intraclass correlation coefficient with its F test and confidence interval (McGraw and Wong's forms). Equivalent
|
|
136
|
+
* to irr's `icc(ratings, model, type, unit, r0, conf.level)` (no missing values).
|
|
137
|
+
*
|
|
138
|
+
* @param ratings - An n × k matrix (array of rows): the ratings of the k raters for each of the n subjects.
|
|
139
|
+
* @param options - See {@link IccOptions}.
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```ts
|
|
143
|
+
* 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]],
|
|
144
|
+
* { model: "twoway", type: "agreement" }).value; // 0.28976377952755905
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export function icc(ratings, options = {}) {
|
|
148
|
+
const model = matchChoice(options.model, ["oneway", "twoway"]);
|
|
149
|
+
const type = matchChoice(options.type, ["consistency", "agreement"]);
|
|
150
|
+
const unit = matchChoice(options.unit, ["single", "average"]);
|
|
151
|
+
const r0 = options.r0 ?? 0;
|
|
152
|
+
const confLevel = options.confLevel ?? 0.95;
|
|
153
|
+
checkConfLevelOpen(confLevel);
|
|
154
|
+
const cols = columnsOf(ratings, "ratings");
|
|
155
|
+
requireComplete(ratings, "ratings");
|
|
156
|
+
const n = ratings.length;
|
|
157
|
+
const k = cols.length;
|
|
158
|
+
const alpha = 1 - confLevel;
|
|
159
|
+
// mean squares from sample variances
|
|
160
|
+
const msr = variance(ratings.map((r) => mean(r))) * k;
|
|
161
|
+
const msc = variance(cols.map((c) => mean(c))) * n;
|
|
162
|
+
const msw = mean(ratings.map((r) => variance(r)));
|
|
163
|
+
const ssTotal = variance(ratings.flat()) * (n * k - 1);
|
|
164
|
+
const mse = (ssTotal - msr * (n - 1) - msc * (k - 1)) / ((n - 1) * (k - 1));
|
|
165
|
+
const upper = (F, d1, d2) => pf1(F, d1, d2, false, false);
|
|
166
|
+
const q = (d1, d2) => qf1(1 - alpha / 2, d1, d2, true, false);
|
|
167
|
+
const df1 = n - 1;
|
|
168
|
+
if (model === "oneway" || type === "consistency") {
|
|
169
|
+
const ms = model === "oneway" ? msw : mse;
|
|
170
|
+
const df2 = model === "oneway" ? n * (k - 1) : (n - 1) * (k - 1);
|
|
171
|
+
const ratio = msr / ms;
|
|
172
|
+
const FL = ratio / q(df1, df2);
|
|
173
|
+
const FU = ratio * q(df2, df1);
|
|
174
|
+
const [value, Fvalue, bound] = unit === "single"
|
|
175
|
+
? [(msr - ms) / (msr + (k - 1) * ms), (ratio * (1 - r0)) / (1 + (k - 1) * r0), (f) => (f - 1) / (f + k - 1)]
|
|
176
|
+
: [(msr - ms) / msr, ratio * (1 - r0), (f) => 1 - 1 / f];
|
|
177
|
+
return { value, Fvalue, df1, df2, pValue: upper(Fvalue, df1, df2), lbound: bound(FL), ubound: bound(FU) };
|
|
178
|
+
}
|
|
179
|
+
// two-way agreement: Satterthwaite's degrees of freedom v for the combination a MSc + b MSe
|
|
180
|
+
const scale = unit === "single" ? k : 1;
|
|
181
|
+
const coefficients = (r) => [(scale * r) / (n * (1 - r)), 1 + (scale * r * (n - 1)) / (n * (1 - r))];
|
|
182
|
+
const dfOf = (a, b) => (a * msc + b * mse) ** 2 / ((a * msc) ** 2 / (k - 1) + (b * mse) ** 2 / ((n - 1) * (k - 1)));
|
|
183
|
+
const value = unit === "single" ? (msr - mse) / (msr + (k - 1) * mse + (k / n) * (msc - mse)) : (msr - mse) / (msr + (msc - mse) / n);
|
|
184
|
+
const [a0, b0] = coefficients(r0);
|
|
185
|
+
const Fvalue = msr / (a0 * msc + b0 * mse);
|
|
186
|
+
const df2 = dfOf(a0, b0);
|
|
187
|
+
// the bounds use the coefficients of the estimate, with k in both units
|
|
188
|
+
const [a, b] = [(k * value) / (n * (1 - value)), 1 + (k * value * (n - 1)) / (n * (1 - value))];
|
|
189
|
+
const v = dfOf(a, b);
|
|
190
|
+
const FL = q(df1, v);
|
|
191
|
+
const FU = q(v, df1);
|
|
192
|
+
const [lbound, ubound] = unit === "single"
|
|
193
|
+
? [
|
|
194
|
+
(n * (msr - FL * mse)) / (FL * (k * msc + (k * n - k - n) * mse) + n * msr),
|
|
195
|
+
(n * (FU * msr - mse)) / (k * msc + (k * n - k - n) * mse + n * FU * msr),
|
|
196
|
+
]
|
|
197
|
+
: [(n * (msr - FL * mse)) / (FL * (msc - mse) + n * msr), (n * (FU * msr - mse)) / (msc - mse + n * FU * msr)];
|
|
198
|
+
return { value, Fvalue, df1, df2, pValue: upper(Fvalue, df1, df2), lbound, ubound };
|
|
199
|
+
}
|
|
200
|
+
/** Raw alpha of the covariance matrix C restricted to the items `keep` */
|
|
201
|
+
function rawAlphaOf(C, keep) {
|
|
202
|
+
const k = keep.length;
|
|
203
|
+
const total = sum(keep.flatMap((i) => keep.map((j) => C[i][j])));
|
|
204
|
+
const trace = sum(keep.map((i) => C[i][i]));
|
|
205
|
+
return ((1 - trace / total) * k) / (k - 1);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Cronbach's alpha of a set of items, standardized alpha, Guttman's lambda 6 and the mean inter-item correlation,
|
|
209
|
+
* and alpha with each item dropped. Equivalent to the `total` row and `alpha.drop$raw_alpha` of psych's `alpha(x)`
|
|
210
|
+
* with its defaults (no missing values, no reversed items).
|
|
211
|
+
*
|
|
212
|
+
* @param x - An n × k matrix (array of rows): k items observed on n subjects.
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```ts
|
|
216
|
+
* cronbachAlpha([[1, 2, 2], [2, 3, 3], [3, 3, 4], [4, 5, 4], [2, 2, 3]]).rawAlpha; // 0.935483870967742
|
|
217
|
+
* ```
|
|
218
|
+
*/
|
|
219
|
+
export function cronbachAlpha(x) {
|
|
220
|
+
const k = columnsOf(x, "x").length;
|
|
221
|
+
requireComplete(x, "x");
|
|
222
|
+
if (k < 2)
|
|
223
|
+
throw new RangeError("'x' needs at least two items");
|
|
224
|
+
const C = cov(x);
|
|
225
|
+
const R = cor(x);
|
|
226
|
+
const items = Array.from({ length: k }, (_, i) => i);
|
|
227
|
+
const sumR = sum(R.flat());
|
|
228
|
+
const Rinv = solve(R);
|
|
229
|
+
const smc = items.map((i) => 1 - 1 / Rinv[i][i]);
|
|
230
|
+
return {
|
|
231
|
+
rawAlpha: rawAlphaOf(C, items),
|
|
232
|
+
stdAlpha: ((1 - k / sumR) * k) / (k - 1),
|
|
233
|
+
G6: 1 - (k - sum(smc)) / sumR,
|
|
234
|
+
averageR: (sumR - k) / (k * (k - 1)),
|
|
235
|
+
alphaDrop: items.map((i) => rawAlphaOf(C, items.filter((j) => j !== i))),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Partial correlation of columns `i` and `j` of `x` given all its other columns. Equivalent to psych's
|
|
240
|
+
* `partial.r(x, c(i, j), others)` (its off-diagonal element; no missing values).
|
|
241
|
+
*
|
|
242
|
+
* @param x - An n × p matrix (array of rows), the variables in the columns.
|
|
243
|
+
* @param i - 0-based column index.
|
|
244
|
+
* @param j - 0-based column index, different from `i`.
|
|
245
|
+
*
|
|
246
|
+
* @example
|
|
247
|
+
* ```ts
|
|
248
|
+
* partialR([[1, 2, 3], [2, 1, 5], [3, 5, 4], [4, 3, 8], [5, 6, 7]], 0, 1); // 0.9804877404385672
|
|
249
|
+
* ```
|
|
250
|
+
*/
|
|
251
|
+
export function partialR(x, i, j) {
|
|
252
|
+
const p = columnsOf(x, "x").length;
|
|
253
|
+
requireComplete(x, "x");
|
|
254
|
+
for (const c of [i, j]) {
|
|
255
|
+
if (!Number.isInteger(c) || c < 0 || c >= p)
|
|
256
|
+
throw new RangeError(`column index ${c} out of range (0 to ${p - 1})`);
|
|
257
|
+
}
|
|
258
|
+
if (i === j)
|
|
259
|
+
throw new RangeError("'i' and 'j' must be different columns");
|
|
260
|
+
const R = cor(x);
|
|
261
|
+
const ab = [i, j];
|
|
262
|
+
const others = Array.from({ length: p }, (_, c) => c).filter((c) => c !== i && c !== j);
|
|
263
|
+
const P = ab.map((r) => ab.map((s) => R[r][s]));
|
|
264
|
+
if (others.length > 0) {
|
|
265
|
+
const Rbb = others.map((r) => others.map((s) => R[r][s]));
|
|
266
|
+
const Rba = others.map((r) => ab.map((s) => R[r][s]));
|
|
267
|
+
const X = solve(Rbb, Rba);
|
|
268
|
+
for (let r = 0; r < 2; r++) {
|
|
269
|
+
for (let s = 0; s < 2; s++)
|
|
270
|
+
P[r][s] -= sum(others.map((o, t) => R[ab[r]][o] * X[t][s]));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return P[0][1] / Math.sqrt(P[0][0] * P[1][1]);
|
|
274
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { DataFrame } from "../models/modelFrame.js";
|
|
1
2
|
import { type Alternative, type HTest, type Sample } from "./types.js";
|
|
2
3
|
/** Options for {@link ansariTest}. */
|
|
3
4
|
export interface AnsariTestOptions {
|
|
@@ -26,5 +27,16 @@ export interface AnsariTestOptions {
|
|
|
26
27
|
* r.confInt; // [0.25, 0.6666666666666666]
|
|
27
28
|
* r.estimate; // 0.41666666666666663
|
|
28
29
|
* ```
|
|
30
|
+
*
|
|
31
|
+
* There is also a formula form, `ansariTest("y ~ g", data, options)` (next overload).
|
|
29
32
|
*/
|
|
30
33
|
export declare function ansariTest(x: Sample, y: Sample, options?: AnsariTestOptions): HTest;
|
|
34
|
+
/**
|
|
35
|
+
* Ansari-Bradley test from a formula and a data frame. Equivalent to R's `ansari.test(formula, data)`: `"y ~ g"`
|
|
36
|
+
* compares the two levels of `g` (the first level is `x`). Only the variables of the formula count: the rows where
|
|
37
|
+
* one of them is missing are dropped.
|
|
38
|
+
*
|
|
39
|
+
* @param formula `"y ~ g"`.
|
|
40
|
+
* @param data The data frame: an object of columns (`null` or `NaN` for a missing value).
|
|
41
|
+
*/
|
|
42
|
+
export declare function ansariTest(formula: string, data: DataFrame, options?: AnsariTestOptions): HTest;
|
package/dist/htest/ansariTest.js
CHANGED
|
@@ -20,25 +20,13 @@ import { pnorm, qnorm } from "../distributions/normal.js";
|
|
|
20
20
|
import { rank } from "../internal/summary.js";
|
|
21
21
|
import { uniroot } from "../internal/uniroot.js";
|
|
22
22
|
import { pansariExact, qansariR } from "./core/ansari.js";
|
|
23
|
+
import { twoGroupData } from "./testFormula.js";
|
|
23
24
|
import { checkConfLevelOpen, matchAlternative } from "./types.js";
|
|
24
|
-
/**
|
|
25
|
-
* Ansari-Bradley test that two samples differ in scale. Equivalent to R's `ansari.test()`.
|
|
26
|
-
* `NaN` values are dropped.
|
|
27
|
-
*
|
|
28
|
-
* With `confInt: true`, `confInt` is the interval for the ratio of the scales of `x` and `y` and `estimate` its
|
|
29
|
-
* estimate, both computed with the locations taken as 0 (exact without ties when both samples have fewer than 50
|
|
30
|
-
* values, otherwise by the normal approximation, whose limits are roots found to a tolerance of 1e-4 as in R). Limits
|
|
31
|
-
* that cannot be formed (the samples differ in location) are `NaN`. With ties and `exact` unset or `true`, R fails
|
|
32
|
-
* ("object 'cint' not found"); rStats.js returns the normal-approximation interval, as with `exact: false`.
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* ```ts
|
|
36
|
-
* const r = ansariTest([-2, -1, 1, 2], [-4, -3, 3, 4], { confInt: true });
|
|
37
|
-
* r.confInt; // [0.25, 0.6666666666666666]
|
|
38
|
-
* r.estimate; // 0.41666666666666663
|
|
39
|
-
* ```
|
|
40
|
-
*/
|
|
41
25
|
export function ansariTest(x, y, options = {}) {
|
|
26
|
+
if (typeof x === "string") {
|
|
27
|
+
const d = twoGroupData(x, y);
|
|
28
|
+
return ansariTest(d.x, d.y, options);
|
|
29
|
+
}
|
|
42
30
|
const xs = Array.from(x).filter((v) => !Number.isNaN(v));
|
|
43
31
|
const ys = Array.from(y).filter((v) => !Number.isNaN(v));
|
|
44
32
|
const m = xs.length;
|
package/dist/htest/aov.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { type AovStrataFit } from "../models/aovStrata.js";
|
|
2
|
+
import { type LmFormulaOptions, type LmFormulaResult } from "../models/lm.js";
|
|
3
|
+
import type { DataFrame } from "../models/modelFrame.js";
|
|
1
4
|
import { type GroupLabel } from "./groups.js";
|
|
2
5
|
import { type Alternative, type HTest, type Sample } from "./types.js";
|
|
3
6
|
/** Result of {@link aov}: the one-way ANOVA table, rows "between groups" and "residuals". */
|
|
@@ -27,6 +30,22 @@ export interface AovResult {
|
|
|
27
30
|
* ```
|
|
28
31
|
*/
|
|
29
32
|
export declare function aov(x: Sample | readonly Sample[], g?: readonly GroupLabel[]): AovResult;
|
|
33
|
+
/**
|
|
34
|
+
* Analysis of variance from a model formula. Equivalent to R's `aov(formula, data)` (with `weights` and
|
|
35
|
+
* `contrasts`): the same fit as {@link lm} with a formula; {@link aovSummary} gives the table of R's
|
|
36
|
+
* `summary(aov(...))`. With one `Error()` term (`y ~ W + Error(id/W)`) the fit has error strata: the result is an
|
|
37
|
+
* {@link AovStrataFit} whose tables {@link aovSummary} returns, one per stratum.
|
|
38
|
+
*
|
|
39
|
+
* @param formula A formula such as `"y ~ A * B"`.
|
|
40
|
+
* @param data The data frame: an object of columns.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* const fit = aov("y ~ g", { y: [4.2, 5.1, 6.3, 5.8, 7.9, 8.4], g: ["a", "a", "b", "b", "c", "c"] });
|
|
45
|
+
* aovSummary(fit).rowNames; // ["g", "Residuals"]
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare function aov(formula: string, data: DataFrame, options?: LmFormulaOptions): LmFormulaResult | AovStrataFit;
|
|
30
49
|
/** Options for {@link TukeyHSD}. */
|
|
31
50
|
export interface TukeyHSDOptions {
|
|
32
51
|
/** Family-wise confidence level. Default `0.95`. */
|
package/dist/htest/aov.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// One-way analysis of variance (the table of R's summary(aov(y ~ g))),
|
|
1
|
+
// One-way analysis of variance (the table of R's summary(aov(y ~ g))), aov from a model formula (the fit of
|
|
2
|
+
// src/models/lm.ts; its table is aovSummary in src/models/anovaSequential.ts), Tukey's honest significant differences (R's
|
|
2
3
|
// TukeyHSD) and the z test with known standard deviations (as BSDA's z.test).
|
|
3
4
|
//
|
|
4
5
|
// Written for rStats.js from the textbook formulas. The sums of squares are accumulated in
|
|
@@ -13,6 +14,10 @@ import { pnorm, qnorm } from "../distributions/normal.js";
|
|
|
13
14
|
import { ptukey, qtukey } from "../distributions/tukey.js";
|
|
14
15
|
import { meanDD } from "../internal/summary.js";
|
|
15
16
|
import { ddAdd, ddMul, ddSub } from "../special/dd.js";
|
|
17
|
+
import { parseFormula, splitErrorTerms } from "../models/formula.js";
|
|
18
|
+
import { aovStrataFit } from "../models/aovStrata.js";
|
|
19
|
+
import { lmFormulaFit } from "../models/lm.js";
|
|
20
|
+
import { design } from "../models/modelMatrix.js";
|
|
16
21
|
import { labelledGroups, toGroups } from "./groups.js";
|
|
17
22
|
import { matchAlternative } from "./types.js";
|
|
18
23
|
function sums(groups) {
|
|
@@ -33,20 +38,22 @@ function sums(groups) {
|
|
|
33
38
|
}
|
|
34
39
|
return { ssb: ssb[0], ssw: ssw[0], means };
|
|
35
40
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
41
|
+
export function aov(x, g, options = {}) {
|
|
42
|
+
if (typeof x === "string")
|
|
43
|
+
return aovFormula(x, g, options);
|
|
44
|
+
return aovOneway(x, g);
|
|
45
|
+
}
|
|
46
|
+
/** aov from a formula (without Error() strata) */
|
|
47
|
+
function aovFormula(formula, data, options) {
|
|
48
|
+
const parsed = parseFormula(formula, true);
|
|
49
|
+
const { treatment, errors } = splitErrorTerms(parsed.rhs);
|
|
50
|
+
if (errors.length > 1)
|
|
51
|
+
throw new Error(`there are ${errors.length} Error terms: only 1 is allowed`);
|
|
52
|
+
if (errors.length === 1)
|
|
53
|
+
return aovStrataFit(formula, parsed, treatment, errors[0], data, options);
|
|
54
|
+
return lmFormulaFit(formula, design(parsed, data, { ...options, dropUnusedLevels: true }, treatment), true);
|
|
55
|
+
}
|
|
56
|
+
function aovOneway(x, g) {
|
|
50
57
|
const groups = toGroups(x, g);
|
|
51
58
|
const k = groups.length;
|
|
52
59
|
if (k < 2)
|
package/dist/htest/cor.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type DD } from "../special/dd.js";
|
|
2
|
+
import type { DataFrame } from "../models/modelFrame.js";
|
|
2
3
|
import { type Alternative, type HTest, type Sample } from "./types.js";
|
|
3
4
|
/** Correlation coefficient: Pearson's r, Kendall's tau or Spearman's rho. */
|
|
4
5
|
export type CorMethod = "pearson" | "kendall" | "spearman";
|
|
@@ -90,6 +91,17 @@ export declare function kendall(x: readonly number[], y: readonly number[]): Ken
|
|
|
90
91
|
*
|
|
91
92
|
* corTest([1, 2, 3, 4, 5, 6], [2, 1, 4, 3, 7, 8], { method: "spearman" });
|
|
92
93
|
* ```
|
|
94
|
+
*
|
|
95
|
+
* There is also a formula form, `corTest("~ x + y", data, options)` (next overload).
|
|
93
96
|
*/
|
|
94
97
|
export declare function corTest(x: Sample, y: Sample, options?: CorTestOptions): CorTestResult;
|
|
98
|
+
/**
|
|
99
|
+
* Test for correlation from a formula and a data frame. Equivalent to R's `cor.test(formula, data)`: the one-sided
|
|
100
|
+
* formula `"~ x + y"` names the two variables. Only they count: the rows where one of them is missing are dropped.
|
|
101
|
+
*
|
|
102
|
+
* @param formula `"~ x + y"` (exactly two variables, no response).
|
|
103
|
+
* @param data The data frame: an object of columns (`null` or `NaN` for a missing value).
|
|
104
|
+
* @param options See {@link CorTestOptions}.
|
|
105
|
+
*/
|
|
106
|
+
export declare function corTest(formula: string, data: DataFrame, options?: CorTestOptions): CorTestResult;
|
|
95
107
|
export {};
|
package/dist/htest/cor.js
CHANGED
|
@@ -27,6 +27,7 @@ import { pt1 } from "../distributions/t.js";
|
|
|
27
27
|
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
28
28
|
import { ddAdd, ddDiv, ddMul, ddSub, twoProd, twoSum } from "../special/dd.js";
|
|
29
29
|
import { completePairs, meanDD, rank, tieCounts } from "../internal/summary.js";
|
|
30
|
+
import { correlationData } from "./testFormula.js";
|
|
30
31
|
import { checkConfLevel, matchAlternative } from "./types.js";
|
|
31
32
|
const METHODS = ["pearson", "kendall", "spearman"];
|
|
32
33
|
function matchMethod(m) {
|
|
@@ -284,34 +285,15 @@ function spearmanTail(n, q, lower) {
|
|
|
284
285
|
return 0;
|
|
285
286
|
return spearmanEdgeworth(n, q, false);
|
|
286
287
|
}
|
|
287
|
-
// ---- cor.test ----
|
|
288
|
-
/**
|
|
289
|
-
* Test for correlation between paired samples. Equivalent to R's `cor.test()`.
|
|
290
|
-
*
|
|
291
|
-
* Supports Pearson's product-moment correlation (t test, with a Fisher-z confidence
|
|
292
|
-
* interval), Kendall's tau and Spearman's rho (exact or approximate p-values, chosen by
|
|
293
|
-
* the same rules as R). Pairs containing `NaN` are dropped; Pearson needs at least 3
|
|
294
|
-
* pairs and the others at least 2. If the correlation is undefined (constant data) the
|
|
295
|
-
* statistic, p-value and estimate are `NaN`. Correlations are computed in double-double
|
|
296
|
-
* arithmetic, so results can differ from R's when r is very close to ±1, where R's own
|
|
297
|
-
* value is less accurate.
|
|
298
|
-
*
|
|
299
|
-
* @param x First sample.
|
|
300
|
-
* @param y Second sample, of the same length as `x`.
|
|
301
|
-
* @param options See {@link CorTestOptions}.
|
|
302
|
-
* @returns The test result; see {@link CorTestResult}.
|
|
303
|
-
*
|
|
304
|
-
* @example
|
|
305
|
-
* ```ts
|
|
306
|
-
* const r = corTest([1, 2, 3, 4, 5, 6], [2, 1, 4, 3, 7, 8]);
|
|
307
|
-
* r.estimate; // 0.9014600868406593
|
|
308
|
-
* r.statistic; // 4.165113148435108 (t, df = 4)
|
|
309
|
-
* r.pValue; // 0.01408675480909387
|
|
310
|
-
*
|
|
311
|
-
* corTest([1, 2, 3, 4, 5, 6], [2, 1, 4, 3, 7, 8], { method: "spearman" });
|
|
312
|
-
* ```
|
|
313
|
-
*/
|
|
314
288
|
export function corTest(x, y, options = {}) {
|
|
289
|
+
if (typeof x === "string") {
|
|
290
|
+
const d = correlationData(x, y);
|
|
291
|
+
return corTest(d.x, d.y, options);
|
|
292
|
+
}
|
|
293
|
+
return corTestSamples(x, y, options);
|
|
294
|
+
}
|
|
295
|
+
/** cor.test's default form */
|
|
296
|
+
function corTestSamples(x, y, options) {
|
|
315
297
|
if (x.length !== y.length)
|
|
316
298
|
throw new TypeError("x and y must have the same length");
|
|
317
299
|
const alternative = matchAlternative(options.alternative);
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
/** R's method suffix for a simulated p-value; B is printed as R's paste() prints a number */
|
|
2
2
|
export declare function simulatedMethod(B: number): string;
|
|
3
|
+
/** A number as R's as.character prints it (15 significant digits, fixed or scientific, whichever is narrower) */
|
|
4
|
+
export declare function formatR(v: number): string;
|
|
@@ -4,7 +4,7 @@ export function simulatedMethod(B) {
|
|
|
4
4
|
return ` with simulated p-value\n\t (based on ${formatR(B)} replicates)`;
|
|
5
5
|
}
|
|
6
6
|
/** A number as R's as.character prints it (15 significant digits, fixed or scientific, whichever is narrower) */
|
|
7
|
-
function formatR(v) {
|
|
7
|
+
export function formatR(v) {
|
|
8
8
|
if (!Number.isFinite(v) || v === 0)
|
|
9
9
|
return String(v);
|
|
10
10
|
const sci = v.toExponential(14).replace(/\.?0+e/, "e");
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upper probability of Dunnett's statistics: P(max T_i >= c) (`twoSided` false) or P(max |T_i| >= c) (`twoSided`
|
|
3
|
+
* true; c is then taken as |c|), with lambda_i = n_i / (n_i + n_0) and df degrees of freedom (Infinity: normal).
|
|
4
|
+
*/
|
|
5
|
+
export declare function pDunnettUpper(c: number, lambda: readonly number[], df: number, twoSided: boolean): number;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Probabilities of Dunnett's many-to-one statistics, computed exactly (to double precision) instead of by randomised
|
|
2
|
+
// multivariate integration.
|
|
3
|
+
//
|
|
4
|
+
// Written for rStats.js from the distribution's definition (no ported code). The statistics comparing groups
|
|
5
|
+
// i = 1..m with a control have, with lambda_i = n_i / (n_i + n_0), the representation
|
|
6
|
+
// T_i = (sqrt(lambda_i) Z_0 + sqrt(1 - lambda_i) Z_i) / U
|
|
7
|
+
// with independent standard normals Z_0, Z_i and U = sqrt(chi^2_df / df) independent of them (U = 1 for df = Inf).
|
|
8
|
+
// Conditionally on Z_0 = z and U = u the T_i are independent, so
|
|
9
|
+
// P(max T_i < c) = E Prod_i Phi((sqrt(lambda_i) z + c u) / sqrt(1 - lambda_i))
|
|
10
|
+
// P(max |T_i| < c) = E Prod_i [Phi((sqrt(lambda_i) z + c u) / sqrt(1 - lambda_i)) - Phi((sqrt(lambda_i) z - c u) / sqrt(1 - lambda_i))]
|
|
11
|
+
// The upper probabilities are integrated directly, as E [1 - Prod_i (1 - q_i)] with 1 - Prod computed as
|
|
12
|
+
// -expm1(sum log1p(-q_i)), so that small p-values keep their relative accuracy. The inner integral over z uses
|
|
13
|
+
// QUADPACK (src/integrate/quadpack.ts) on the whole line; the outer one is over v = log u, where the density of U
|
|
14
|
+
// times du is, with a = df / 2 and Stirling's error term stirlerr (Loader 2000),
|
|
15
|
+
// 2 sqrt(a / (2 pi)) exp(-stirlerr(a) - a (expm1(2 v) - 2 v)) dv,
|
|
16
|
+
// which keeps its relative accuracy for large df.
|
|
17
|
+
import { dqagie } from "../integrate/quadpack.js";
|
|
18
|
+
import { pnorm } from "../distributions/normal.js";
|
|
19
|
+
import { stirlerr } from "../special/loader.js";
|
|
20
|
+
const LOG_2PI = Math.log(2 * Math.PI);
|
|
21
|
+
const REL_TOL = 2e-14;
|
|
22
|
+
const LIMIT = 500;
|
|
23
|
+
function phi(z) {
|
|
24
|
+
return Math.exp(-0.5 * z * z - 0.5 * LOG_2PI);
|
|
25
|
+
}
|
|
26
|
+
/** log(Phi(x)) */
|
|
27
|
+
function logPhi(x) {
|
|
28
|
+
return pnorm(x, { logP: true });
|
|
29
|
+
}
|
|
30
|
+
/** Integral over the whole line with QUADPACK's dqagi at full precision */
|
|
31
|
+
function wholeLine(f, lower = -Infinity) {
|
|
32
|
+
const r = lower === -Infinity ? dqagie(f, 0, 2, 0, REL_TOL, LIMIT) : dqagie(f, lower, 1, 0, REL_TOL, LIMIT);
|
|
33
|
+
return r.result;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Inner probability given w = c u: P(max T_i >= c | U = u) (twoSided false) or P(max |T_i| >= c | U = u) (twoSided
|
|
37
|
+
* true, w >= 0), integrated over Z_0.
|
|
38
|
+
*/
|
|
39
|
+
function conditionalUpper(w, lambda, twoSided) {
|
|
40
|
+
const sl = lambda.map(Math.sqrt);
|
|
41
|
+
const s = lambda.map((l) => Math.sqrt(1 - l));
|
|
42
|
+
const f = (z) => {
|
|
43
|
+
// log of the conditional probability that no statistic exceeds c
|
|
44
|
+
let logIn = 0;
|
|
45
|
+
for (let i = 0; i < sl.length; i++) {
|
|
46
|
+
const a = (sl[i] * z + w) / s[i];
|
|
47
|
+
if (!twoSided) {
|
|
48
|
+
logIn += logPhi(a);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const b = (sl[i] * z - w) / s[i];
|
|
52
|
+
// probability outside (b, a): Phi(b) + (1 - Phi(a))
|
|
53
|
+
const q = pnorm(b) + pnorm(a, { lowerTail: false });
|
|
54
|
+
if (q < 0.5)
|
|
55
|
+
logIn += Math.log1p(-q);
|
|
56
|
+
else
|
|
57
|
+
logIn += Math.log(a + b < 0 ? pnorm(a) - pnorm(b) : pnorm(b, { lowerTail: false }) - pnorm(a, { lowerTail: false }));
|
|
58
|
+
}
|
|
59
|
+
return phi(z) * -Math.expm1(logIn);
|
|
60
|
+
};
|
|
61
|
+
return wholeLine(f);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Upper probability of Dunnett's statistics: P(max T_i >= c) (`twoSided` false) or P(max |T_i| >= c) (`twoSided`
|
|
65
|
+
* true; c is then taken as |c|), with lambda_i = n_i / (n_i + n_0) and df degrees of freedom (Infinity: normal).
|
|
66
|
+
*/
|
|
67
|
+
export function pDunnettUpper(c, lambda, df, twoSided) {
|
|
68
|
+
if (Number.isNaN(c) || Number.isNaN(df))
|
|
69
|
+
return NaN;
|
|
70
|
+
if (twoSided)
|
|
71
|
+
c = Math.abs(c);
|
|
72
|
+
if (c === Infinity)
|
|
73
|
+
return 0;
|
|
74
|
+
if (c === -Infinity)
|
|
75
|
+
return 1;
|
|
76
|
+
if (twoSided && c === 0)
|
|
77
|
+
return 1;
|
|
78
|
+
if (df === Infinity)
|
|
79
|
+
return Math.min(1, conditionalUpper(c, lambda, twoSided));
|
|
80
|
+
const a = df / 2;
|
|
81
|
+
const logConst = Math.log(2) + 0.5 * Math.log(a) - 0.5 * LOG_2PI - stirlerr(a);
|
|
82
|
+
const g = (v) => {
|
|
83
|
+
const ld = logConst - a * (Math.expm1(2 * v) - 2 * v);
|
|
84
|
+
if (ld < -745)
|
|
85
|
+
return 0;
|
|
86
|
+
return Math.exp(ld) * conditionalUpper(c * Math.exp(v), lambda, twoSided);
|
|
87
|
+
};
|
|
88
|
+
return Math.min(1, wholeLine(g));
|
|
89
|
+
}
|