@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
package/dist/htest/aov.js CHANGED
@@ -1,47 +1,37 @@
1
- // One-way analysis of variance (the table of R's summary(aov(y ~ g))), aov from a model formula (the fit of
2
- // src/models/lm.ts; its table is aovSummary in src/models/anovaSequential.ts), Tukey's honest significant differences (R's
3
- // TukeyHSD) and the z test with known standard deviations (as BSDA's z.test).
1
+ // aov from a model formula or from samples (the fit of src/models/lm.ts, with samples as the model y ~ g; its table
2
+ // is aovSummary in src/models/anovaSequential.ts), the one-way table that leveneTest uses, Tukey's honest significant
3
+ // differences (R's TukeyHSD) and the z test with known standard deviations (as BSDA's z.test).
4
4
  //
5
- // Written for rStats.js from the textbook formulas. The sums of squares are accumulated in
6
- // double-double: between groups sum n_i (m_i - m)^2, within groups sum (x - m_i)^2, so a within sum that is exactly
7
- // 0 stays 0 (F = Inf; R's QR leaves rounding residue there). TukeyHSD uses the Tukey-Kramer standard error
8
- // sqrt(MSE / 2 (1/n_i + 1/n_j)) with the studentized range distribution for the interval and the adjusted p-value.
5
+ // Written for rStats.js from the textbook formulas. The sums of squares of the one-way table and of TukeyHSD are
6
+ // accumulated in double-double: between groups sum n_i (m_i - m)^2, within groups sum (x - m_i)^2, so a within sum
7
+ // that is exactly 0 stays 0 (F = Inf; R's QR leaves rounding residue there). TukeyHSD uses the Tukey-Kramer standard
8
+ // error sqrt(MSE / 2 (1/n_i + 1/n_j)) with the studentized range distribution for the interval and the adjusted
9
+ // p-value.
9
10
  // zTest is the textbook z test (standard error sigma / sqrt(n), or sqrt(sigma_x^2/n_x + sigma_y^2/n_y) for two
10
11
  // samples, normal quantiles for the interval around the estimate); its input checks (at least 3 observations,
11
12
  // confLevel allowed in the closed [0, 1]) follow BSDA's documented/observed behaviour, with messages of our own.
12
13
  import { pf1 } from "../distributions/f.js";
13
14
  import { pnorm, qnorm } from "../distributions/normal.js";
14
15
  import { ptukey, qtukey } from "../distributions/tukey.js";
15
- import { meanDD } from "../internal/summary.js";
16
- import { ddAdd, ddMul, ddSub } from "../special/dd.js";
16
+ import { groupMoments, ldexp, meanDD, scaleToUnit } from "../internal/summary.js";
17
17
  import { parseFormula, splitErrorTerms } from "../models/formula.js";
18
18
  import { aovStrataFit } from "../models/aovStrata.js";
19
19
  import { lmFormulaFit } from "../models/lm.js";
20
20
  import { design } from "../models/modelMatrix.js";
21
- import { labelledGroups, toGroups } from "./groups.js";
22
- import { matchAlternative } from "./types.js";
23
- function sums(groups) {
24
- const all = groups.flat();
25
- const m = meanDD(all);
26
- let ssb = [0, 0];
27
- let ssw = [0, 0];
28
- const means = [];
29
- for (const g of groups) {
30
- const mi = meanDD(g);
31
- means.push(mi[0]);
32
- const d = ddSub(mi, m);
33
- ssb = ddAdd(ssb, ddMul(ddMul(d, d), [g.length, 0]));
34
- for (const v of g) {
35
- const e = ddSub([v, 0], mi);
36
- ssw = ddAdd(ssw, ddMul(e, e));
37
- }
38
- }
39
- return { ssb: ssb[0], ssw: ssw[0], means };
40
- }
21
+ import { labelledGroups } from "./groups.js";
22
+ import { checkConfLevel, matchAlternative } from "./types.js";
23
+ import { reported } from "../internal/warnings.js";
24
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
25
+ import { checkOptions } from "../internal/checkOptions.js";
26
+ import { isOptionsObject } from "../internal/optionalArgs.js";
27
+ const AOV_KEYS = ["weights", "contrasts", "levels"];
28
+ const TUKEY_HSD_KEYS = ["confLevel"];
29
+ const Z_TEST_KEYS = ["sigmaX", "sigmaY", "mu", "alternative", "confLevel"];
41
30
  export function aov(x, g, options = {}) {
31
+ checkOptions(options, AOV_KEYS, "aov"); // generated: option-keys.mjs
42
32
  if (typeof x === "string")
43
- return aovFormula(x, g, options);
44
- return aovOneway(x, g);
33
+ return reported("aov", aovFormula(x, g, options));
34
+ return reported("aov", aovGroups(x, g));
45
35
  }
46
36
  /** aov from a formula (without Error() strata) */
47
37
  function aovFormula(formula, data, options) {
@@ -53,22 +43,36 @@ function aovFormula(formula, data, options) {
53
43
  return aovStrataFit(formula, parsed, treatment, errors[0], data, options);
54
44
  return lmFormulaFit(formula, design(parsed, data, { ...options, dropUnusedLevels: true }, treatment), true);
55
45
  }
56
- function aovOneway(x, g) {
57
- const groups = toGroups(x, g);
46
+ /** aov(x, g): the fit of y ~ g, with the groups as a factor whose levels are the group labels in order */
47
+ function aovGroups(x, g) {
48
+ const { labels, groups } = labelledGroups(x, g);
49
+ if (groups.length < 2)
50
+ throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
51
+ const y = groups.flat();
52
+ const gs = groups.flatMap((s, i) => s.map(() => labels[i]));
53
+ return aovFormula("y ~ g", { y, g: gs }, { levels: { g: labels } });
54
+ }
55
+ /**
56
+ * The one-way ANOVA table of groups: the sums of squares of groupMoments (double-double, on the data scaled by a
57
+ * power of 2), so that a within sum that is exactly 0 stays 0
58
+ */
59
+ export function onewayTable(groups) {
58
60
  const k = groups.length;
59
61
  if (k < 2)
60
62
  throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
61
63
  const N = groups.reduce((a, s) => a + s.length, 0);
62
- const { ssb, ssw } = sums(groups);
64
+ // sums of squares of the data scaled by 2^-k (groupMoments): F from them, the sums of squares scaled back
65
+ const { ssBetween: ssb, ssWithin: ssw, k: e } = groupMoments(groups);
63
66
  const df1 = k - 1;
64
67
  const df2 = N - k;
65
68
  const msb = ssb / df1;
66
69
  const msw = ssw / df2;
67
70
  const fValue = msb / msw;
71
+ const back = (v) => ldexp(v, 2 * e);
68
72
  return {
69
73
  df: [df1, df2],
70
- sumSq: [ssb, ssw],
71
- meanSq: [msb, msw],
74
+ sumSq: [back(ssb), back(ssw)],
75
+ meanSq: [back(msb), back(msw)],
72
76
  fValue,
73
77
  pValue: df2 > 0 ? pf1(fValue, df1, df2, false, false) : NaN,
74
78
  };
@@ -92,6 +96,9 @@ function aovOneway(x, g) {
92
96
  * @category Multiple comparisons
93
97
  */
94
98
  export function TukeyHSD(x, g, options = {}) {
99
+ if (isOptionsObject(g))
100
+ checkOptions(g, TUKEY_HSD_KEYS, "TukeyHSD"); // generated: option-keys.mjs
101
+ checkOptions(options, TUKEY_HSD_KEYS, "TukeyHSD"); // generated: option-keys.mjs
95
102
  let labels;
96
103
  if (g !== undefined && !Array.isArray(g))
97
104
  options = g;
@@ -104,12 +111,23 @@ export function TukeyHSD(x, g, options = {}) {
104
111
  if (k < 2)
105
112
  throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
106
113
  const confLevel = options.confLevel ?? 0.95;
114
+ // R accepts 0 and 1 (limits diff and ±Inf) but returns NaN limits outside [0, 1]: that is rejected
115
+ checkConfLevel(confLevel);
107
116
  const N = groups.reduce((a, s) => a + s.length, 0);
108
117
  const df = N - k;
109
- const { ssw, means } = sums(groups);
118
+ // No residual variance without residual degrees of freedom (one value per group): the limits and p-values were NaN
119
+ // (R's too). The message is tukeyTest's (#315)
120
+ if (df === 0)
121
+ throw new RangeError("no residual degrees of freedom");
122
+ // ptukey and qtukey (R's too) are defined from 2 df: with 1 the limits and p-values were NaN (#315)
123
+ if (df < 2)
124
+ throw new RangeError("the studentized range needs at least 2 residual degrees of freedom");
125
+ // means and MSE of the data scaled by 2^-e (groupMoments): the differences and limits are scaled back
126
+ const { ssWithin: ssw, mean: means, k: e } = groupMoments(groups);
110
127
  const mse = ssw / df;
111
128
  const q = qtukey(confLevel, k, df);
112
- const out = { names: [], i: [], j: [], diff: [], lwr: [], upr: [], pAdj: [] };
129
+ const pAdj = [];
130
+ const out = { names: [], i: [], j: [], diff: [], lwr: [], upr: [], pAdj, pAdjusted: pAdj, warnings: [] };
113
131
  for (let b = 0; b < k - 1; b++) {
114
132
  for (let a = b + 1; a < k; a++) {
115
133
  const diff = means[a] - means[b];
@@ -117,9 +135,9 @@ export function TukeyHSD(x, g, options = {}) {
117
135
  out.names.push(`${names[a]}-${names[b]}`);
118
136
  out.i.push(a + 1);
119
137
  out.j.push(b + 1);
120
- out.diff.push(diff);
121
- out.lwr.push(diff - q * se);
122
- out.upr.push(diff + q * se);
138
+ out.diff.push(ldexp(diff, e));
139
+ out.lwr.push(ldexp(diff - q * se, e));
140
+ out.upr.push(ldexp(diff + q * se, e));
123
141
  out.pAdj.push(ptukey(Math.abs(diff) / se, k, df, { lowerTail: false }));
124
142
  }
125
143
  }
@@ -138,6 +156,9 @@ export function TukeyHSD(x, g, options = {}) {
138
156
  * @category Hypothesis tests
139
157
  */
140
158
  export function zTest(x, y, options = {}) {
159
+ if (isOptionsObject(y))
160
+ checkOptions(y, Z_TEST_KEYS, "zTest"); // generated: option-keys.mjs
161
+ checkOptions(options, Z_TEST_KEYS, "zTest"); // generated: option-keys.mjs
141
162
  let ys;
142
163
  if (y !== undefined && !ArrayBuffer.isView(y) && !Array.isArray(y))
143
164
  options = y;
@@ -150,6 +171,10 @@ export function zTest(x, y, options = {}) {
150
171
  if (sigmaX === undefined || (ys !== undefined && sigmaY === undefined)) {
151
172
  throw new RangeError("sigmaX and sigmaY are both required for two samples");
152
173
  }
174
+ for (const sd of [sigmaX, sigmaY]) {
175
+ if (sd !== undefined && !(sd > 0 && sd < Infinity))
176
+ throw new RangeError("sigmaX and sigmaY must be positive finite numbers");
177
+ }
153
178
  if (Number.isNaN(mu))
154
179
  throw new RangeError("mu must be a number");
155
180
  const alternative = matchAlternative(options.alternative);
@@ -162,11 +187,16 @@ export function zTest(x, y, options = {}) {
162
187
  throw new RangeError("x needs at least 3 non-missing values");
163
188
  if (yv !== undefined && yv.length < 3)
164
189
  throw new RangeError("y needs at least 3 non-missing values");
165
- const meanX = meanDD(xs)[0];
166
- const meanY = yv === undefined ? NaN : meanDD(yv)[0];
167
- const se = yv === undefined ? sigmaX / Math.sqrt(xs.length) : Math.sqrt(sigmaX ** 2 / xs.length + sigmaY ** 2 / yv.length);
190
+ // the data, the known standard deviations and mu scaled by one power of 2 (exact), so that the squared standard
191
+ // deviations stay in range; the estimates and interval are scaled back
192
+ const sc = scaleToUnit([xs, yv ?? [], [sigmaX, sigmaY ?? 0]]);
193
+ const k = sc.k;
194
+ const [xS, yS, [sxS, syS]] = sc.groups;
195
+ const meanX = meanDD(xS)[0];
196
+ const meanY = yv === undefined ? NaN : meanDD(yS)[0];
197
+ const se = yv === undefined ? sxS / Math.sqrt(xs.length) : Math.sqrt(sxS ** 2 / xs.length + syS ** 2 / yv.length);
168
198
  const target = yv === undefined ? meanX : meanX - meanY;
169
- const z = (target - mu) / se;
199
+ const z = (target - ldexp(mu, -k)) / se;
170
200
  let pValue;
171
201
  let confInt;
172
202
  if (alternative === "less") {
@@ -179,10 +209,22 @@ export function zTest(x, y, options = {}) {
179
209
  }
180
210
  else {
181
211
  pValue = 2 * pnorm(-Math.abs(z));
182
- const half = qnorm(1 - (1 - confLevel) / 2) * se;
212
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
213
+ const a2 = (1 - confLevel) / 2;
214
+ const half = (a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - (1 - confLevel) / 2)) * se;
183
215
  confInt = [target - half, target + half];
184
216
  }
217
+ confInt = [ldexp(confInt[0], k), ldexp(confInt[1], k)];
185
218
  const twoSample = yv !== undefined;
219
+ // The reported means. Where the common scale, set by sigma, divides a nonzero value below the normal range (#192: x
220
+ // around 1e-308 with sigma 1e308 gave the mean 0), the mean of that sample in its own scale instead, but never scaled
221
+ // up: small data are averaged as they are, so that a subnormal mean is rounded once. Elsewhere the same bits
222
+ const reported = (v, vS) => {
223
+ if (!(k > 0 && v.some((t, j) => t !== 0 && Math.abs(vS[j]) < 2 ** -1022)))
224
+ return ldexp(meanDD(vS)[0], k);
225
+ const own = Math.max(scaleToUnit([v]).k, 0);
226
+ return ldexp(meanDD(own === 0 ? v : v.map((t) => ldexp(t, -own)))[0], own);
227
+ };
186
228
  return {
187
229
  method: twoSample ? "Two-sample z-Test" : "One-sample z-Test",
188
230
  alternative,
@@ -191,9 +233,10 @@ export function zTest(x, y, options = {}) {
191
233
  pValue,
192
234
  confInt,
193
235
  confLevel,
194
- estimate: twoSample ? [meanX, meanY] : meanX,
236
+ estimate: twoSample ? [reported(xs, xS), reported(yv, yS)] : reported(xs, xS),
195
237
  estimateNames: twoSample ? ["mean of x", "mean of y"] : "mean of x",
196
238
  nullValue: mu,
197
239
  nullValueName: twoSample ? "difference in means" : "mean",
240
+ warnings: [],
198
241
  };
199
242
  }
@@ -44,3 +44,8 @@ export interface BinomTestResult extends HTest {
44
44
  * @category Hypothesis tests
45
45
  */
46
46
  export declare function binomTest(x: number | readonly [number, number], n?: number | BinomTestOptions, options?: BinomTestOptions): BinomTestResult;
47
+ /**
48
+ * The exact binomial test of xs successes in ns trials, without the check of ns > 0 (poissonTest compares two counts
49
+ * of 0 as R does: p-value 1, interval [0, 1])
50
+ */
51
+ export declare function binomTestCounts(xs: number, ns: number, options?: BinomTestOptions): BinomTestResult;
@@ -8,16 +8,32 @@
8
8
  // quantiles.
9
9
  import { dbinom1, pbinom1 } from "../distributions/binomial.js";
10
10
  import { qbeta1 } from "../distributions/beta.js";
11
- import { checkConfLevelOpen, matchAlternative } from "./types.js";
11
+ import { firstTrue, lastTrue } from "../internal/discrete.js";
12
+ import { twoSum } from "../special/dd.js";
13
+ import { checkConfLevelOpen, isCount, matchAlternative } from "./types.js";
14
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
15
+ import { checkOptions } from "../internal/checkOptions.js";
16
+ const BINOM_TEST_KEYS = ["p", "alternative", "confLevel"];
12
17
  /** Relative slack when comparing outcome probabilities with the observed one */
13
18
  const SLACK = 1 + 1e-7;
14
- function isCount(v) {
15
- return Number.isFinite(v) && v >= 0 && Math.abs(v - Math.round(v)) <= 1e-7 * Math.max(1, Math.abs(v));
19
+ /**
20
+ * P[X >= x] under Binomial(n, p). Where x - 1 or n - (x - 1) is not exact (beyond 2^53), P[X > x] + dbinom(x):
21
+ * pbinom(x - 1, upper) took a rounded x - 1 or n - (x - 1) (x = 2^53, n = 2^54, p = 1/2 gave 0.5, true
22
+ * 0.5000000029724; issue #324)
23
+ */
24
+ function atLeast(x, n, p) {
25
+ const xm = x - 1;
26
+ if (x === 0 || (x - xm === 1 && twoSum(n, -xm)[1] === 0))
27
+ return pbinom1(xm, n, p, false, false);
28
+ return pbinom1(x, n, p, false, false) + dbinom1(x, n, p, false);
16
29
  }
17
30
  /**
18
31
  * Two-sided p-value: the total probability of the outcomes no more likely than x (within the relative slack). The
19
- * observed side is one tail of the distribution function; on the opposite side the qualifying outcomes are counted,
20
- * and as they are the most extreme ones there, their mass is again a tail probability.
32
+ * observed side is one tail of the distribution function; on the opposite side the qualifying outcomes are the most
33
+ * extreme ones there, so their mass is again a tail probability. The density decreases from ceil(np) upwards and
34
+ * increases up to floor(np) (the ratio f(i + 1) / f(i) = (n - i) p / ((i + 1)(1 - p)) is below 1 exactly for
35
+ * i > (n + 1) p - 1), so the boundary of the qualifying outcomes is found by search in O(log n) evaluations instead of
36
+ * testing each of the outcomes on that side (which took seconds for n around 1e8).
21
37
  */
22
38
  function twoSidedP(x, n, p) {
23
39
  if (p === 0)
@@ -28,19 +44,17 @@ function twoSidedP(x, n, p) {
28
44
  if (x === mean)
29
45
  return 1;
30
46
  const cut = dbinom1(x, n, p, false) * SLACK;
31
- let count = 0;
47
+ const qualifies = (i) => dbinom1(i, n, p, false) <= cut;
32
48
  if (x < mean) {
33
- for (let i = Math.ceil(mean); i <= n; i++)
34
- if (dbinom1(i, n, p, false) <= cut)
35
- count++;
36
- const other = count === 0 ? 0 : pbinom1(n - count, n, p, false, false);
49
+ // the first qualifying outcome above the mean; those from it to n qualify
50
+ const j = firstTrue(qualifies, Math.ceil(mean), n);
51
+ const other = j > n ? 0 : atLeast(j, n, p);
37
52
  return Math.min(1, pbinom1(x, n, p, true, false) + other);
38
53
  }
39
- for (let i = 0; i <= Math.floor(mean); i++)
40
- if (dbinom1(i, n, p, false) <= cut)
41
- count++;
42
- const other = count === 0 ? 0 : pbinom1(count - 1, n, p, true, false);
43
- return Math.min(1, pbinom1(x - 1, n, p, false, false) + other);
54
+ // the last qualifying outcome below the mean; those from 0 to it qualify
55
+ const j = lastTrue(qualifies, 0, Math.floor(mean));
56
+ const other = j < 0 ? 0 : pbinom1(j, n, p, true, false);
57
+ return Math.min(1, atLeast(x, n, p) + other);
44
58
  }
45
59
  /**
46
60
  * Exact test of a simple null hypothesis about the probability of success in Bernoulli trials. Equivalent to R's
@@ -59,6 +73,8 @@ function twoSidedP(x, n, p) {
59
73
  * @category Hypothesis tests
60
74
  */
61
75
  export function binomTest(x, n, options = {}) {
76
+ checkOptions(n, BINOM_TEST_KEYS, "binomTest"); // generated: option-keys.mjs
77
+ checkOptions(options, BINOM_TEST_KEYS, "binomTest"); // generated: option-keys.mjs
62
78
  let xs;
63
79
  let ns;
64
80
  if (typeof x !== "number") {
@@ -70,6 +86,10 @@ export function binomTest(x, n, options = {}) {
70
86
  throw new RangeError("'x' must be nonnegative and integer");
71
87
  xs = Math.round(x[0]);
72
88
  ns = Math.round(x[0]) + Math.round(x[1]);
89
+ // no trials: neither the estimate nor the test is defined (R returns a p-value of 1), as for binomTest(0, 0)
90
+ // no trials, or a total that overflows (binomTest([1e308, 1e308]) gave NaN; a scalar n = Infinity is rejected too)
91
+ if (ns === 0 || ns === Infinity)
92
+ throw new RangeError("'n' must be a positive integer >= 'x'");
73
93
  }
74
94
  else {
75
95
  if (typeof n !== "number")
@@ -81,6 +101,13 @@ export function binomTest(x, n, options = {}) {
81
101
  throw new RangeError("'n' must be a positive integer >= 'x'");
82
102
  ns = Math.round(n);
83
103
  }
104
+ return binomTestCounts(xs, ns, options);
105
+ }
106
+ /**
107
+ * The exact binomial test of xs successes in ns trials, without the check of ns > 0 (poissonTest compares two counts
108
+ * of 0 as R does: p-value 1, interval [0, 1])
109
+ */
110
+ export function binomTestCounts(xs, ns, options = {}) {
84
111
  const p = options.p ?? 0.5;
85
112
  if (!(p >= 0 && p <= 1))
86
113
  throw new RangeError("'p' must be a single number between 0 and 1");
@@ -91,11 +118,13 @@ export function binomTest(x, n, options = {}) {
91
118
  if (alternative === "less")
92
119
  pValue = pbinom1(xs, ns, p, true, false);
93
120
  else if (alternative === "greater")
94
- pValue = pbinom1(xs - 1, ns, p, false, false);
121
+ pValue = atLeast(xs, ns, p);
95
122
  else
96
123
  pValue = twoSidedP(xs, ns, p);
97
124
  const lower = (alpha) => (xs === 0 ? 0 : qbeta1(alpha, xs, ns - xs + 1, true, false));
98
- const upper = (alpha) => (xs === ns ? 1 : qbeta1(1 - alpha, xs + 1, ns - xs, true, false));
125
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits, and is 1 below 1.1e-16, which gave
126
+ // the limit 1 at confLevel = 0.9999999999999999)
127
+ const upper = (alpha) => xs === ns ? 1 : alpha < 1e-8 ? qbeta1(alpha, xs + 1, ns - xs, false, false) : qbeta1(1 - alpha, xs + 1, ns - xs, true, false);
99
128
  let confInt;
100
129
  if (alternative === "less")
101
130
  confInt = [0, upper(1 - confLevel)];
@@ -119,5 +148,6 @@ export function binomTest(x, n, options = {}) {
119
148
  estimateNames: "probability of success",
120
149
  nullValue: p,
121
150
  nullValueName: "probability of success",
151
+ warnings: [],
122
152
  };
123
153
  }
@@ -17,9 +17,10 @@ export interface BrunnerMunzelTestOptions {
17
17
  * Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
18
18
  * variances or shapes. Equivalent to `lawstat::brunner.munzel.test()` in R. `NaN` values are dropped.
19
19
  *
20
- * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). When a
21
- * sample has one value, or when the variance estimates are 0 (for example completely separated samples), the
22
- * statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in lawstat.
20
+ * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). Each
21
+ * sample needs at least 2 values (lawstat returns NaN for a sample of one). When the variance estimates are 0 (for
22
+ * example completely separated samples), the statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
23
+ * lawstat.
23
24
  *
24
25
  * @example
25
26
  * ```ts
@@ -14,13 +14,17 @@
14
14
  import { pt1, qt1 } from "../distributions/t.js";
15
15
  import { rank } from "../internal/summary.js";
16
16
  import { checkConfLevel, matchAlternative } from "./types.js";
17
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
18
+ import { checkOptions } from "../internal/checkOptions.js";
19
+ const BRUNNER_MUNZEL_TEST_KEYS = ["alternative", "confLevel"];
17
20
  /**
18
21
  * Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
19
22
  * variances or shapes. Equivalent to `lawstat::brunner.munzel.test()` in R. `NaN` values are dropped.
20
23
  *
21
- * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). When a
22
- * sample has one value, or when the variance estimates are 0 (for example completely separated samples), the
23
- * statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in lawstat.
24
+ * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). Each
25
+ * sample needs at least 2 values (lawstat returns NaN for a sample of one). When the variance estimates are 0 (for
26
+ * example completely separated samples), the statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
27
+ * lawstat.
24
28
  *
25
29
  * @example
26
30
  * ```ts
@@ -33,13 +37,15 @@ import { checkConfLevel, matchAlternative } from "./types.js";
33
37
  * @category Hypothesis tests
34
38
  */
35
39
  export function brunnerMunzelTest(x, y, options = {}) {
40
+ checkOptions(options, BRUNNER_MUNZEL_TEST_KEYS, "brunnerMunzelTest"); // generated: option-keys.mjs
36
41
  const xs = Array.from(x).filter((v) => !Number.isNaN(v));
37
42
  const ys = Array.from(y).filter((v) => !Number.isNaN(v));
38
43
  const n1 = xs.length;
39
44
  const n2 = ys.length;
40
- if (n1 < 1)
45
+ // S_i^2 divides by n_i - 1 (lawstat returns NaN for a sample of one)
46
+ if (n1 < 2)
41
47
  throw new RangeError("not enough 'x' observations");
42
- if (n2 < 1)
48
+ if (n2 < 2)
43
49
  throw new RangeError("not enough 'y' observations");
44
50
  const alternative = matchAlternative(options.alternative);
45
51
  const confLevel = options.confLevel ?? 0.95;
@@ -84,5 +90,6 @@ export function brunnerMunzelTest(x, y, options = {}) {
84
90
  confLevel,
85
91
  estimate,
86
92
  estimateNames: "P(X<Y)+.5*P(X=Y)",
93
+ warnings: [],
87
94
  };
88
95
  }
@@ -36,7 +36,8 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
36
36
  /**
37
37
  * Standardized residuals `(O - E) / sqrt(V)`, where `V` is
38
38
  * `E (1 - row proportion) (1 - column proportion)` for a contingency table and
39
- * `n p (1 - p)` for goodness of fit.
39
+ * `n p (1 - p)` for goodness of fit. For a contingency table the complements are the other rows' and columns'
40
+ * sums over the total, and the residual and `V` are computed in double-double.
40
41
  */
41
42
  stdres: number[] | number[][];
42
43
  }
@@ -77,7 +78,9 @@ export type Factor = readonly (string | null | undefined)[];
77
78
  * Given two factor vectors (arrays of labels of the same length), tests independence in their contingency table, as
78
79
  * R's `chisq.test(x, y)`; pairs with a missing label are dropped and the levels are sorted by code point.
79
80
  *
80
- * R's warning for expected counts below 5 is not issued.
81
+ * As R, `warnings` has "Chi-squared approximation may be incorrect" where an expected count is below 5 (unless the
82
+ * p-value is simulated), and "cannot compute simulated p-value with zero marginals" where `simulatePValue` is asked for
83
+ * a table with a zero row or column sum (the ordinary test is done).
81
84
  *
82
85
  * @param x Counts, or a contingency table as an array of rows (or a factor, with `y`).
83
86
  * @param options See {@link ChisqTestOptions}.