@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
@@ -7,12 +7,14 @@
7
7
  // - Densities are formed in logs from the accurate log dhyper (evaluated every 16 points, exact ratios in
8
8
  // between) and normalised with double-double sums, so the root
9
9
  // search sees accurate function values; at psi = 1 the tails are the central hypergeometric distribution function
10
- // - Roots are found with R's uniroot conventions (Brent, tolerance eps^0.25; src/internal/uniroot.ts): if the root
11
- // lies below 1, on psi in [0, 1]; otherwise on s = 1/psi in [eps, 1]. R's estimate and limits are where this
12
- // iteration stops (1e-6 to 1e-2 from the true roots), so the brackets and tolerance are part of the result
10
+ // - Roots are found on the log scale of psi to the precision of the doubles (logScaleRoot, src/internal/uniroot.ts).
11
+ // R solves on psi in [0, 1] or 1/psi in [eps, 1] with the absolute tolerance eps^0.25 and stops 1e-6 to 1e-2 from
12
+ // the true roots (0.7% for the 95% upper limit of [[3, 1], [1, 3]], 6% at 99%, and the end 1/eps at 99.99%); the
13
+ // values here are the roots (review 58)
13
14
  // - The two-sided p-value is the sum of probabilities of tables whose probability is at most (1 + 1e-7) times the
14
15
  // observed one (R's convention); for or = 0 or Inf the distribution is a point mass at the end of the support
15
- // - Counts are made integer by rounding half to even (R rounds with a warning)
16
+ // - Counts are made integer by rounding half to even, with R's warning "'x' has been rounded to integer: " and the text
17
+ // of all.equal(original, rounded) (allEqualMessage)
16
18
  // The same distribution and root conventions are used for the exact Mantel-Haenszel test (src/htest/core/mantelhaen.ts).
17
19
  //
18
20
  // rxc tables: the probabilities of tables with fixed margins (multivariate hypergeometric) are
@@ -33,12 +35,17 @@
33
35
  // R's hybrid is not implemented.
34
36
  import { dhyper1, phyper1 } from "../distributions/hypergeometric.js";
35
37
  import { roundHalfEven } from "../internal/integer.js";
36
- import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
38
+ import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
37
39
  import { lfactorial } from "../special/choose.js";
38
- import { uniroot } from "../internal/uniroot.js";
40
+ import { logScaleRoot } from "../internal/uniroot.js";
39
41
  import { ddAdd, ddLog, ddNeg, ddSub } from "../special/dd.js";
40
- import { simulatedMethod } from "./core/simulate.js";
42
+ import { formatDigits, simulatedMethod } from "./core/simulate.js";
43
+ import { reported } from "../internal/warnings.js";
41
44
  import { matchAlternative } from "./types.js";
45
+ import { maxOf, minOf } from "../internal/extremes.js";
46
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
47
+ import { checkOptions } from "../internal/checkOptions.js";
48
+ const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulatePValue", "B"];
42
49
  /**
43
50
  * Fisher's exact test for count data. Equivalent to R's `fisher.test()`.
44
51
  *
@@ -47,7 +54,8 @@ import { matchAlternative } from "./types.js";
47
54
  * reproducing R's numbers (including R's root-finding tolerance). The two-sided p-value
48
55
  * sums the probabilities of tables no more likely than the observed one (relative
49
56
  * tolerance `1e-7`, as in R). Non-integer counts are rounded to the nearest integer
50
- * (ties to even), where R warns and rounds.
57
+ * (ties to even), with R's warning ("'x' has been rounded to integer: Mean relative difference: 0.0625", the text of
58
+ * R's `all.equal` of the counts and the rounded counts; none where they differ by less than about 1.5e-8).
51
59
  *
52
60
  * With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
53
61
  * observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
@@ -62,13 +70,14 @@ import { matchAlternative } from "./types.js";
62
70
  * ```ts
63
71
  * const r = fisherTest([[3, 1], [1, 3]]);
64
72
  * r.pValue; // 0.4857142857142857
65
- * r.estimate; // 6.408308867005792 (conditional MLE of the odds ratio)
66
- * r.confInt; // [0.2117329153055031, 621.9337505454175]
73
+ * r.estimate; // 6.408319658199675 (conditional MLE of the odds ratio; R: 6.408309)
74
+ * r.confInt; // [0.2117355954465785, 626.2435305888127] (R: 0.2117329, 621.93)
67
75
  * ```
68
76
  *
69
77
  * @category Hypothesis tests
70
78
  */
71
79
  export function fisherTest(x, options = {}) {
80
+ checkOptions(options, FISHER_TEST_KEYS, "fisherTest"); // generated: option-keys.mjs
72
81
  const nr = x.length;
73
82
  const nc = nr === 0 ? 0 : x[0].length;
74
83
  if (x.some((r) => r.length !== nc))
@@ -82,18 +91,61 @@ export function fisherTest(x, options = {}) {
82
91
  if (raw.flat().some((v) => v === Infinity))
83
92
  throw new RangeError("'x' has entries too large to be integer");
84
93
  const t = raw.map((r) => r.map(roundHalfEven));
94
+ // as in R, counts beyond the largest integer (2^31 - 1) are rejected (the 2 x 2 support would also be huge)
95
+ if (t.flat().some((v) => v > 2147483647))
96
+ throw new RangeError("'x' has entries too large to be integer");
97
+ const warnings = [];
98
+ const rounding = allEqualMessage(raw, t);
99
+ if (rounding !== null)
100
+ warnings.push(`'x' has been rounded to integer: ${rounding}`);
85
101
  const method = "Fisher's Exact Test for Count Data";
86
102
  if (nr === 2 && nc === 2)
87
- return fisher2x2(t, options, method);
103
+ return reported("fisherTest", { ...fisher2x2(t, options, method), warnings });
88
104
  // For rxc, alternative etc. are not validated and are returned as given (as in R)
89
105
  const alternative = (options.alternative ?? "two.sided");
90
106
  if (options.simulatePValue ?? false) {
91
107
  const B = options.B ?? 2000;
92
- if (!(B >= 0 && B < 2 ** 31))
93
- throw new RangeError("'B' must be a non-negative number");
94
- return { method: method + simulatedMethod(B), alternative, pValue: fisherSimulated(t, B) };
108
+ // a fractional B ran trunc(B) simulations but was reported as B (#278); an error, as in chisqTest. B = 0 simulates
109
+ // nothing (R's p = (1 + 0) / (0 + 1) = 1): an error too (#488)
110
+ if (!(Number.isInteger(B) && B >= 1 && B < 2 ** 31))
111
+ throw new RangeError("'B' must be a positive integer");
112
+ return reported("fisherTest", { method: method + simulatedMethod(B), alternative, pValue: fisherSimulated(t, B), warnings });
95
113
  }
96
- return { method, alternative, pValue: fisherRxC(t) };
114
+ return reported("fisherTest", { method, alternative, pValue: fisherRxC(t), warnings });
115
+ }
116
+ /**
117
+ * The text of R's `all.equal(target, current)` for two numeric matrices of the same shape with no NA, or null where
118
+ * it is TRUE: "Mean relative difference: <format(err)>", the mean absolute difference over the entries that differ
119
+ * divided by the mean absolute target over them ("absolute" with no division where that mean is at most the
120
+ * tolerance sqrt(eps) or not finite), when it exceeds the tolerance. The entries are taken in R's (column) order.
121
+ */
122
+ function allEqualMessage(target, current) {
123
+ const tolerance = Math.sqrt(Number.EPSILON);
124
+ const t = [];
125
+ const c = [];
126
+ for (let j = 0; j < target[0].length; j++) {
127
+ for (let i = 0; i < target.length; i++) {
128
+ if (target[i][j] !== current[i][j]) {
129
+ t.push(target[i][j]);
130
+ c.push(current[i][j]);
131
+ }
132
+ }
133
+ }
134
+ const n = t.length;
135
+ if (n === 0)
136
+ return null;
137
+ let scale = 0;
138
+ for (const v of t)
139
+ scale += Math.abs(v) / n;
140
+ let what = "relative";
141
+ if (!(Number.isFinite(scale) && scale > tolerance)) {
142
+ scale = 1;
143
+ what = "absolute";
144
+ }
145
+ let xy = 0;
146
+ for (let k = 0; k < n; k++)
147
+ xy += Math.abs(t[k] - c[k]) / (n * scale);
148
+ return Number.isNaN(xy) || xy > tolerance ? `Mean ${what} difference: ${formatDigits(xy)}` : null;
97
149
  }
98
150
  /** Monte Carlo p-value of an r x c table: tables with fixed margins drawn by Patefield's algorithm */
99
151
  function fisherSimulated(t, B) {
@@ -113,7 +165,11 @@ function fisherSimulated(t, B) {
113
165
  for (const v of x.flat())
114
166
  acc = ddAdd(acc, [-lfactorial(v), 0]);
115
167
  const threshold = acc[0] / (1 + 64 * Number.EPSILON);
116
- const fact = logFactorialTable(sr.reduce((a, b) => a + b, 0));
168
+ const total = sr.reduce((a, b) => a + b, 0);
169
+ // the table of log factorials has total + 1 entries: limited as in r2dtable (#286)
170
+ if (total > MAX_TABLE_TOTAL)
171
+ throw new RangeError("the simulation needs a total count of at most 16777216 (2^24)");
172
+ const fact = logFactorialTable(total);
117
173
  const table = new Int32Array(nr * nc);
118
174
  let count = 0;
119
175
  const reps = Math.trunc(B);
@@ -125,13 +181,18 @@ function fisherSimulated(t, B) {
125
181
  if (s <= threshold)
126
182
  count++;
127
183
  }
128
- return Math.max(0, Math.min(1, (1 + count) / (B + 1)));
184
+ return Math.max(0, Math.min(1, (1 + count) / (reps + 1)));
129
185
  }
130
186
  // ---- 2×2 ----
131
187
  /** Relative slack for counting a table as "no more likely than the observed one" in the two-sided p-value */
132
188
  const SLACK = 1 + 1e-7;
133
189
  /** Spacing of the points at which the central log density is evaluated directly */
134
190
  const ANCHOR = 16;
191
+ /**
192
+ * Largest support (number of values of the (1, 1) cell) of the exact 2 x 2 distribution: 2^24 values take about
193
+ * 12 s and 0.4 GB; R allocates the whole support whatever its size (counts of 1e9 would take 16 GB per array)
194
+ */
195
+ const MAX_SUPPORT = 2 ** 24;
135
196
  /** Double-double sum of v[from..to] (inclusive, clipped to the array) */
136
197
  function accurateSum(v, from, to) {
137
198
  let acc = [0, 0];
@@ -225,12 +286,9 @@ class OddsRatioDistribution {
225
286
  return upper ? accurateSum(d, j, d.length - 1) : accurateSum(d, 0, j);
226
287
  }
227
288
  }
228
- /**
229
- * Root of f, monotone in the odds ratio psi: searched for as psi in [0, 1] when it lies below 1, otherwise as
230
- * s = 1/psi in [eps, 1] (uniroot with its default tolerance in both cases)
231
- */
289
+ /** Root of f, monotone in the odds ratio psi, to the precision of the doubles (on the log scale, see logScaleRoot) */
232
290
  function oddsRatioRoot(f, belowOne) {
233
- return belowOne ? uniroot(f, 0, 1) : 1 / uniroot((s) => f(1 / s), Number.EPSILON, 1);
291
+ return logScaleRoot(f, belowOne);
234
292
  }
235
293
  function fisher2x2(t, options, method) {
236
294
  const alternative = matchAlternative(options.alternative);
@@ -242,6 +300,11 @@ function fisher2x2(t, options, method) {
242
300
  throw new RangeError("confLevel must be a single number between 0 and 1");
243
301
  const [[a, b], [c, d]] = t;
244
302
  const x = a;
303
+ // the support lo..hi has min(a, d) + min(b, c) + 1 values; checked before it is allocated
304
+ const size = Math.min(a, d) + Math.min(b, c) + 1;
305
+ if (size > MAX_SUPPORT) {
306
+ throw new RangeError(`the exact distribution of the 2 x 2 table has ${size} values, more than 2^24`);
307
+ }
245
308
  const dist = new OddsRatioDistribution(a + c, b + d, a + b);
246
309
  const { lo, hi } = dist;
247
310
  let pValue;
@@ -279,6 +342,7 @@ function fisher2x2(t, options, method) {
279
342
  estimateNames: "odds ratio",
280
343
  nullValue: or,
281
344
  nullValueName: "odds ratio",
345
+ warnings: [],
282
346
  };
283
347
  if (!(options.confInt ?? true))
284
348
  return result;
@@ -430,8 +494,8 @@ function fisherRxC(t) {
430
494
  };
431
495
  rec(0, colSums[j], [0, 0]);
432
496
  node.edges = [...groups.values()];
433
- node.max = Math.max(...node.edges.map((e) => e.hi + e.to.max));
434
- node.min = Math.min(...node.edges.map((e) => e.hi + e.to.min));
497
+ node.max = maxOf(node.edges.map((e) => e.hi + e.to.max));
498
+ node.min = minOf(node.edges.map((e) => e.hi + e.to.min));
435
499
  if (j === ncol - 2) {
436
500
  // With two columns left, the rest of the table is determined by a single edge. Sort by value and take cumulative sums,
437
501
  // then find the threshold position per path by binary search (reducing paths × edges work to paths × log(edges))
@@ -5,6 +5,13 @@ import type { Sample } from "./types.js";
5
5
  * @category Hypothesis tests
6
6
  */
7
7
  export type GroupLabel = number | string;
8
+ /**
9
+ * Labels as R's factor() takes them: numbers with the same 15-digit text as one (numberLevels), and all as text when
10
+ * any label is a string (R coerces a mixed vector to character). NaN stays missing
11
+ */
12
+ export declare function factorLabels(g: readonly GroupLabel[]): GroupLabel[];
13
+ /** Order of levels (of one type after factorLabels): numbers numerically, strings by code point (C locale) */
14
+ export declare function compareLabels(a: GroupLabel, b: GroupLabel): number;
8
15
  /** Groups with their labels: the sorted labels (x, g form) or the 1-based positions in the list (list form) */
9
16
  export interface LabelledGroups {
10
17
  labels: string[];
@@ -2,8 +2,25 @@
2
2
  // of group labels (R's x, g form). Pairs with a missing value or label are dropped, and groups are kept in order
3
3
  // of the sorted labels (as R orders factor levels). Numeric labels with the same 15-digit text are one group, as in
4
4
  // R's factor() (src/internal/levels.ts); the group's label is the smallest of them, written as R writes it
5
- // ("1e+15", "0.333333333333333").
5
+ // ("1e+15", "0.333333333333333"). When the labels mix numbers and strings, all are text, as R coerces such a vector
6
+ // to character (2 and "2" are one group); levels are then ordered by code point.
6
7
  import { levelText, numberLevels } from "../internal/levels.js";
8
+ import { compareCodePoints } from "../models/modelFrame.js";
9
+ import { midpoint } from "../internal/extremes.js";
10
+ /**
11
+ * Labels as R's factor() takes them: numbers with the same 15-digit text as one (numberLevels), and all as text when
12
+ * any label is a string (R coerces a mixed vector to character). NaN stays missing
13
+ */
14
+ export function factorLabels(g) {
15
+ const gs = numberLevels(g);
16
+ if (!gs.some((l) => typeof l === "string"))
17
+ return gs;
18
+ return gs.map((l) => (typeof l === "number" && !Number.isNaN(l) ? levelText(l) : l));
19
+ }
20
+ /** Order of levels (of one type after factorLabels): numbers numerically, strings by code point (C locale) */
21
+ export function compareLabels(a, b) {
22
+ return typeof a === "number" && typeof b === "number" ? a - b : compareCodePoints(String(a), String(b));
23
+ }
7
24
  /**
8
25
  * Normalise the two input forms to groups with NaN removed, each with its label. In the x, g form a label whose
9
26
  * values are all missing has no group (as R drops an unused factor level). In the list form a group left empty is
@@ -30,7 +47,7 @@ export function labelledGroups(x, g, emptyGroups = "drop") {
30
47
  const xs = Array.from(x);
31
48
  if (xs.length !== g.length)
32
49
  throw new RangeError("'x' and 'g' must have the same length");
33
- const gs = numberLevels(g);
50
+ const gs = factorLabels(g);
34
51
  const byLabel = new Map();
35
52
  for (let i = 0; i < xs.length; i++) {
36
53
  const v = xs[i];
@@ -42,7 +59,7 @@ export function labelledGroups(x, g, emptyGroups = "drop") {
42
59
  byLabel.set(l, (arr = []));
43
60
  arr.push(v);
44
61
  }
45
- const labels = Array.from(byLabel.keys()).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0);
62
+ const labels = Array.from(byLabel.keys()).sort(compareLabels);
46
63
  return { labels: labels.map(levelText), groups: labels.map((l) => byLabel.get(l)) };
47
64
  }
48
65
  /** Normalise the two input forms to an array of non-empty groups with NaN removed (see {@link labelledGroups}) */
@@ -53,7 +70,7 @@ export function toGroups(x, g, emptyGroups = "drop") {
53
70
  export function median(x) {
54
71
  const s = [...x].sort((a, b) => a - b);
55
72
  const n = s.length;
56
- return n % 2 === 1 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
73
+ return n % 2 === 1 ? s[(n - 1) / 2] : midpoint(s[n / 2 - 1], s[n / 2]);
57
74
  }
58
75
  /** Rows of a blocks x treatments table with any NaN dropped (R's complete.cases) */
59
76
  export function completeRows(y) {
@@ -13,7 +13,9 @@ export interface KsTestOptions {
13
13
  alternative?: Alternative | "two" | "l" | "g";
14
14
  /**
15
15
  * Exact p-value. Default: exact for one sample of fewer than 100 values without ties, and for two samples with
16
- * m n < 10000.
16
+ * m n < 10000. The exact two-sided one-sample p-value for D < 1/2 raises a matrix of size 2 floor(n D) + 1 to the
17
+ * n-th power; where that needs more than 2^33 multiply-adds (m 781 at n 1023, about 4 s) it is a RangeError (R
18
+ * computes it however long it takes).
17
19
  */
18
20
  exact?: boolean;
19
21
  }
@@ -33,6 +35,10 @@ export interface KsTestResult extends Omit<HTest, "alternative"> {
33
35
  * Kolmogorov-Smirnov test. Equivalent to R's `ks.test()`. Takes a distribution function given as a function (for
34
36
  * example `(q) => pnorm(q)`) or a second sample. `NaN` values are dropped.
35
37
  *
38
+ * As R, `warnings` has "ties should not be present for the one-sample Kolmogorov-Smirnov test" for one sample with
39
+ * ties, and "p-value will be approximate in the presence of ties" for two samples with ties and `exact: false` (or
40
+ * m n >= 10000).
41
+ *
36
42
  * @param x Sample.
37
43
  * @param y A continuous distribution function, or a second sample.
38
44
  * @param options See {@link KsTestOptions}.
@@ -6,10 +6,16 @@
6
6
  // Kolmogorov's limit and exp(-2 n D^2). Two samples: the largest differences of the empirical distribution functions,
7
7
  // taken only where the pooled sorted values change; exact p-values (by default for m n < 10000, with or without ties)
8
8
  // by counting lattice paths, asymptotic ones as for one sample with n replaced by m n / (m + n).
9
- import { pkolmogorovExact, pkolmogorovLimit, pkolmogorovOneSidedUpper } from "./core/kolmogorov.js";
9
+ // R's warnings: "ties should not be present for the one-sample Kolmogorov-Smirnov test" for one sample with ties, and
10
+ // "p-value will be approximate in the presence of ties" for two samples with ties and the asymptotic p-value.
11
+ import { checkKolmogorovExactSize, pkolmogorovExact, pkolmogorovExactUpper, pkolmogorovLimit, pkolmogorovOneSidedUpper, } from "./core/kolmogorov.js";
10
12
  import { psmirnovUpper } from "./core/smirnov.js";
11
13
  import { twoGroupData } from "./testFormula.js";
12
14
  import { matchAlternative } from "./types.js";
15
+ import { reported } from "../internal/warnings.js";
16
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
+ import { checkOptions } from "../internal/checkOptions.js";
18
+ const KS_TEST_KEYS = ["alternative", "exact"];
13
19
  function describe(alternative, oneSample) {
14
20
  if (alternative === "two.sided")
15
21
  return "two-sided";
@@ -17,6 +23,7 @@ function describe(alternative, oneSample) {
17
23
  return `the CDF of x lies ${where} ${oneSample ? "the null hypothesis" : "that of y"}`;
18
24
  }
19
25
  export function ksTest(x, y, options = {}) {
26
+ checkOptions(options, KS_TEST_KEYS, "ksTest"); // generated: option-keys.mjs
20
27
  if (typeof x === "string") {
21
28
  const d = twoGroupData(x, y);
22
29
  return ksTest(d.x, d.y, options);
@@ -34,6 +41,9 @@ export function ksTest(x, y, options = {}) {
34
41
  let dminus = -Infinity;
35
42
  for (let i = 0; i < n; i++) {
36
43
  const f = y(xs[i]);
44
+ // a distribution function takes values in [0, 1] (R uses whatever it returns: D = 1.5 and p = 0 for 1.5)
45
+ if (!(f >= 0 && f <= 1))
46
+ throw new RangeError(`the distribution function returned ${f} at ${xs[i]}, not a value in [0, 1]`);
37
47
  dplus = Math.max(dplus, (i + 1) / n - f);
38
48
  dminus = Math.max(dminus, f - i / n);
39
49
  }
@@ -41,20 +51,39 @@ export function ksTest(x, y, options = {}) {
41
51
  const ties = new Set(xs).size < n;
42
52
  const exact = options.exact ?? (n < 100 && !ties);
43
53
  let pValue;
54
+ // (the matrix of the exact distribution grows with n D: a RangeError before it is built when too large, #307)
55
+ if (exact && alternative === "two.sided" && statistic < 0.5)
56
+ checkKolmogorovExactSize(n, statistic);
44
57
  if (alternative === "two.sided") {
45
- pValue = exact ? 1 - pkolmogorovExact(n, statistic) : pkolmogorovLimit(Math.sqrt(n) * statistic, false);
58
+ // For D >= 1/2 the two one-sided exceedances cannot both occur, so P(D >= d) = 2 P(D+ >= d) exactly, a sum of
59
+ // positive terms: 1 - P(D < d) lost all digits of small p-values (D = 0.9 gave 0 at n = 20 for 2e-20, and 3e-15
60
+ // at n = 99 for 2e-99; R too). For D < 1/2 and 2 P(D+ >= d) < 1e-2 (an upper bound of p), the upper tail as a sum of positive
61
+ // terms too (#483: 1e-22 was 3e-15 at n = 99, R 2e-15); 1 - P(D < d) where p may be larger (as R), or where the
62
+ // sum needs too much work
63
+ if (!exact)
64
+ pValue = pkolmogorovLimit(Math.sqrt(n) * statistic, false);
65
+ else {
66
+ const bound = 2 * pkolmogorovOneSidedUpper(n, statistic);
67
+ if (statistic >= 0.5)
68
+ pValue = Math.min(1, bound);
69
+ else {
70
+ const upper = bound < 1e-2 ? pkolmogorovExactUpper(n, statistic) : NaN;
71
+ pValue = Number.isNaN(upper) ? 1 - pkolmogorovExact(n, statistic) : upper;
72
+ }
73
+ }
46
74
  }
47
75
  else {
48
76
  pValue = exact ? pkolmogorovOneSidedUpper(n, statistic) : Math.exp(-2 * n * statistic * statistic);
49
77
  }
50
- return {
78
+ return reported("ksTest", {
51
79
  method: `${exact ? "Exact" : "Asymptotic"} one-sample Kolmogorov-Smirnov test`,
52
80
  alternative: describe(alternative, true),
53
81
  exact,
54
82
  statistic,
55
83
  statisticName,
56
84
  pValue: Math.min(1, Math.max(0, pValue)),
57
- };
85
+ warnings: ties ? ["ties should not be present for the one-sample Kolmogorov-Smirnov test"] : [],
86
+ });
58
87
  }
59
88
  const ys = Array.from(y).filter((v) => !Number.isNaN(v));
60
89
  const m = ys.length;
@@ -92,12 +121,13 @@ export function ksTest(x, y, options = {}) {
92
121
  ? pkolmogorovLimit(Math.sqrt(en) * statistic, false)
93
122
  : Math.exp(-2 * en * statistic * statistic);
94
123
  }
95
- return {
124
+ return reported("ksTest", {
96
125
  method: `${exact ? "Exact" : "Asymptotic"} two-sample Kolmogorov-Smirnov test`,
97
126
  alternative: describe(alternative, false),
98
127
  exact,
99
128
  statistic,
100
129
  statisticName,
101
130
  pValue: Math.min(1, Math.max(0, pValue)),
102
- };
131
+ warnings: ties && !exact ? ["p-value will be approximate in the presence of ties"] : [],
132
+ });
103
133
  }
@@ -21,6 +21,8 @@ export interface LeveneTestResult {
21
21
  rowNames: string[];
22
22
  /** One array per row; NaN where car prints nothing. */
23
23
  table: number[][];
24
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
25
+ warnings: string[];
24
26
  }
25
27
  /**
26
28
  * Levene's test for homogeneity of variance across groups. Equivalent to `car::leveneTest()` in R. Computes
@@ -3,10 +3,15 @@
3
3
  // median).
4
4
  //
5
5
  // Written for rStats.js from oracle/rm-tests-behaviour.md (no ported code; car's source was not read).
6
- import { mean } from "../internal/summary.js";
7
- import { aov } from "./aov.js";
8
- import { labelledGroups, median } from "./groups.js";
6
+ import { ldexp, mean, scaleToUnit } from "../internal/summary.js";
7
+ import { onewayTable } from "./aov.js";
8
+ import { labelledGroups, median, toGroups } from "./groups.js";
9
9
  import { matchChoice } from "./power.js";
10
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
11
+ import { checkOptions } from "../internal/checkOptions.js";
12
+ const LEVENE_TEST_KEYS = ["center"];
13
+ // Generated by `node scripts/option-keys.mjs --write` (end)
14
+ const MIN_NORMAL = 2 ** -1022;
10
15
  /**
11
16
  * Levene's test for homogeneity of variance across groups. Equivalent to `car::leveneTest()` in R. Computes
12
17
  * `leveneTest(y ~ g, center = median)` (or `mean`). Pairs with a missing value are dropped; groups are ordered by
@@ -24,15 +29,31 @@ import { matchChoice } from "./power.js";
24
29
  * @category Hypothesis tests
25
30
  */
26
31
  export function leveneTest(y, g, options = {}) {
32
+ checkOptions(options, LEVENE_TEST_KEYS, "leveneTest"); // generated: option-keys.mjs
27
33
  const center = matchChoice(options.center ?? "median", ["median", "mean"]);
28
34
  const { groups } = labelledGroups(y, g);
29
35
  if (groups.length < 2)
30
36
  throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
31
- const deviations = groups.map((s) => {
37
+ // the absolute deviations of the data scaled by one power of 2 (exact), so that they cannot overflow; F does not
38
+ // depend on the units
39
+ const deviationsOf = (s) => {
32
40
  const c = center === "median" ? median(s) : mean(s);
33
41
  return s.map((v) => Math.abs(v - c));
34
- });
35
- const r = aov(deviations);
42
+ };
43
+ let deviations = scaleToUnit(groups).groups.map(deviationsOf);
44
+ const lost = (d, i) => d.some((v) => v > 0 && v < MIN_NORMAL) || (d.every((v) => v === 0) && groups[i].some((v) => v !== groups[i][0]));
45
+ if (deviations.some(lost)) {
46
+ // the deviations of a group fall below the normal range on the common scale (#393; as #270): each group's
47
+ // deviations on its own scale, then all on the scale of the largest deviation
48
+ const own = groups.map((s) => {
49
+ const r = scaleToUnit([s]);
50
+ return { d: deviationsOf(r.groups[0]), k: r.k };
51
+ });
52
+ const top = Math.max(...own.map((o) => (o.d.some((v) => v > 0) ? Math.floor(Math.log2(Math.max(...o.d))) + o.k : -Infinity)));
53
+ const e = Number.isFinite(top) ? top : 0;
54
+ deviations = own.map((o) => o.d.map((v) => ldexp(v, o.k - e)));
55
+ }
56
+ const r = onewayTable(toGroups(deviations));
36
57
  return {
37
58
  colNames: ["Df", "F value", "Pr(>F)"],
38
59
  rowNames: ["group", ""],
@@ -40,5 +61,6 @@ export function leveneTest(y, g, options = {}) {
40
61
  [r.df[0], r.fValue, r.pValue],
41
62
  [r.df[1], NaN, NaN],
42
63
  ],
64
+ warnings: [],
43
65
  };
44
66
  }