@numero-uno-jpn/rstats 0.15.3 → 0.16.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 (285) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +24 -4
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +12 -4
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +5 -0
  52. package/dist/distributions/f.js +32 -17
  53. package/dist/distributions/gamma.js +27 -3
  54. package/dist/distributions/geometric.js +49 -13
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +2 -1
  58. package/dist/distributions/laplace.js +27 -6
  59. package/dist/distributions/logistic.js +4 -1
  60. package/dist/distributions/lognormal.js +8 -2
  61. package/dist/distributions/multinomial.js +54 -11
  62. package/dist/distributions/nbeta.js +62 -11
  63. package/dist/distributions/nchisq.js +30 -6
  64. package/dist/distributions/negbinomial.js +94 -17
  65. package/dist/distributions/normal.js +9 -4
  66. package/dist/distributions/nt.js +392 -17
  67. package/dist/distributions/pareto.js +4 -1
  68. package/dist/distributions/poisson.js +28 -3
  69. package/dist/distributions/signrank.js +7 -4
  70. package/dist/distributions/summary.js +450 -60
  71. package/dist/distributions/triangular.js +10 -5
  72. package/dist/distributions/tukey.js +5 -2
  73. package/dist/distributions/weibull.js +10 -0
  74. package/dist/distributions/wilcox.d.ts +9 -3
  75. package/dist/distributions/wilcox.js +155 -26
  76. package/dist/distributions.js +2 -2
  77. package/dist/htest/agreement.d.ts +3 -2
  78. package/dist/htest/agreement.js +76 -14
  79. package/dist/htest/ansariTest.d.ts +6 -1
  80. package/dist/htest/ansariTest.js +75 -8
  81. package/dist/htest/aov.d.ts +1 -1
  82. package/dist/htest/aov.js +48 -34
  83. package/dist/htest/binomTest.d.ts +5 -0
  84. package/dist/htest/binomTest.js +41 -17
  85. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  86. package/dist/htest/brunnerMunzelTest.js +7 -5
  87. package/dist/htest/chisqTest.d.ts +2 -1
  88. package/dist/htest/chisqTest.js +130 -43
  89. package/dist/htest/cor.d.ts +2 -1
  90. package/dist/htest/cor.js +17 -19
  91. package/dist/htest/core/ansari.d.ts +9 -0
  92. package/dist/htest/core/ansari.js +21 -1
  93. package/dist/htest/core/kolmogorov.d.ts +25 -0
  94. package/dist/htest/core/kolmogorov.js +123 -0
  95. package/dist/htest/core/mantelhaen.js +6 -4
  96. package/dist/htest/core/shapiro.d.ts +1 -1
  97. package/dist/htest/core/shapiro.js +5 -1
  98. package/dist/htest/dunnett.js +14 -5
  99. package/dist/htest/effectSize.d.ts +2 -0
  100. package/dist/htest/effectSize.js +91 -29
  101. package/dist/htest/fisherTest.d.ts +2 -2
  102. package/dist/htest/fisherTest.js +36 -18
  103. package/dist/htest/groups.d.ts +7 -0
  104. package/dist/htest/groups.js +21 -4
  105. package/dist/htest/ksTest.d.ts +3 -1
  106. package/dist/htest/ksTest.js +23 -2
  107. package/dist/htest/leveneTest.js +19 -3
  108. package/dist/htest/mantelhaenTest.js +125 -25
  109. package/dist/htest/mcnemarTest.js +32 -11
  110. package/dist/htest/multipleComparisons.d.ts +8 -1
  111. package/dist/htest/multipleComparisons.js +44 -21
  112. package/dist/htest/normalityTests.js +44 -10
  113. package/dist/htest/onewayTest.js +96 -5
  114. package/dist/htest/pAdjust.d.ts +3 -2
  115. package/dist/htest/pAdjust.js +38 -6
  116. package/dist/htest/pairwise.d.ts +1 -1
  117. package/dist/htest/pairwise.js +17 -15
  118. package/dist/htest/poissonTest.d.ts +1 -1
  119. package/dist/htest/poissonTest.js +111 -59
  120. package/dist/htest/polycor.js +27 -7
  121. package/dist/htest/power.d.ts +11 -1
  122. package/dist/htest/power.js +112 -8
  123. package/dist/htest/propTest.js +21 -4
  124. package/dist/htest/pwr.js +121 -24
  125. package/dist/htest/rankTests.js +29 -5
  126. package/dist/htest/tTest.js +44 -21
  127. package/dist/htest/trendTests.d.ts +7 -3
  128. package/dist/htest/trendTests.js +114 -20
  129. package/dist/htest/types.d.ts +5 -0
  130. package/dist/htest/types.js +7 -0
  131. package/dist/htest/varTest.js +45 -14
  132. package/dist/htest/wilcoxTest.js +114 -21
  133. package/dist/integrate/quadpack.js +27 -5
  134. package/dist/internal/covmat.d.ts +5 -0
  135. package/dist/internal/covmat.js +20 -0
  136. package/dist/internal/ddexp.d.ts +15 -1
  137. package/dist/internal/ddexp.js +59 -6
  138. package/dist/internal/discrete.d.ts +14 -0
  139. package/dist/internal/discrete.js +78 -5
  140. package/dist/internal/extremes.d.ts +9 -0
  141. package/dist/internal/extremes.js +24 -0
  142. package/dist/internal/fround.js +13 -4
  143. package/dist/internal/integer.d.ts +9 -0
  144. package/dist/internal/integer.js +12 -0
  145. package/dist/internal/invert.js +15 -2
  146. package/dist/internal/scaledInverse.d.ts +10 -0
  147. package/dist/internal/scaledInverse.js +22 -0
  148. package/dist/internal/seq.js +15 -2
  149. package/dist/internal/summary.d.ts +90 -0
  150. package/dist/internal/summary.js +458 -39
  151. package/dist/internal/uniroot.d.ts +7 -0
  152. package/dist/internal/uniroot.js +28 -3
  153. package/dist/linalg/basic.d.ts +3 -1
  154. package/dist/linalg/basic.js +51 -7
  155. package/dist/linalg/chol.js +4 -1
  156. package/dist/linalg/dot.d.ts +29 -0
  157. package/dist/linalg/dot.js +132 -0
  158. package/dist/linalg/eigen.d.ts +6 -1
  159. package/dist/linalg/eigen.js +71 -14
  160. package/dist/linalg/expm.d.ts +3 -2
  161. package/dist/linalg/expm.js +109 -15
  162. package/dist/linalg/kappa.js +58 -10
  163. package/dist/linalg/lu.d.ts +2 -1
  164. package/dist/linalg/lu.js +35 -5
  165. package/dist/linalg/matrix.d.ts +14 -0
  166. package/dist/linalg/matrix.js +24 -0
  167. package/dist/linalg/ops.js +60 -13
  168. package/dist/linalg/qr.d.ts +2 -1
  169. package/dist/linalg/qr.js +91 -23
  170. package/dist/linalg/schur.js +11 -3
  171. package/dist/linalg/solve.d.ts +6 -1
  172. package/dist/linalg/solve.js +147 -26
  173. package/dist/linalg/svd.d.ts +9 -2
  174. package/dist/linalg/svd.js +29 -11
  175. package/dist/linalg.js +2 -2
  176. package/dist/mixed.js +4 -4
  177. package/dist/models/anovaSequential.d.ts +16 -1
  178. package/dist/models/anovaSequential.js +124 -25
  179. package/dist/models/aovEz.js +140 -30
  180. package/dist/models/aovStrata.js +55 -22
  181. package/dist/models/carAnova.d.ts +1 -1
  182. package/dist/models/carAnova.js +83 -32
  183. package/dist/models/coxph.js +148 -66
  184. package/dist/models/estimable.d.ts +15 -0
  185. package/dist/models/estimable.js +68 -0
  186. package/dist/models/formula.d.ts +1 -1
  187. package/dist/models/formula.js +26 -8
  188. package/dist/models/glm.d.ts +35 -5
  189. package/dist/models/glm.js +398 -55
  190. package/dist/models/glmAnova.js +84 -13
  191. package/dist/models/glmConfint.d.ts +1 -1
  192. package/dist/models/glmConfint.js +115 -27
  193. package/dist/models/glmFamily.d.ts +10 -0
  194. package/dist/models/glmFamily.js +244 -40
  195. package/dist/models/lm.d.ts +12 -1
  196. package/dist/models/lm.js +235 -36
  197. package/dist/models/lmer.d.ts +20 -1
  198. package/dist/models/lmer.js +109 -27
  199. package/dist/models/lmerAnova.js +37 -4
  200. package/dist/models/lmerHypotheses.d.ts +6 -2
  201. package/dist/models/lmerHypotheses.js +14 -2
  202. package/dist/models/lmerTest.d.ts +9 -2
  203. package/dist/models/lmerTest.js +64 -19
  204. package/dist/models/mauchly.d.ts +4 -1
  205. package/dist/models/mauchly.js +34 -13
  206. package/dist/models/mixedStructure.js +6 -0
  207. package/dist/models/modelFrame.js +8 -2
  208. package/dist/models/modelMatrix.d.ts +3 -1
  209. package/dist/models/modelMatrix.js +40 -15
  210. package/dist/models/scaledTables.d.ts +8 -0
  211. package/dist/models/scaledTables.js +6 -0
  212. package/dist/models/survival.d.ts +6 -1
  213. package/dist/models/survival.js +67 -27
  214. package/dist/models/tiedTimes.d.ts +2 -0
  215. package/dist/models/tiedTimes.js +34 -0
  216. package/dist/numerics/deriv.d.ts +1 -1
  217. package/dist/numerics/deriv.js +64 -8
  218. package/dist/numerics/integrate.d.ts +9 -1
  219. package/dist/numerics/integrate.js +103 -16
  220. package/dist/numerics/interp.d.ts +8 -2
  221. package/dist/numerics/interp.js +352 -50
  222. package/dist/numerics/ode.js +55 -1
  223. package/dist/numerics.js +2 -2
  224. package/dist/optim/localmin.js +4 -0
  225. package/dist/optim/optim.d.ts +3 -1
  226. package/dist/optim/optim.js +80 -8
  227. package/dist/random/beta.js +53 -4
  228. package/dist/random/binomial.d.ts +14 -3
  229. package/dist/random/binomial.js +59 -24
  230. package/dist/random/continuous.js +33 -5
  231. package/dist/random/extra.js +42 -9
  232. package/dist/random/gamma.d.ts +4 -1
  233. package/dist/random/gamma.js +36 -8
  234. package/dist/random/hyper.js +9 -6
  235. package/dist/random/mt.js +17 -2
  236. package/dist/random/poisson.js +26 -3
  237. package/dist/random/r2dtable.d.ts +8 -1
  238. package/dist/random/r2dtable.js +24 -3
  239. package/dist/random/rank.d.ts +2 -0
  240. package/dist/random/rank.js +44 -4
  241. package/dist/random/sample.d.ts +12 -2
  242. package/dist/random/sample.js +57 -20
  243. package/dist/random/streams.js +4 -2
  244. package/dist/rstats.js +14 -14
  245. package/dist/special/besselIK.d.ts +12 -0
  246. package/dist/special/besselIK.js +168 -23
  247. package/dist/special/besselJY.d.ts +11 -1
  248. package/dist/special/besselJY.js +127 -19
  249. package/dist/special/besselSeries.d.ts +27 -0
  250. package/dist/special/besselSeries.js +45 -2
  251. package/dist/special/beta.js +4 -1
  252. package/dist/special/choose.js +17 -8
  253. package/dist/special/dd.js +122 -18
  254. package/dist/special/extra.js +14 -2
  255. package/dist/special/gamma.js +11 -2
  256. package/dist/special/incbet.js +30 -4
  257. package/dist/special/incbetTemme.d.ts +7 -0
  258. package/dist/special/incbetTemme.js +45 -12
  259. package/dist/special/loader.d.ts +1 -1
  260. package/dist/special/loader.js +117 -20
  261. package/dist/special/log1pmx.js +4 -0
  262. package/dist/special.js +2 -2
  263. package/dist/tests.js +11 -11
  264. package/llms.txt +12 -6
  265. package/package.json +1 -1
  266. package/dist/chunks/chunk-3THFTB36.js +0 -2
  267. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  268. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  269. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  270. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  271. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  272. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  273. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  274. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  275. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  276. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  277. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  278. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  279. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  280. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  281. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  282. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  283. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  284. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  285. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -16,6 +16,7 @@
16
16
  import { pgamma1 } from "../distributions/gamma.js";
17
17
  import { pnorm, qnorm } from "../distributions/normal.js";
18
18
  import { solve } from "../linalg/solve.js";
19
+ import { ldexp, productOver, squareOver } from "../internal/summary.js";
19
20
  import { ddAdd } from "../special/dd.js";
20
21
  import { ConvolvedNoncentralHyper, conditionalMLE, lowerLimit, upperLimit } from "./core/mantelhaen.js";
21
22
  import { checkConfLevelOpen, matchAlternative } from "./types.js";
@@ -55,7 +56,7 @@ export function mantelhaenTest(strata, options = {}) {
55
56
  if (t.some((r) => r.some((v) => !Number.isFinite(v) || v < 0)))
56
57
  throw new RangeError("all entries of 'x' must be nonnegative and finite");
57
58
  }
58
- const totals = strata.map((t) => t.reduce((a, r) => a + r.reduce((b, v) => b + v, 0), 0));
59
+ const totals = strata.map(stratumTotal);
59
60
  if (totals.some((t) => t < 2))
60
61
  throw new RangeError("sample size in each stratum must be > 1");
61
62
  const alternative = matchAlternative(options.alternative);
@@ -64,13 +65,50 @@ export function mantelhaenTest(strata, options = {}) {
64
65
  const confLevel = options.confLevel ?? 0.95;
65
66
  checkConfLevelOpen(confLevel);
66
67
  if (I === 2 && J === 2) {
68
+ // the exact conditional distribution is over integer tables (R takes fractional counts and returns a result)
69
+ if (exact && strata.some((t) => t.some((r) => r.some((v) => !Number.isInteger(v))))) {
70
+ throw new RangeError("the exact test needs integer counts");
71
+ }
72
+ // from 2^53 on the counts are not exact integers and the loop over a stratum's support does not advance (x + 1
73
+ // rounds to x; #494); the total bounds every cell, margin and sum over the strata
74
+ if (exact && totals.reduce((a, t) => a + t, 0) > Number.MAX_SAFE_INTEGER) {
75
+ throw new RangeError("the exact test needs counts with a total below 2^53: use exact: false");
76
+ }
67
77
  const tables = strata.map((t) => [[t[0][0], t[0][1]], [t[1][0], t[1][1]]]);
68
78
  return exact ? exact2x2xK(tables, alternative, confLevel) : asymptotic2x2xK(tables, totals, alternative, correct, confLevel);
69
79
  }
70
80
  // as in R, exact applies to 2 x 2 x K tables only and is ignored otherwise
71
81
  return general(strata, totals, I, J);
72
82
  }
73
- function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
83
+ /** Sum of the counts of one stratum */
84
+ function stratumTotal(t) {
85
+ return t.reduce((a, r) => a + r.reduce((b, v) => b + v, 0), 0);
86
+ }
87
+ /**
88
+ * The even power of 2 to divide all counts by where the totals or sums over the strata overflow: the largest count
89
+ * then below 2^1020 / (8 I J K), so that the totals and the sums over the strata are finite (#224, #226). The
90
+ * statistics are homogeneous in the counts (the count 1 in t - 1 becomes 2^-s), so they are scaled back exactly
91
+ */
92
+ function countExponent(strata) {
93
+ let m = 0;
94
+ let cells = 0;
95
+ for (const t of strata) {
96
+ for (const r of t) {
97
+ for (const v of r) {
98
+ m = Math.max(m, v);
99
+ cells++;
100
+ }
101
+ }
102
+ }
103
+ const s = Math.floor(Math.log2(m)) + 1 + Math.ceil(Math.log2(8 * cells)) - 1020;
104
+ return s <= 0 ? 0 : s + (s % 2);
105
+ }
106
+ /** The strata with every count divided by 2^s */
107
+ function scaledStrata(strata, s) {
108
+ return strata.map((t) => t.map((r) => r.map((v) => ldexp(v, -s))));
109
+ }
110
+ /** Sums over the strata of the 2 x 2 x K test, in units of 2^s counts (one = 2^-s is the count 1 in those units) */
111
+ function sums2x2xK(tables, totals, one) {
74
112
  let sa = 0;
75
113
  let se = 0;
76
114
  let sv = 0;
@@ -86,33 +124,56 @@ function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
86
124
  const c1 = a + c;
87
125
  const c2 = b + d;
88
126
  sa += a;
89
- se += (r1 * c1) / t;
90
- sv += (r1 * r2 * c1 * c2) / (t * t * (t - 1));
127
+ // products of counts near 1e150 overflow (the variance was Infinity / Infinity = NaN; R too): the ratios first there
128
+ const e = (r1 * c1) / t;
129
+ se += Number.isFinite(e) ? e : (r1 / t) * c1;
130
+ const v = (r1 * r2 * c1 * c2) / (t * t * (t - one));
131
+ sv += Number.isFinite(v) ? v : (r1 / t) * (r2 / t) * (c1 / (t - one)) * c2;
91
132
  const P = (a + d) / t;
92
133
  const Q = (b + c) / t;
93
- const R = (a * d) / t;
94
- const S = (b * c) / t;
134
+ const ad = (a * d) / t;
135
+ const bc = (b * c) / t;
136
+ const R = Number.isFinite(ad) ? ad : (a / t) * d;
137
+ const S = Number.isFinite(bc) ? bc : (b / t) * c;
95
138
  sR += R;
96
139
  sS += S;
97
140
  sPR += P * R;
98
141
  sPSQR += P * S + Q * R;
99
142
  sQS += Q * S;
100
143
  });
144
+ return { sa, se, sv, sR, sS, sPR, sPSQR, sQS };
145
+ }
146
+ function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
147
+ let sums = sums2x2xK(tables, totals, 1);
148
+ // a total or a sum over the strata overflows (finite counts near 1e308; NaN before, R fails, #226): all counts
149
+ // divided by an even power of 2, 2^s. The differences, variances and odds ratio terms are of degree 1 in the
150
+ // counts, so the statistic is 2^s times the scaled one, the estimate unchanged, and the sd of its log 2^(-s/2) times
151
+ let s = 0;
152
+ if (!totals.every(Number.isFinite) || !Object.values(sums).every(Number.isFinite)) {
153
+ s = countExponent(tables);
154
+ const scaled = scaledStrata(tables, s);
155
+ sums = sums2x2xK(scaled, scaled.map(stratumTotal), ldexp(1, -s));
156
+ }
157
+ const { sa, se, sv, sR, sS, sPR, sPSQR, sQS } = sums;
101
158
  const delta = sa - se;
102
- const yates = correct && Math.abs(delta) >= 0.5 ? 0.5 : 0;
103
- const statistic = (Math.abs(delta) - yates) ** 2 / sv;
159
+ // the correction 1/2 in the units of the sums
160
+ const half = ldexp(0.5, -s);
161
+ const yates = correct && Math.abs(delta) >= half ? half : 0;
162
+ const statistic = ldexp(squareOver(Math.abs(delta) - yates, sv), s);
104
163
  const pValue = alternative === "two.sided"
105
164
  ? pgamma1(statistic, 0.5, 2, false, false)
106
165
  : pnorm(Math.sign(delta) * Math.sqrt(statistic), { lowerTail: alternative === "less" });
107
166
  const estimate = sR / sS;
108
- const sd = Math.sqrt(sPR / (2 * sR * sR) + sPSQR / (2 * sR * sS) + sQS / (2 * sS * sS));
167
+ const sd = ldexp(Math.sqrt(sPR / (2 * sR * sR) + sPSQR / (2 * sR * sS) + sQS / (2 * sS * sS)), -s / 2);
109
168
  let confInt;
110
169
  if (alternative === "less")
111
170
  confInt = [0, estimate * Math.exp(qnorm(confLevel) * sd)];
112
171
  else if (alternative === "greater")
113
172
  confInt = [estimate * Math.exp(qnorm(confLevel, { lowerTail: false }) * sd), Infinity];
114
173
  else {
115
- const z = qnorm((1 + confLevel) / 2);
174
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
175
+ const a2 = (1 - confLevel) / 2;
176
+ const z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + confLevel) / 2);
116
177
  confInt = [estimate * Math.exp(-z * sd), estimate * Math.exp(z * sd)];
117
178
  }
118
179
  return {
@@ -131,8 +192,20 @@ function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
131
192
  nullValueName: "common odds ratio",
132
193
  };
133
194
  }
195
+ /**
196
+ * Largest support (number of values of S) of the exact test: 2^24 values take a few hundred MB (one large stratum
197
+ * near 2^24 takes about 40 s; several large strata take longer, as the convolution grows with the product of their
198
+ * spreads); R allocates every stratum's support whatever its size (counts of 1e9 would take 16 GB per stratum)
199
+ */
200
+ const MAX_SUPPORT = 2 ** 24;
134
201
  /** Exact conditional test on 2 x 2 x K tables: S = sum of the (1, 1) cells given all margins */
135
202
  function exact2x2xK(tables, alternative, confLevel) {
203
+ // the support of S has 1 + sum (min(a, d) + min(b, c)) values (each stratum's support and every partial
204
+ // convolution are no longer); checked before any of them is allocated
205
+ const size = tables.reduce((acc, [[a, b], [c, d]]) => acc + Math.min(a, d) + Math.min(b, c), 1);
206
+ if (size > MAX_SUPPORT) {
207
+ throw new RangeError(`the exact distribution of S has ${size} values, more than 2^24: use exact: false`);
208
+ }
136
209
  const h = new ConvolvedNoncentralHyper(tables);
137
210
  const s = tables.reduce((acc, t) => acc + t[0][0], 0);
138
211
  let pValue;
@@ -172,6 +245,36 @@ function exact2x2xK(tables, alternative, confLevel) {
172
245
  };
173
246
  }
174
247
  function general(strata, totals, I, J) {
248
+ let { diff, V } = generalSums(strata, totals, I, J, 1);
249
+ // a total or a sum over the strata overflows: all counts divided by 2^s (see countExponent); the differences and
250
+ // the covariance are of degree 1 in the counts, so the statistic is 2^s times the scaled one
251
+ let s = 0;
252
+ if (!totals.every(Number.isFinite) || !diff.every(Number.isFinite) || !V.every((row) => row.every(Number.isFinite))) {
253
+ s = countExponent(strata);
254
+ const scaled = scaledStrata(strata, s);
255
+ ({ diff, V } = generalSums(scaled, scaled.map(stratumTotal), I, J, ldexp(1, -s)));
256
+ }
257
+ const p = diff.length;
258
+ const sol = solve(V, diff);
259
+ let statistic = 0;
260
+ for (let u = 0; u < p; u++)
261
+ statistic += diff[u] * sol[u];
262
+ statistic = ldexp(statistic, s);
263
+ return {
264
+ method: "Cochran-Mantel-Haenszel test",
265
+ statistic,
266
+ statisticName: "Cochran-Mantel-Haenszel M^2",
267
+ parameter: p,
268
+ parameterName: "df",
269
+ pValue: pgamma1(statistic, p / 2, 2, false, false),
270
+ };
271
+ }
272
+ const MIN_NORMAL = 2 ** -1022;
273
+ /**
274
+ * The differences n - m and the covariance V of the generalized statistic, summed over the strata, in units of 2^s
275
+ * counts (one = 2^-s is the count 1 in those units)
276
+ */
277
+ function generalSums(strata, totals, I, J, one) {
175
278
  const p = (I - 1) * (J - 1);
176
279
  const diff = new Array(p).fill(0);
177
280
  const V = Array.from({ length: p }, () => new Array(p).fill(0));
@@ -179,32 +282,29 @@ function general(strata, totals, I, J) {
179
282
  const t = totals[k];
180
283
  const r = tab.map((row) => row.reduce((a, b) => a + b, 0));
181
284
  const c = Array.from({ length: J }, (_, j) => tab.reduce((a, row) => a + row[j], 0));
182
- const f = 1 / (t * t * (t - 1));
285
+ const f = 1 / (t * t * (t - one));
183
286
  // cell (i, j) of the first I - 1 rows and J - 1 columns is element i + (I - 1) j (column-major, as in R)
184
287
  for (let j = 0; j < J - 1; j++) {
185
288
  for (let i = 0; i < I - 1; i++) {
186
289
  const u = i + (I - 1) * j;
187
- diff[u] += tab[i][j] - (r[i] * c[j]) / t;
290
+ // a product of margins near 1e154 overflows: formed from the margins scaled to [1, 2) there
291
+ const e = (r[i] * c[j]) / t;
292
+ diff[u] += tab[i][j] - (Number.isFinite(e) ? e : productOver(r[i], c[j], t));
188
293
  for (let jj = 0; jj < J - 1; jj++) {
189
294
  for (let ii = 0; ii < I - 1; ii++) {
190
295
  const vr = (i === ii ? t * r[i] : 0) - r[i] * r[ii];
191
296
  const vc = (j === jj ? t * c[j] : 0) - c[j] * c[jj];
192
- V[u][ii + (I - 1) * jj] += f * vr * vc;
297
+ const v = f * vr * vc;
298
+ // t^2 (t - 1) or the product overflows from counts near 1e103 (0 times Infinity was NaN; R fails, #224):
299
+ // r_i (d_ii - r_ii / t) (d_jj - c_jj / t) c_j / (t - 1) there, each factor in range
300
+ V[u][ii + (I - 1) * jj] +=
301
+ Number.isFinite(v) && f >= MIN_NORMAL
302
+ ? v
303
+ : r[i] * ((i === ii ? 1 : 0) - r[ii] / t) * (((j === jj ? 1 : 0) - c[jj] / t) * (c[j] / (t - one)));
193
304
  }
194
305
  }
195
306
  }
196
307
  }
197
308
  });
198
- const sol = solve(V, diff);
199
- let statistic = 0;
200
- for (let u = 0; u < p; u++)
201
- statistic += diff[u] * sol[u];
202
- return {
203
- method: "Cochran-Mantel-Haenszel test",
204
- statistic,
205
- statisticName: "Cochran-Mantel-Haenszel M^2",
206
- parameter: p,
207
- parameterName: "df",
208
- pValue: pgamma1(statistic, p / 2, 2, false, false),
209
- };
309
+ return { diff, V };
210
310
  }
@@ -2,9 +2,10 @@
2
2
  //
3
3
  // Written for rStats.js from the textbook construction (McNemar, Psychometrika 12, 1947; no ported code):
4
4
  // sum over i < j of (n_ij - n_ji)^2 / (n_ij + n_ji), chi-squared with r (r - 1) / 2 degrees of freedom. For a 2 x 2
5
- // table the continuity correction replaces |n_12 - n_21| by |n_12 - n_21| - 1.
5
+ // table the continuity correction replaces |n_12 - n_21| by max(0, |n_12 - n_21| - 1).
6
6
  import { pgamma1 } from "../distributions/gamma.js";
7
- import { numberLevels } from "../internal/levels.js";
7
+ import { ldexp, squareOver } from "../internal/summary.js";
8
+ import { compareLabels, factorLabels } from "./groups.js";
8
9
  /**
9
10
  * McNemar's chi-squared test for symmetry of rows and columns in a square table of counts. Equivalent to R's
10
11
  * `mcnemar.test()`. Takes a matrix, or two factors given as paired category codes.
@@ -46,17 +47,27 @@ export function mcnemarTest(x, y, options = {}) {
46
47
  if (useCorrection) {
47
48
  const b = table[0][1];
48
49
  const c = table[1][0];
49
- statistic = (Math.abs(b - c) - 1) ** 2 / (b + c);
50
+ // the correction stops at 0: with fractional counts abs(b - c) can be below 1, and (abs(b - c) - 1)^2 would make the
51
+ // statistic larger than without it (R squares the negative difference; its chisq.test and prop.test clamp)
52
+ statistic = pairTerm(Math.max(0, Math.abs(b - c) - 1), b, c);
50
53
  }
51
54
  else {
52
55
  statistic = 0;
56
+ // a pair of cells with no discordant counts adds nothing (0 / 0 made the statistic NaN; R too); with none at all
57
+ // there is nothing to test
58
+ let terms = 0;
53
59
  for (let i = 0; i < r; i++) {
54
60
  for (let j = i + 1; j < r; j++) {
55
61
  const a = table[i][j];
56
62
  const b = table[j][i];
57
- statistic += (a - b) ** 2 / (a + b);
63
+ if (a + b === 0)
64
+ continue;
65
+ statistic += pairTerm(a - b, a, b);
66
+ terms++;
58
67
  }
59
68
  }
69
+ if (terms === 0)
70
+ throw new RangeError("the table has no discordant pairs");
60
71
  }
61
72
  const df = (r * (r - 1)) / 2;
62
73
  return {
@@ -68,19 +79,29 @@ export function mcnemarTest(x, y, options = {}) {
68
79
  pValue: pgamma1(statistic, df / 2, 2, false, false),
69
80
  };
70
81
  }
82
+ /**
83
+ * d^2 / (a + b) for a pair of nonnegative finite cells. Where a + b overflows, the same quotient with d in units of
84
+ * 2^520 and the cells in units of 2^1040: (d 2^-520)^2 / (a 2^-1040 + b 2^-1040), which neither overflows nor needs
85
+ * scaling back, and the scaling is exact (both cells exceed 2^969 there, as |d| <= the largest double). Elsewhere the
86
+ * plain quotient, unchanged
87
+ */
88
+ function pairTerm(d, a, b) {
89
+ const s = a + b;
90
+ return s < Infinity ? squareOver(d, s) : squareOver(ldexp(d, -520), ldexp(a, -1040) + ldexp(b, -1040));
91
+ }
71
92
  /**
72
93
  * Cross-tabulation of two paired samples of category codes (pairs with a missing value dropped), as R tabulates two
73
- * factors: the rows are the levels of x and the columns those of y, each sorted (numbers numerically, strings as R
74
- * sorts factor levels in the C locale). As in R, both must have the same number of levels, at least 2; the levels
75
- * are matched by position, not by value.
94
+ * factors: the rows are the levels of x and the columns those of y, each sorted (numbers numerically, strings by code
95
+ * point as R sorts factor levels in the C locale; a sample mixing numbers and strings is all text, as R coerces it). As
96
+ * in R, both must have the same number of levels, at least 2; the levels are matched by position, not by value.
76
97
  */
77
98
  function crossTable(x, y) {
78
99
  if (x.length !== y.length)
79
100
  throw new RangeError("'x' and 'y' must have the same length");
80
101
  const keep = [];
81
- // numeric values with the same 15-digit text are one level, as in R's factor()
82
- const xl = numberLevels(x);
83
- const yl = numberLevels(y);
102
+ // numeric values with the same 15-digit text are one level, and mixed samples are text, as in R's factor()
103
+ const xl = factorLabels(x);
104
+ const yl = factorLabels(y);
84
105
  for (let i = 0; i < x.length; i++) {
85
106
  const a = xl[i];
86
107
  const b = yl[i];
@@ -90,7 +111,7 @@ function crossTable(x, y) {
90
111
  continue;
91
112
  keep.push([a, b]);
92
113
  }
93
- const levelsOf = (v) => Array.from(new Set(v)).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0);
114
+ const levelsOf = (v) => Array.from(new Set(v)).sort(compareLabels);
94
115
  const lx = levelsOf(keep.map((p) => p[0]));
95
116
  const ly = levelsOf(keep.map((p) => p[1]));
96
117
  if (lx.length < 2 || lx.length !== ly.length) {
@@ -59,6 +59,12 @@ export interface KwManyOneDunnTestOptions extends ManyOneTestOptions {
59
59
  * @category Multiple comparisons
60
60
  */
61
61
  export type ManyOneUTestOptions = KwManyOneDunnTestOptions;
62
+ /**
63
+ * No inference without a residual variance (the statistics were +-Infinity, or NaN for equal means): the pooled
64
+ * comparisons here, pairwiseTTest with a pooled SD and onewayTest with equal variances. The sum of squares
65
+ * (groupMoments) is double-double, so it is exactly 0 only when every group is constant
66
+ */
67
+ export declare function checkPooledVariance(df: number, ssWithin: number): void;
62
68
  /**
63
69
  * Dunn's all-pairs test of mean ranks with adjusted p-values. Equivalent to `PMCMRplus::kwAllPairsDunnTest()` in R.
64
70
  *
@@ -229,7 +235,8 @@ export interface DunnTestResult {
229
235
  /**
230
236
  * Dunn's test of all pairs of mean ranks. Equivalent to `dunn.test::dunn.test(x, g, method, altp)` in R. The step-wise
231
237
  * adjustments multiply (or transform) each p-value by the factor of its rank and cap it at 1, without enforcing
232
- * monotonicity, as dunn.test does (unlike `pAdjust`).
238
+ * monotonicity, as dunn.test does (unlike `pAdjust`). Equal p-values share the rank of the first of them in the
239
+ * ordering, so they get the same adjusted value (dunn.test ranks ties in the order of the comparisons).
233
240
  *
234
241
  * @example
235
242
  * ```ts
@@ -16,7 +16,7 @@
16
16
  // - Tukey (1953), Tukey-Kramer: the pooled standard error, studentized range on N - k degrees of freedom.
17
17
  import { pnorm } from "../distributions/normal.js";
18
18
  import { ptukey } from "../distributions/tukey.js";
19
- import { mean, rank, tieCounts, variance } from "../internal/summary.js";
19
+ import { groupMoments, ldexp, rank, satterthwaiteDfPM, tieCounts } from "../internal/summary.js";
20
20
  import { pDunnettUpper } from "./dunnett.js";
21
21
  import { labelledGroups } from "./groups.js";
22
22
  import { pAdjust } from "./pAdjust.js";
@@ -96,17 +96,29 @@ function manyOne(d, method, statistic, pValue, adjust, warnings = []) {
96
96
  }
97
97
  const upperNormal = (z) => pnorm(z, { lowerTail: false });
98
98
  const upperRange = (q, k, df) => ptukey(Math.abs(q), k, df, { lowerTail: false });
99
- /** Group means, and the pooled variance sum (n_i - 1) s_i^2 / sum (n_i - 1) with its degrees of freedom */
99
+ /**
100
+ * Group means, and the pooled variance sum (n_i - 1) s_i^2 / sum (n_i - 1) with its degrees of freedom, of the data
101
+ * scaled by 2^-k (exact; the variances then stay in range). Means and standard errors are multiplied by 2^k for output
102
+ */
100
103
  function pooled(d) {
101
- let ss = 0;
104
+ const gm = groupMoments(d.groups);
102
105
  let df = 0;
103
- for (const grp of d.groups) {
104
- if (grp.length < 2)
105
- continue;
106
- ss += (grp.length - 1) * variance(grp);
107
- df += grp.length - 1;
108
- }
109
- return { m: d.groups.map(mean), s2: ss / df, df: d.N - d.k };
106
+ for (const n of gm.n)
107
+ if (n > 1)
108
+ df += n - 1;
109
+ checkPooledVariance(df, gm.ssWithin);
110
+ return { m: gm.mean, s2: gm.ssWithin / df, df: d.N - d.k, k: gm.k };
111
+ }
112
+ /**
113
+ * No inference without a residual variance (the statistics were +-Infinity, or NaN for equal means): the pooled
114
+ * comparisons here, pairwiseTTest with a pooled SD and onewayTest with equal variances. The sum of squares
115
+ * (groupMoments) is double-double, so it is exactly 0 only when every group is constant
116
+ */
117
+ export function checkPooledVariance(df, ssWithin) {
118
+ if (df === 0)
119
+ throw new RangeError("no residual degrees of freedom");
120
+ if (ssWithin === 0)
121
+ throw new RangeError("the pooled within-group variance is 0");
110
122
  }
111
123
  /**
112
124
  * Dunn's all-pairs test of mean ranks with adjusted p-values. Equivalent to `PMCMRplus::kwAllPairsDunnTest()` in R.
@@ -299,11 +311,13 @@ export function dscfAllPairsTest(x, g) {
299
311
  */
300
312
  export function gamesHowellTest(x, g) {
301
313
  const d = layout(x, g);
302
- const m = d.groups.map(mean);
303
- const w = d.groups.map((grp, i) => variance(grp) / d.n[i]);
314
+ // moments of the data scaled by a power of 2 (exact), so that the variances stay in range; q and df have no units
315
+ const gm = groupMoments(d.groups);
316
+ const m = gm.mean;
317
+ const w = gm.variance.map((v, i) => v / d.n[i]);
304
318
  const q = lowerTable(d.k, (i, j) => ((m[i] - m[j]) / Math.sqrt(w[i] + w[j])) * Math.SQRT2);
305
319
  const p = lowerTable(d.k, (i, j) => {
306
- const df = (w[i] + w[j]) ** 2 / (w[i] ** 2 / (d.n[i] - 1) + w[j] ** 2 / (d.n[j] - 1));
320
+ const df = satterthwaiteDfPM([gm.variance[i], gm.variance[j]], [d.n[i], d.n[j]]);
307
321
  return upperRange(q[i - 1][j], d.k, df);
308
322
  });
309
323
  return allPairs(d, "Games-Howell test", q, p, "none");
@@ -323,6 +337,9 @@ export function gamesHowellTest(x, g) {
323
337
  export function tukeyTest(x, g) {
324
338
  const d = layout(x, g);
325
339
  const { m, s2, df } = pooled(d);
340
+ // ptukey is defined from 2 df: with 1 the p-values were NaN (as TukeyHSD, #315)
341
+ if (df < 2)
342
+ throw new RangeError("the studentized range needs at least 2 residual degrees of freedom");
326
343
  const q = lowerTable(d.k, (i, j) => (m[i] - m[j]) / Math.sqrt((s2 * (1 / d.n[i] + 1 / d.n[j])) / 2));
327
344
  const p = q.map((row) => row.map((v) => (Number.isNaN(v) ? NaN : upperRange(v, d.k, df))));
328
345
  return allPairs(d, "Tukey's test", q, p, "single-step");
@@ -363,7 +380,8 @@ export function steelTest(x, g, options = {}) {
363
380
  /**
364
381
  * Dunn's test of all pairs of mean ranks. Equivalent to `dunn.test::dunn.test(x, g, method, altp)` in R. The step-wise
365
382
  * adjustments multiply (or transform) each p-value by the factor of its rank and cap it at 1, without enforcing
366
- * monotonicity, as dunn.test does (unlike `pAdjust`).
383
+ * monotonicity, as dunn.test does (unlike `pAdjust`). Equal p-values share the rank of the first of them in the
384
+ * ordering, so they get the same adjusted value (dunn.test ranks ties in the order of the comparisons).
367
385
  *
368
386
  * @example
369
387
  * ```ts
@@ -394,15 +412,18 @@ export function dunnTest(x, g, options = {}) {
394
412
  const P = Z.map((z) => (altp ? 2 : 1) * upperNormal(Math.abs(z)));
395
413
  return { chi2, Z, P, PAdjusted: dunnAdjust(P, method), comparisons };
396
414
  }
397
- /** dunn.test's adjustments: each value by the factor of its rank, capped at 1 */
415
+ /** dunn.test's adjustments: each value by the factor of its rank (tied values: the same rank), capped at 1 */
398
416
  function dunnAdjust(P, method) {
399
417
  const m = P.length;
400
418
  const sidakLike = (p, e) => Math.min(1, -Math.expm1(e * Math.log1p(-p)));
401
- // i = 1..m: rank among the increasing (or decreasing) values, ties in the order of the comparisons
419
+ // i = 1..m: rank among the increasing (or decreasing) values. Tied values share the first rank of their run
420
+ // (dunn.test ranks them in the order of the comparisons, so equal p-values got different adjusted values that
421
+ // depended on the order of the groups). The first of a run is the one the stopping rule decides on, step-down
422
+ // (increasing) or step-up (decreasing), so the decisions are those of dunn.test
402
423
  const ranks = (decreasing) => {
403
424
  const order = P.map((_, k) => k).sort((a, b) => (decreasing ? P[b] - P[a] : P[a] - P[b]) || a - b);
404
425
  const r = new Array(m);
405
- order.forEach((k, pos) => (r[k] = pos + 1));
426
+ order.forEach((k, pos) => (r[k] = pos > 0 && P[k] === P[order[pos - 1]] ? r[order[pos - 1]] : pos + 1));
406
427
  return r;
407
428
  };
408
429
  switch (method) {
@@ -459,12 +480,14 @@ function dunnAdjust(P, method) {
459
480
  export function glhtDunnett(x, g, options = {}) {
460
481
  const alternative = matchAlternative(options.alternative);
461
482
  const d = layout(x, g);
462
- const { m, s2, df } = pooled(d);
483
+ const { m, s2, df, k } = pooled(d);
463
484
  const s = Math.sqrt(s2);
464
485
  const idx = d.n.slice(1).map((_, i) => i + 1);
465
- const estimate = idx.map((j) => m[j] - m[0]);
466
- const se = idx.map((j) => s * Math.sqrt(1 / d.n[j] + 1 / d.n[0]));
467
- const t = estimate.map((e, i) => e / se[i]);
486
+ const est = idx.map((j) => m[j] - m[0]);
487
+ const seS = idx.map((j) => s * Math.sqrt(1 / d.n[j] + 1 / d.n[0]));
488
+ const t = est.map((e, i) => e / seS[i]);
489
+ const estimate = est.map((v) => ldexp(v, k));
490
+ const se = seS.map((v) => ldexp(v, k));
468
491
  const lambda = idx.map((j) => d.n[j] / (d.n[j] + d.n[0]));
469
492
  const p = t.map((v) => alternative === "two.sided"
470
493
  ? pDunnettUpper(v, lambda, df, true)
@@ -8,16 +8,26 @@
8
8
  // the Shapiro-Francia W), and the chi-square test on classes of equal probability.
9
9
  import { pgamma1 } from "../distributions/gamma.js";
10
10
  import { pnorm, qnorm } from "../distributions/normal.js";
11
- import { covariance, dropNaN, mean, variance } from "../internal/summary.js";
11
+ import { covariance, dropNaN, scaleToUnit, standardize, variance } from "../internal/summary.js";
12
12
  /** The sorted values without NaN */
13
13
  function sorted(x) {
14
14
  return dropNaN(Array.from(x)).sort((a, b) => a - b);
15
15
  }
16
+ /** Rejects infinite values (the sorted values without NaN: only the ends can be infinite) */
17
+ function requireFinite(xs) {
18
+ if (xs.length > 0 && !(Number.isFinite(xs[0]) && Number.isFinite(xs[xs.length - 1])))
19
+ throw new RangeError("'x' must be finite");
20
+ }
16
21
  /** The sorted values standardised by their mean and standard deviation */
17
22
  function standardized(xs) {
18
- const m = mean(xs);
19
- const s = Math.sqrt(variance(xs));
20
- return xs.map((v) => (v - m) / s);
23
+ // from the deviations of the values scaled by a power of 2 first (src/internal/summary.ts): no overflow or
24
+ // underflow at any scale. An infinite value is an error, as in shapiroTest: its standardised values are NaN and
25
+ // the piecewise p-values fell through to a fixed tail value (#304)
26
+ requireFinite(xs);
27
+ const z = standardize(xs);
28
+ if (z.some(Number.isNaN))
29
+ throw new RangeError("all 'x' values are identical");
30
+ return z;
21
31
  }
22
32
  /**
23
33
  * Anderson-Darling test for normality. Equivalent to `nortest::ad.test()` in R. `NaN` values are dropped; at least 8
@@ -154,8 +164,15 @@ export function sfTest(x) {
154
164
  const n = xs.length;
155
165
  if (n < 5 || n > 5000)
156
166
  throw new RangeError("sample size must be between 5 and 5000");
167
+ requireFinite(xs);
168
+ if (xs[0] === xs[n - 1])
169
+ throw new RangeError("all 'x' values are identical");
157
170
  const q = xs.map((_, k) => qnorm((k + 1 - 3 / 8) / (n + 1 / 4)));
158
- const w = covariance(xs, q) ** 2 / (variance(xs) * variance(q));
171
+ // the values scaled by a power of 2 (exact) first, so that the squared covariance stays in range (W has no units)
172
+ const xu = scaleToUnit([xs]).groups[0];
173
+ // a squared correlation: the three moments are rounded separately, so the quotient can exceed 1 by an ulp for data
174
+ // almost affine in the scores, where log(1 - W) was NaN (#384); at most 1, as R's cor()
175
+ const w = Math.min(covariance(xu, q) ** 2 / (variance(xu) * variance(q)), 1);
159
176
  const u = Math.log(n);
160
177
  const v = Math.log(u);
161
178
  const mu = -1.2725 + 1.0521 * (v - u);
@@ -180,14 +197,31 @@ export function pearsonTest(x, options = {}) {
180
197
  const n = xs.length;
181
198
  const k = options.nClasses ?? Math.ceil(2 * n ** (2 / 5));
182
199
  const adjust = options.adjust ?? true;
183
- const counts = new Array(k).fill(0);
200
+ if (!(Number.isInteger(k) && k - 1 - (adjust ? 2 : 0) > 0))
201
+ throw new RangeError("'nClasses' must be an integer leaving positive degrees of freedom");
202
+ // R's tabulate(num, n.classes): beyond the integer range "attempt to make a table with >= 2^31 elements" (#305)
203
+ if (k > 2147483647)
204
+ throw new RangeError("attempt to make a table with >= 2^31 elements");
205
+ const classes = [];
184
206
  for (const z of standardized(xs)) {
185
- const c = Math.floor(1 + k * pnorm(z));
186
- if (c >= 1 && c <= k)
187
- counts[c - 1]++;
207
+ // a value whose pnorm rounds to 1 belongs to the last class (nortest drops it: tabulate ignores the class k + 1)
208
+ const c = Math.min(k, Math.floor(1 + k * pnorm(z)));
209
+ if (c >= 1)
210
+ classes.push(c);
188
211
  }
212
+ classes.sort((a, b) => a - b);
213
+ // the sum over the classes 1..k in order, with the counts taken from the sorted class numbers: the same terms in
214
+ // the same order as summing a k-entry count array, without allocating it (#305)
189
215
  const e = n / k;
190
- const statistic = counts.reduce((a, c) => a + (c - e) ** 2 / e, 0);
216
+ let statistic = 0;
217
+ for (let c = 1, i = 0; c <= k; c++) {
218
+ let count = 0;
219
+ while (i < classes.length && classes[i] === c) {
220
+ count++;
221
+ i++;
222
+ }
223
+ statistic = statistic + (count - e) ** 2 / e;
224
+ }
191
225
  const df = k - 1 - (adjust ? 2 : 0);
192
226
  return {
193
227
  method: "Pearson chi-square normality test",