@numero-uno-jpn/rstats 0.15.3 → 0.17.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 (322) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/README.ja.md +68 -35
  3. package/README.md +65 -30
  4. package/dist/chunks/chunk-2C33MXSW.js +3 -0
  5. package/dist/chunks/chunk-34S5SQY6.js +2 -0
  6. package/dist/chunks/chunk-4WE3OO62.js +2 -0
  7. package/dist/chunks/chunk-5AYHCITP.js +2 -0
  8. package/dist/chunks/chunk-6JJQL6HL.js +2 -0
  9. package/dist/chunks/chunk-C7V2FH6L.js +3 -0
  10. package/dist/chunks/chunk-CZI7KUO3.js +2 -0
  11. package/dist/chunks/chunk-DXI5N2ET.js +2 -0
  12. package/dist/chunks/chunk-FY3FVOBM.js +2 -0
  13. package/dist/chunks/chunk-H3WVPZDL.js +2 -0
  14. package/dist/chunks/chunk-LHUIJQHY.js +2 -0
  15. package/dist/chunks/chunk-LV3W2F7N.js +2 -0
  16. package/dist/chunks/chunk-M4ITG7YR.js +2 -0
  17. package/dist/chunks/chunk-NSYZTS26.js +2 -0
  18. package/dist/chunks/chunk-ONY5CISH.js +2 -0
  19. package/dist/chunks/chunk-RFE7MVP7.js +2 -0
  20. package/dist/chunks/chunk-SE7V2KLO.js +2 -0
  21. package/dist/chunks/chunk-THIGHOKK.js +2 -0
  22. package/dist/chunks/chunk-TNMJPQPV.js +2 -0
  23. package/dist/chunks/chunk-WM7VFXTV.js +2 -0
  24. package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
  25. package/dist/chunks/chunk-XLSFJTTK.js +2 -0
  26. package/dist/chunks/chunk-Z37NELOS.js +2 -0
  27. package/dist/chunks/chunk-ZFQWB222.js +2 -0
  28. package/dist/data/grouping.js +26 -7
  29. package/dist/descriptive/basic.js +110 -8
  30. package/dist/descriptive/cov.js +23 -4
  31. package/dist/descriptive/dataFrames.d.ts +4 -2
  32. package/dist/descriptive/dataFrames.js +69 -23
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +26 -9
  35. package/dist/descriptive/hist.d.ts +8 -5
  36. package/dist/descriptive/hist.js +77 -31
  37. package/dist/descriptive/missing.js +3 -1
  38. package/dist/descriptive/moments.js +86 -19
  39. package/dist/descriptive/omega.d.ts +1 -1
  40. package/dist/descriptive/omega.js +74 -10
  41. package/dist/descriptive/pivot.d.ts +25 -10
  42. package/dist/descriptive/pivot.js +182 -42
  43. package/dist/descriptive/quantile.js +10 -1
  44. package/dist/descriptive/rank.js +8 -1
  45. package/dist/descriptive/table.d.ts +23 -3
  46. package/dist/descriptive/table.js +36 -21
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions/arcsine.js +27 -2
  49. package/dist/distributions/beta.js +33 -4
  50. package/dist/distributions/binomial.js +46 -14
  51. package/dist/distributions/bvnorm.js +11 -2
  52. package/dist/distributions/cauchy.js +21 -4
  53. package/dist/distributions/chisq.js +16 -3
  54. package/dist/distributions/exponential.js +14 -0
  55. package/dist/distributions/f.js +41 -17
  56. package/dist/distributions/gamma.js +35 -3
  57. package/dist/distributions/geometric.js +58 -13
  58. package/dist/distributions/hypergeometric.d.ts +5 -1
  59. package/dist/distributions/hypergeometric.js +101 -6
  60. package/dist/distributions/invgamma.js +10 -1
  61. package/dist/distributions/kumaraswamy.js +9 -0
  62. package/dist/distributions/laplace.js +36 -6
  63. package/dist/distributions/logistic.js +13 -1
  64. package/dist/distributions/lognormal.js +16 -2
  65. package/dist/distributions/multinomial.js +58 -11
  66. package/dist/distributions/nbeta.js +62 -11
  67. package/dist/distributions/nchisq.js +30 -6
  68. package/dist/distributions/negbinomial.js +102 -17
  69. package/dist/distributions/normal.js +17 -4
  70. package/dist/distributions/nt.js +392 -17
  71. package/dist/distributions/pareto.js +12 -1
  72. package/dist/distributions/poisson.js +37 -3
  73. package/dist/distributions/signrank.js +16 -4
  74. package/dist/distributions/summary.d.ts +2 -1
  75. package/dist/distributions/summary.js +481 -61
  76. package/dist/distributions/t.js +9 -0
  77. package/dist/distributions/triangular.js +19 -5
  78. package/dist/distributions/tukey.js +11 -2
  79. package/dist/distributions/uniform.js +8 -0
  80. package/dist/distributions/weibull.js +18 -0
  81. package/dist/distributions/wilcox.d.ts +9 -3
  82. package/dist/distributions/wilcox.js +164 -26
  83. package/dist/distributions.js +2 -2
  84. package/dist/entries/descriptive.d.ts +3 -1
  85. package/dist/entries/descriptive.js +1 -1
  86. package/dist/entries/distributions.d.ts +1 -0
  87. package/dist/entries/distributions.js +2 -0
  88. package/dist/entries/linalg.d.ts +3 -1
  89. package/dist/entries/mixed.d.ts +3 -0
  90. package/dist/entries/mixed.js +2 -0
  91. package/dist/entries/numerics.d.ts +2 -1
  92. package/dist/entries/tests.d.ts +8 -5
  93. package/dist/entries/tests.js +3 -1
  94. package/dist/htest/agreement.d.ts +16 -2
  95. package/dist/htest/agreement.js +122 -21
  96. package/dist/htest/ansariTest.d.ts +8 -2
  97. package/dist/htest/ansariTest.js +116 -18
  98. package/dist/htest/aov.d.ts +29 -23
  99. package/dist/htest/aov.js +90 -47
  100. package/dist/htest/binomTest.d.ts +5 -0
  101. package/dist/htest/binomTest.js +47 -17
  102. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  103. package/dist/htest/brunnerMunzelTest.js +12 -5
  104. package/dist/htest/chisqTest.d.ts +5 -2
  105. package/dist/htest/chisqTest.js +151 -46
  106. package/dist/htest/cor.d.ts +9 -2
  107. package/dist/htest/cor.js +57 -26
  108. package/dist/htest/core/ansari.d.ts +9 -0
  109. package/dist/htest/core/ansari.js +21 -1
  110. package/dist/htest/core/kolmogorov.d.ts +25 -0
  111. package/dist/htest/core/kolmogorov.js +123 -0
  112. package/dist/htest/core/mantelhaen.js +6 -4
  113. package/dist/htest/core/shapiro.d.ts +1 -1
  114. package/dist/htest/core/shapiro.js +5 -1
  115. package/dist/htest/core/simulate.d.ts +6 -0
  116. package/dist/htest/core/simulate.js +20 -0
  117. package/dist/htest/dunnett.js +14 -5
  118. package/dist/htest/effectSize.d.ts +5 -0
  119. package/dist/htest/effectSize.js +117 -35
  120. package/dist/htest/fisherTest.d.ts +4 -3
  121. package/dist/htest/fisherTest.js +88 -24
  122. package/dist/htest/groups.d.ts +7 -0
  123. package/dist/htest/groups.js +21 -4
  124. package/dist/htest/ksTest.d.ts +7 -1
  125. package/dist/htest/ksTest.js +36 -6
  126. package/dist/htest/leveneTest.d.ts +2 -0
  127. package/dist/htest/leveneTest.js +28 -6
  128. package/dist/htest/mantelhaenTest.js +132 -25
  129. package/dist/htest/mcnemarTest.js +40 -11
  130. package/dist/htest/multipleComparisons.d.ts +24 -26
  131. package/dist/htest/multipleComparisons.js +70 -64
  132. package/dist/htest/normalityTests.js +54 -14
  133. package/dist/htest/onewayTest.js +106 -5
  134. package/dist/htest/pAdjust.d.ts +3 -2
  135. package/dist/htest/pAdjust.js +42 -6
  136. package/dist/htest/pairwise.d.ts +3 -1
  137. package/dist/htest/pairwise.js +46 -21
  138. package/dist/htest/poissonTest.d.ts +1 -1
  139. package/dist/htest/poissonTest.js +117 -59
  140. package/dist/htest/polycor.js +47 -17
  141. package/dist/htest/power.d.ts +15 -1
  142. package/dist/htest/power.js +128 -10
  143. package/dist/htest/propTest.d.ts +3 -0
  144. package/dist/htest/propTest.js +44 -6
  145. package/dist/htest/pwr.d.ts +38 -1
  146. package/dist/htest/pwr.js +159 -39
  147. package/dist/htest/rankTests.js +36 -6
  148. package/dist/htest/tTest.d.ts +2 -0
  149. package/dist/htest/tTest.js +53 -21
  150. package/dist/htest/testFormula.js +11 -11
  151. package/dist/htest/trendTests.d.ts +28 -4
  152. package/dist/htest/trendTests.js +124 -35
  153. package/dist/htest/types.d.ts +7 -0
  154. package/dist/htest/types.js +7 -0
  155. package/dist/htest/varTest.js +52 -14
  156. package/dist/htest/wilcoxTest.js +164 -29
  157. package/dist/integrate/quadpack.js +27 -5
  158. package/dist/internal/checkOptions.d.ts +11 -0
  159. package/dist/internal/checkOptions.js +31 -0
  160. package/dist/internal/covmat.d.ts +5 -0
  161. package/dist/internal/covmat.js +20 -0
  162. package/dist/internal/ddexp.d.ts +15 -1
  163. package/dist/internal/ddexp.js +59 -6
  164. package/dist/internal/discrete.d.ts +14 -0
  165. package/dist/internal/discrete.js +78 -5
  166. package/dist/internal/extremes.d.ts +9 -0
  167. package/dist/internal/extremes.js +24 -0
  168. package/dist/internal/fround.js +13 -4
  169. package/dist/internal/integer.d.ts +9 -0
  170. package/dist/internal/integer.js +12 -0
  171. package/dist/internal/invert.js +15 -2
  172. package/dist/internal/optionalArgs.d.ts +12 -0
  173. package/dist/internal/optionalArgs.js +46 -0
  174. package/dist/internal/scaledInverse.d.ts +10 -0
  175. package/dist/internal/scaledInverse.js +22 -0
  176. package/dist/internal/seq.js +15 -2
  177. package/dist/internal/summary.d.ts +90 -0
  178. package/dist/internal/summary.js +458 -39
  179. package/dist/internal/uniroot.d.ts +7 -0
  180. package/dist/internal/uniroot.js +28 -3
  181. package/dist/internal/warnings.d.ts +66 -0
  182. package/dist/internal/warnings.js +122 -0
  183. package/dist/linalg/basic.d.ts +3 -1
  184. package/dist/linalg/basic.js +58 -7
  185. package/dist/linalg/chol.js +10 -1
  186. package/dist/linalg/dot.d.ts +29 -0
  187. package/dist/linalg/dot.js +132 -0
  188. package/dist/linalg/eigen.d.ts +6 -1
  189. package/dist/linalg/eigen.js +75 -14
  190. package/dist/linalg/expm.d.ts +3 -2
  191. package/dist/linalg/expm.js +113 -15
  192. package/dist/linalg/kappa.js +64 -10
  193. package/dist/linalg/lu.d.ts +2 -1
  194. package/dist/linalg/lu.js +40 -5
  195. package/dist/linalg/matrix.d.ts +14 -0
  196. package/dist/linalg/matrix.js +24 -0
  197. package/dist/linalg/norm.js +4 -0
  198. package/dist/linalg/ops.d.ts +27 -2
  199. package/dist/linalg/ops.js +74 -26
  200. package/dist/linalg/qr.d.ts +2 -1
  201. package/dist/linalg/qr.js +105 -23
  202. package/dist/linalg/schur.js +11 -3
  203. package/dist/linalg/solve.d.ts +6 -1
  204. package/dist/linalg/solve.js +156 -26
  205. package/dist/linalg/svd.d.ts +9 -2
  206. package/dist/linalg/svd.js +33 -11
  207. package/dist/linalg.js +2 -2
  208. package/dist/mixed.js +4 -4
  209. package/dist/models/anovaSequential.d.ts +32 -2
  210. package/dist/models/anovaSequential.js +170 -28
  211. package/dist/models/aovEz.js +154 -39
  212. package/dist/models/aovStrata.js +68 -24
  213. package/dist/models/carAnova.d.ts +1 -1
  214. package/dist/models/carAnova.js +78 -33
  215. package/dist/models/coxph.d.ts +6 -0
  216. package/dist/models/coxph.js +166 -69
  217. package/dist/models/estimable.d.ts +15 -0
  218. package/dist/models/estimable.js +68 -0
  219. package/dist/models/formula.d.ts +1 -1
  220. package/dist/models/formula.js +26 -8
  221. package/dist/models/glm.d.ts +57 -7
  222. package/dist/models/glm.js +427 -74
  223. package/dist/models/glmAnova.js +90 -14
  224. package/dist/models/glmConfint.d.ts +1 -1
  225. package/dist/models/glmConfint.js +121 -29
  226. package/dist/models/glmFamily.d.ts +11 -6
  227. package/dist/models/glmFamily.js +247 -62
  228. package/dist/models/lm.d.ts +12 -1
  229. package/dist/models/lm.js +246 -37
  230. package/dist/models/lmer.d.ts +31 -7
  231. package/dist/models/lmer.js +129 -42
  232. package/dist/models/lmerAnova.d.ts +3 -3
  233. package/dist/models/lmerAnova.js +47 -9
  234. package/dist/models/lmerHypotheses.d.ts +6 -2
  235. package/dist/models/lmerHypotheses.js +14 -2
  236. package/dist/models/lmerTest.d.ts +13 -6
  237. package/dist/models/lmerTest.js +82 -29
  238. package/dist/models/mauchly.d.ts +6 -1
  239. package/dist/models/mauchly.js +41 -15
  240. package/dist/models/mixedStructure.js +6 -0
  241. package/dist/models/modelFrame.js +10 -4
  242. package/dist/models/modelMatrix.d.ts +3 -1
  243. package/dist/models/modelMatrix.js +47 -17
  244. package/dist/models/scaledTables.d.ts +8 -0
  245. package/dist/models/scaledTables.js +6 -0
  246. package/dist/models/survival.d.ts +12 -1
  247. package/dist/models/survival.js +75 -28
  248. package/dist/models/tiedTimes.d.ts +2 -0
  249. package/dist/models/tiedTimes.js +34 -0
  250. package/dist/numerics/deriv.d.ts +1 -1
  251. package/dist/numerics/deriv.js +72 -8
  252. package/dist/numerics/integrate.d.ts +9 -1
  253. package/dist/numerics/integrate.js +111 -16
  254. package/dist/numerics/interp.d.ts +40 -9
  255. package/dist/numerics/interp.js +375 -55
  256. package/dist/numerics/ode.js +59 -1
  257. package/dist/numerics.js +2 -2
  258. package/dist/optim/localmin.js +4 -0
  259. package/dist/optim/optim.d.ts +3 -1
  260. package/dist/optim/optim.js +97 -10
  261. package/dist/random/beta.js +58 -4
  262. package/dist/random/binomial.d.ts +14 -3
  263. package/dist/random/binomial.js +59 -24
  264. package/dist/random/continuous.js +50 -5
  265. package/dist/random/extra.js +55 -9
  266. package/dist/random/gamma.d.ts +4 -1
  267. package/dist/random/gamma.js +47 -8
  268. package/dist/random/hyper.js +9 -6
  269. package/dist/random/mt.js +17 -2
  270. package/dist/random/poisson.js +31 -3
  271. package/dist/random/r2dtable.d.ts +8 -1
  272. package/dist/random/r2dtable.js +24 -3
  273. package/dist/random/rank.d.ts +2 -0
  274. package/dist/random/rank.js +44 -4
  275. package/dist/random/rng.js +4 -0
  276. package/dist/random/sample.d.ts +12 -2
  277. package/dist/random/sample.js +63 -20
  278. package/dist/random/streams.js +4 -2
  279. package/dist/rstats.js +17 -14
  280. package/dist/special/besselIK.d.ts +12 -0
  281. package/dist/special/besselIK.js +175 -23
  282. package/dist/special/besselJY.d.ts +11 -1
  283. package/dist/special/besselJY.js +127 -19
  284. package/dist/special/besselSeries.d.ts +27 -0
  285. package/dist/special/besselSeries.js +45 -2
  286. package/dist/special/beta.js +4 -1
  287. package/dist/special/choose.js +24 -8
  288. package/dist/special/dd.js +122 -18
  289. package/dist/special/extra.js +14 -2
  290. package/dist/special/gamma.js +11 -2
  291. package/dist/special/incbet.js +30 -4
  292. package/dist/special/incbetTemme.d.ts +7 -0
  293. package/dist/special/incbetTemme.js +45 -12
  294. package/dist/special/loader.d.ts +1 -1
  295. package/dist/special/loader.js +117 -20
  296. package/dist/special/log1pmx.js +4 -0
  297. package/dist/special/psigamma.js +7 -0
  298. package/dist/special.js +2 -2
  299. package/dist/tests.js +15 -11
  300. package/llms.txt +15 -6
  301. package/package.json +19 -10
  302. package/dist/chunks/chunk-3THFTB36.js +0 -2
  303. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  304. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  305. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  306. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  307. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  308. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  309. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  310. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  311. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  312. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  313. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  314. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  315. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  316. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  317. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  318. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  319. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  320. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  321. package/dist/chunks/chunk-VLUL2HFW.js +0 -3
  322. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -16,9 +16,13 @@
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";
23
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
24
+ import { checkOptions } from "../internal/checkOptions.js";
25
+ const MANTELHAEN_TEST_KEYS = ["alternative", "correct", "exact", "confLevel"];
22
26
  /**
23
27
  * Cochran-Mantel-Haenszel chi-squared test of conditional independence in a set of contingency tables, one per
24
28
  * stratum. Equivalent to R's `mantelhaen.test()`. Takes the strata as R takes a three-dimensional array.
@@ -42,6 +46,7 @@ import { checkConfLevelOpen, matchAlternative } from "./types.js";
42
46
  * @category Hypothesis tests
43
47
  */
44
48
  export function mantelhaenTest(strata, options = {}) {
49
+ checkOptions(options, MANTELHAEN_TEST_KEYS, "mantelhaenTest"); // generated: option-keys.mjs
45
50
  const K = strata.length;
46
51
  if (K < 1)
47
52
  throw new RangeError("'x' must have at least one stratum");
@@ -55,7 +60,7 @@ export function mantelhaenTest(strata, options = {}) {
55
60
  if (t.some((r) => r.some((v) => !Number.isFinite(v) || v < 0)))
56
61
  throw new RangeError("all entries of 'x' must be nonnegative and finite");
57
62
  }
58
- const totals = strata.map((t) => t.reduce((a, r) => a + r.reduce((b, v) => b + v, 0), 0));
63
+ const totals = strata.map(stratumTotal);
59
64
  if (totals.some((t) => t < 2))
60
65
  throw new RangeError("sample size in each stratum must be > 1");
61
66
  const alternative = matchAlternative(options.alternative);
@@ -64,13 +69,50 @@ export function mantelhaenTest(strata, options = {}) {
64
69
  const confLevel = options.confLevel ?? 0.95;
65
70
  checkConfLevelOpen(confLevel);
66
71
  if (I === 2 && J === 2) {
72
+ // the exact conditional distribution is over integer tables (R takes fractional counts and returns a result)
73
+ if (exact && strata.some((t) => t.some((r) => r.some((v) => !Number.isInteger(v))))) {
74
+ throw new RangeError("the exact test needs integer counts");
75
+ }
76
+ // from 2^53 on the counts are not exact integers and the loop over a stratum's support does not advance (x + 1
77
+ // rounds to x; #494); the total bounds every cell, margin and sum over the strata
78
+ if (exact && totals.reduce((a, t) => a + t, 0) > Number.MAX_SAFE_INTEGER) {
79
+ throw new RangeError("the exact test needs counts with a total below 2^53: use exact: false");
80
+ }
67
81
  const tables = strata.map((t) => [[t[0][0], t[0][1]], [t[1][0], t[1][1]]]);
68
82
  return exact ? exact2x2xK(tables, alternative, confLevel) : asymptotic2x2xK(tables, totals, alternative, correct, confLevel);
69
83
  }
70
84
  // as in R, exact applies to 2 x 2 x K tables only and is ignored otherwise
71
85
  return general(strata, totals, I, J);
72
86
  }
73
- function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
87
+ /** Sum of the counts of one stratum */
88
+ function stratumTotal(t) {
89
+ return t.reduce((a, r) => a + r.reduce((b, v) => b + v, 0), 0);
90
+ }
91
+ /**
92
+ * The even power of 2 to divide all counts by where the totals or sums over the strata overflow: the largest count
93
+ * then below 2^1020 / (8 I J K), so that the totals and the sums over the strata are finite (#224, #226). The
94
+ * statistics are homogeneous in the counts (the count 1 in t - 1 becomes 2^-s), so they are scaled back exactly
95
+ */
96
+ function countExponent(strata) {
97
+ let m = 0;
98
+ let cells = 0;
99
+ for (const t of strata) {
100
+ for (const r of t) {
101
+ for (const v of r) {
102
+ m = Math.max(m, v);
103
+ cells++;
104
+ }
105
+ }
106
+ }
107
+ const s = Math.floor(Math.log2(m)) + 1 + Math.ceil(Math.log2(8 * cells)) - 1020;
108
+ return s <= 0 ? 0 : s + (s % 2);
109
+ }
110
+ /** The strata with every count divided by 2^s */
111
+ function scaledStrata(strata, s) {
112
+ return strata.map((t) => t.map((r) => r.map((v) => ldexp(v, -s))));
113
+ }
114
+ /** 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) */
115
+ function sums2x2xK(tables, totals, one) {
74
116
  let sa = 0;
75
117
  let se = 0;
76
118
  let sv = 0;
@@ -86,33 +128,56 @@ function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
86
128
  const c1 = a + c;
87
129
  const c2 = b + d;
88
130
  sa += a;
89
- se += (r1 * c1) / t;
90
- sv += (r1 * r2 * c1 * c2) / (t * t * (t - 1));
131
+ // products of counts near 1e150 overflow (the variance was Infinity / Infinity = NaN; R too): the ratios first there
132
+ const e = (r1 * c1) / t;
133
+ se += Number.isFinite(e) ? e : (r1 / t) * c1;
134
+ const v = (r1 * r2 * c1 * c2) / (t * t * (t - one));
135
+ sv += Number.isFinite(v) ? v : (r1 / t) * (r2 / t) * (c1 / (t - one)) * c2;
91
136
  const P = (a + d) / t;
92
137
  const Q = (b + c) / t;
93
- const R = (a * d) / t;
94
- const S = (b * c) / t;
138
+ const ad = (a * d) / t;
139
+ const bc = (b * c) / t;
140
+ const R = Number.isFinite(ad) ? ad : (a / t) * d;
141
+ const S = Number.isFinite(bc) ? bc : (b / t) * c;
95
142
  sR += R;
96
143
  sS += S;
97
144
  sPR += P * R;
98
145
  sPSQR += P * S + Q * R;
99
146
  sQS += Q * S;
100
147
  });
148
+ return { sa, se, sv, sR, sS, sPR, sPSQR, sQS };
149
+ }
150
+ function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
151
+ let sums = sums2x2xK(tables, totals, 1);
152
+ // a total or a sum over the strata overflows (finite counts near 1e308; NaN before, R fails, #226): all counts
153
+ // divided by an even power of 2, 2^s. The differences, variances and odds ratio terms are of degree 1 in the
154
+ // counts, so the statistic is 2^s times the scaled one, the estimate unchanged, and the sd of its log 2^(-s/2) times
155
+ let s = 0;
156
+ if (!totals.every(Number.isFinite) || !Object.values(sums).every(Number.isFinite)) {
157
+ s = countExponent(tables);
158
+ const scaled = scaledStrata(tables, s);
159
+ sums = sums2x2xK(scaled, scaled.map(stratumTotal), ldexp(1, -s));
160
+ }
161
+ const { sa, se, sv, sR, sS, sPR, sPSQR, sQS } = sums;
101
162
  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;
163
+ // the correction 1/2 in the units of the sums
164
+ const half = ldexp(0.5, -s);
165
+ const yates = correct && Math.abs(delta) >= half ? half : 0;
166
+ const statistic = ldexp(squareOver(Math.abs(delta) - yates, sv), s);
104
167
  const pValue = alternative === "two.sided"
105
168
  ? pgamma1(statistic, 0.5, 2, false, false)
106
169
  : pnorm(Math.sign(delta) * Math.sqrt(statistic), { lowerTail: alternative === "less" });
107
170
  const estimate = sR / sS;
108
- const sd = Math.sqrt(sPR / (2 * sR * sR) + sPSQR / (2 * sR * sS) + sQS / (2 * sS * sS));
171
+ const sd = ldexp(Math.sqrt(sPR / (2 * sR * sR) + sPSQR / (2 * sR * sS) + sQS / (2 * sS * sS)), -s / 2);
109
172
  let confInt;
110
173
  if (alternative === "less")
111
174
  confInt = [0, estimate * Math.exp(qnorm(confLevel) * sd)];
112
175
  else if (alternative === "greater")
113
176
  confInt = [estimate * Math.exp(qnorm(confLevel, { lowerTail: false }) * sd), Infinity];
114
177
  else {
115
- const z = qnorm((1 + confLevel) / 2);
178
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
179
+ const a2 = (1 - confLevel) / 2;
180
+ const z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + confLevel) / 2);
116
181
  confInt = [estimate * Math.exp(-z * sd), estimate * Math.exp(z * sd)];
117
182
  }
118
183
  return {
@@ -129,10 +194,23 @@ function asymptotic2x2xK(tables, totals, alternative, correct, confLevel) {
129
194
  estimateNames: "common odds ratio",
130
195
  nullValue: 1,
131
196
  nullValueName: "common odds ratio",
197
+ warnings: [],
132
198
  };
133
199
  }
200
+ /**
201
+ * Largest support (number of values of S) of the exact test: 2^24 values take a few hundred MB (one large stratum
202
+ * near 2^24 takes about 40 s; several large strata take longer, as the convolution grows with the product of their
203
+ * spreads); R allocates every stratum's support whatever its size (counts of 1e9 would take 16 GB per stratum)
204
+ */
205
+ const MAX_SUPPORT = 2 ** 24;
134
206
  /** Exact conditional test on 2 x 2 x K tables: S = sum of the (1, 1) cells given all margins */
135
207
  function exact2x2xK(tables, alternative, confLevel) {
208
+ // the support of S has 1 + sum (min(a, d) + min(b, c)) values (each stratum's support and every partial
209
+ // convolution are no longer); checked before any of them is allocated
210
+ const size = tables.reduce((acc, [[a, b], [c, d]]) => acc + Math.min(a, d) + Math.min(b, c), 1);
211
+ if (size > MAX_SUPPORT) {
212
+ throw new RangeError(`the exact distribution of S has ${size} values, more than 2^24: use exact: false`);
213
+ }
136
214
  const h = new ConvolvedNoncentralHyper(tables);
137
215
  const s = tables.reduce((acc, t) => acc + t[0][0], 0);
138
216
  let pValue;
@@ -169,9 +247,41 @@ function exact2x2xK(tables, alternative, confLevel) {
169
247
  estimateNames: "common odds ratio",
170
248
  nullValue: 1,
171
249
  nullValueName: "common odds ratio",
250
+ warnings: [],
172
251
  };
173
252
  }
174
253
  function general(strata, totals, I, J) {
254
+ let { diff, V } = generalSums(strata, totals, I, J, 1);
255
+ // a total or a sum over the strata overflows: all counts divided by 2^s (see countExponent); the differences and
256
+ // the covariance are of degree 1 in the counts, so the statistic is 2^s times the scaled one
257
+ let s = 0;
258
+ if (!totals.every(Number.isFinite) || !diff.every(Number.isFinite) || !V.every((row) => row.every(Number.isFinite))) {
259
+ s = countExponent(strata);
260
+ const scaled = scaledStrata(strata, s);
261
+ ({ diff, V } = generalSums(scaled, scaled.map(stratumTotal), I, J, ldexp(1, -s)));
262
+ }
263
+ const p = diff.length;
264
+ const sol = solve(V, diff);
265
+ let statistic = 0;
266
+ for (let u = 0; u < p; u++)
267
+ statistic += diff[u] * sol[u];
268
+ statistic = ldexp(statistic, s);
269
+ return {
270
+ method: "Cochran-Mantel-Haenszel test",
271
+ statistic,
272
+ statisticName: "Cochran-Mantel-Haenszel M^2",
273
+ parameter: p,
274
+ parameterName: "df",
275
+ pValue: pgamma1(statistic, p / 2, 2, false, false),
276
+ warnings: [],
277
+ };
278
+ }
279
+ const MIN_NORMAL = 2 ** -1022;
280
+ /**
281
+ * The differences n - m and the covariance V of the generalized statistic, summed over the strata, in units of 2^s
282
+ * counts (one = 2^-s is the count 1 in those units)
283
+ */
284
+ function generalSums(strata, totals, I, J, one) {
175
285
  const p = (I - 1) * (J - 1);
176
286
  const diff = new Array(p).fill(0);
177
287
  const V = Array.from({ length: p }, () => new Array(p).fill(0));
@@ -179,32 +289,29 @@ function general(strata, totals, I, J) {
179
289
  const t = totals[k];
180
290
  const r = tab.map((row) => row.reduce((a, b) => a + b, 0));
181
291
  const c = Array.from({ length: J }, (_, j) => tab.reduce((a, row) => a + row[j], 0));
182
- const f = 1 / (t * t * (t - 1));
292
+ const f = 1 / (t * t * (t - one));
183
293
  // 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
294
  for (let j = 0; j < J - 1; j++) {
185
295
  for (let i = 0; i < I - 1; i++) {
186
296
  const u = i + (I - 1) * j;
187
- diff[u] += tab[i][j] - (r[i] * c[j]) / t;
297
+ // a product of margins near 1e154 overflows: formed from the margins scaled to [1, 2) there
298
+ const e = (r[i] * c[j]) / t;
299
+ diff[u] += tab[i][j] - (Number.isFinite(e) ? e : productOver(r[i], c[j], t));
188
300
  for (let jj = 0; jj < J - 1; jj++) {
189
301
  for (let ii = 0; ii < I - 1; ii++) {
190
302
  const vr = (i === ii ? t * r[i] : 0) - r[i] * r[ii];
191
303
  const vc = (j === jj ? t * c[j] : 0) - c[j] * c[jj];
192
- V[u][ii + (I - 1) * jj] += f * vr * vc;
304
+ const v = f * vr * vc;
305
+ // t^2 (t - 1) or the product overflows from counts near 1e103 (0 times Infinity was NaN; R fails, #224):
306
+ // r_i (d_ii - r_ii / t) (d_jj - c_jj / t) c_j / (t - 1) there, each factor in range
307
+ V[u][ii + (I - 1) * jj] +=
308
+ Number.isFinite(v) && f >= MIN_NORMAL
309
+ ? v
310
+ : r[i] * ((i === ii ? 1 : 0) - r[ii] / t) * (((j === jj ? 1 : 0) - c[jj] / t) * (c[j] / (t - one)));
193
311
  }
194
312
  }
195
313
  }
196
314
  }
197
315
  });
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
- };
316
+ return { diff, V };
210
317
  }
@@ -2,9 +2,14 @@
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";
9
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
10
+ import { checkOptions } from "../internal/checkOptions.js";
11
+ import { isOptionsObject } from "../internal/optionalArgs.js";
12
+ const MCNEMAR_TEST_KEYS = ["correct"];
8
13
  /**
9
14
  * McNemar's chi-squared test for symmetry of rows and columns in a square table of counts. Equivalent to R's
10
15
  * `mcnemar.test()`. Takes a matrix, or two factors given as paired category codes.
@@ -22,6 +27,9 @@ import { numberLevels } from "../internal/levels.js";
22
27
  * @category Hypothesis tests
23
28
  */
24
29
  export function mcnemarTest(x, y, options = {}) {
30
+ if (isOptionsObject(y))
31
+ checkOptions(y, MCNEMAR_TEST_KEYS, "mcnemarTest"); // generated: option-keys.mjs
32
+ checkOptions(options, MCNEMAR_TEST_KEYS, "mcnemarTest"); // generated: option-keys.mjs
25
33
  let table;
26
34
  if (x.length > 0 && Array.isArray(x[0])) {
27
35
  if (y !== undefined && !Array.isArray(y))
@@ -46,17 +54,27 @@ export function mcnemarTest(x, y, options = {}) {
46
54
  if (useCorrection) {
47
55
  const b = table[0][1];
48
56
  const c = table[1][0];
49
- statistic = (Math.abs(b - c) - 1) ** 2 / (b + c);
57
+ // the correction stops at 0: with fractional counts abs(b - c) can be below 1, and (abs(b - c) - 1)^2 would make the
58
+ // statistic larger than without it (R squares the negative difference; its chisq.test and prop.test clamp)
59
+ statistic = pairTerm(Math.max(0, Math.abs(b - c) - 1), b, c);
50
60
  }
51
61
  else {
52
62
  statistic = 0;
63
+ // a pair of cells with no discordant counts adds nothing (0 / 0 made the statistic NaN; R too); with none at all
64
+ // there is nothing to test
65
+ let terms = 0;
53
66
  for (let i = 0; i < r; i++) {
54
67
  for (let j = i + 1; j < r; j++) {
55
68
  const a = table[i][j];
56
69
  const b = table[j][i];
57
- statistic += (a - b) ** 2 / (a + b);
70
+ if (a + b === 0)
71
+ continue;
72
+ statistic += pairTerm(a - b, a, b);
73
+ terms++;
58
74
  }
59
75
  }
76
+ if (terms === 0)
77
+ throw new RangeError("the table has no discordant pairs");
60
78
  }
61
79
  const df = (r * (r - 1)) / 2;
62
80
  return {
@@ -66,21 +84,32 @@ export function mcnemarTest(x, y, options = {}) {
66
84
  parameter: df,
67
85
  parameterName: "df",
68
86
  pValue: pgamma1(statistic, df / 2, 2, false, false),
87
+ warnings: [],
69
88
  };
70
89
  }
90
+ /**
91
+ * d^2 / (a + b) for a pair of nonnegative finite cells. Where a + b overflows, the same quotient with d in units of
92
+ * 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
93
+ * scaling back, and the scaling is exact (both cells exceed 2^969 there, as |d| <= the largest double). Elsewhere the
94
+ * plain quotient, unchanged
95
+ */
96
+ function pairTerm(d, a, b) {
97
+ const s = a + b;
98
+ return s < Infinity ? squareOver(d, s) : squareOver(ldexp(d, -520), ldexp(a, -1040) + ldexp(b, -1040));
99
+ }
71
100
  /**
72
101
  * 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.
102
+ * factors: the rows are the levels of x and the columns those of y, each sorted (numbers numerically, strings by code
103
+ * point as R sorts factor levels in the C locale; a sample mixing numbers and strings is all text, as R coerces it). As
104
+ * in R, both must have the same number of levels, at least 2; the levels are matched by position, not by value.
76
105
  */
77
106
  function crossTable(x, y) {
78
107
  if (x.length !== y.length)
79
108
  throw new RangeError("'x' and 'y' must have the same length");
80
109
  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);
110
+ // numeric values with the same 15-digit text are one level, and mixed samples are text, as in R's factor()
111
+ const xl = factorLabels(x);
112
+ const yl = factorLabels(y);
84
113
  for (let i = 0; i < x.length; i++) {
85
114
  const a = xl[i];
86
115
  const b = yl[i];
@@ -90,7 +119,7 @@ function crossTable(x, y) {
90
119
  continue;
91
120
  keep.push([a, b]);
92
121
  }
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);
122
+ const levelsOf = (v) => Array.from(new Set(v)).sort(compareLabels);
94
123
  const lx = levelsOf(keep.map((p) => p[0]));
95
124
  const ly = levelsOf(keep.map((p) => p[1]));
96
125
  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
  *
@@ -167,31 +173,6 @@ export declare function gamesHowellTest(x: Sample, g: readonly GroupLabel[]): PM
167
173
  * @category Multiple comparisons
168
174
  */
169
175
  export declare function tukeyTest(x: Sample, g: readonly GroupLabel[]): PMCMRResult;
170
- /**
171
- * Steel's many-to-one rank test. Equivalent to `PMCMRplus::steelTest()` in R. It behaves as `steelTest()` of
172
- * PMCMRplus 1.9.12 does: that fails on every input, so this reproduces its errors. A two-sided
173
- * alternative is rejected (`'arg' should be one of “greater”, “less”`), unequal group sizes give `Steel's test is
174
- * only valid for balanced designs.`, and balanced data the error PMCMRplus raises internally.
175
- *
176
- * @throws Always.
177
- *
178
- * @example
179
- * ```ts
180
- * const x = [1.2, 2.3, 1.8, 2.9, 3.1, 3.6, 4.0, 4.4, 5.2];
181
- * const g = ["a", "a", "a", "b", "b", "b", "c", "c", "c"];
182
- * const message = (() => {
183
- * try {
184
- * steelTest(x, g, { alternative: "greater" });
185
- * } catch (e) {
186
- * return (e as Error).message;
187
- * }
188
- * })();
189
- * message; // "'data' must be of a vector type, was 'NULL'"
190
- * ```
191
- *
192
- * @category Multiple comparisons
193
- */
194
- export declare function steelTest(x: Sample, g: readonly GroupLabel[], options?: ManyOneTestOptions): never;
195
176
  /**
196
177
  * Adjustment method of {@link dunnTest} (dunn.test's `method`).
197
178
  *
@@ -223,13 +204,22 @@ export interface DunnTestResult {
223
204
  P: number[];
224
205
  /** Adjusted p-values (no monotonicity step). */
225
206
  PAdjusted: number[];
207
+ /** Alias of `Z`: the same array. */
208
+ zValue: number[];
209
+ /** Alias of `P`: the same array. */
210
+ pValue: number[];
211
+ /** Alias of `PAdjusted`: the same array. */
212
+ pAdjusted: number[];
226
213
  /** Labels of the comparisons, `"<label j> - <label i>"`, in the order (2,1), (3,1), (3,2), (4,1), ... */
227
214
  comparisons: string[];
215
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
216
+ warnings: string[];
228
217
  }
229
218
  /**
230
219
  * 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
220
  * 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`).
221
+ * monotonicity, as dunn.test does (unlike `pAdjust`). Equal p-values share the rank of the first of them in the
222
+ * ordering, so they get the same adjusted value (dunn.test ranks ties in the order of the comparisons).
233
223
  *
234
224
  * @example
235
225
  * ```ts
@@ -268,8 +258,16 @@ export interface GlhtDunnettResult {
268
258
  t: number[];
269
259
  /** Simultaneous (single-step) p-values. */
270
260
  p: number[];
261
+ /** Alias of `se`: the same array. */
262
+ stdError: number[];
263
+ /** Alias of `t`: the same array. */
264
+ tValue: number[];
265
+ /** Alias of `p`: the same array. */
266
+ pValue: number[];
271
267
  /** Residual degrees of freedom, N - k. */
272
268
  df: number;
269
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
270
+ warnings: string[];
273
271
  }
274
272
  /**
275
273
  * Dunnett's many-to-one comparisons of a one-way ANOVA with simultaneous p-values. Equivalent to