@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
@@ -10,11 +10,20 @@ import { cor, cov } from "../descriptive/cov.js";
10
10
  import { pf1, qf1 } from "../distributions/f.js";
11
11
  import { pnorm } from "../distributions/normal.js";
12
12
  import { numberLevels } from "../internal/levels.js";
13
- import { mean, sum, variance } from "../internal/summary.js";
13
+ import { mean, satterthwaiteDf, scaleToUnit, sum, variance } from "../internal/summary.js";
14
+ import { eigen } from "../linalg/eigen.js";
14
15
  import { solve } from "../linalg/solve.js";
16
+ import { qr, qrResid } from "../linalg/qr.js";
17
+ import { ddAdd, ddDivNum, ddMul, ddSub } from "../special/dd.js";
15
18
  import { formatR } from "./core/simulate.js";
16
19
  import { matchChoice } from "./power.js";
17
20
  import { checkConfLevelOpen } from "./types.js";
21
+ import { reported } from "../internal/warnings.js";
22
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
23
+ import { checkOptions } from "../internal/checkOptions.js";
24
+ const KAPPA2_KEYS = ["weight"];
25
+ const KAPPAM_FLEISS_KEYS = ["exact"];
26
+ const ICC_KEYS = ["model", "type", "unit", "r0", "confLevel"];
18
27
  /** Columns of a matrix given as an array of rows, after checking that it is rectangular */
19
28
  function columnsOf(x, what) {
20
29
  const k = x[0]?.length ?? 0;
@@ -25,6 +34,8 @@ function columnsOf(x, what) {
25
34
  function requireComplete(x, what) {
26
35
  if (x.some((r) => r.some(Number.isNaN)))
27
36
  throw new RangeError(`'${what}' contains missing values`);
37
+ if (x.some((r) => r.some((v) => !Number.isFinite(v))))
38
+ throw new RangeError(`'${what}' contains infinite values`);
28
39
  }
29
40
  /** Two-sided normal p-value 2 Φ(−|z|) */
30
41
  const twoSidedP = (z) => 2 * pnorm(-Math.abs(z));
@@ -37,7 +48,8 @@ const twoSidedP = (z) => 2 * pnorm(-Math.abs(z));
37
48
  * the one under the null hypothesis; the p-value is computed as 2 Φ(−|z|), so small p-values are more accurate than
38
49
  * irr's.
39
50
  *
40
- * @param ratings - An n × 2 matrix (array of rows): the ratings of the two raters for each subject.
51
+ * @param ratings - An n × 2 matrix (array of rows): the ratings of the two raters for each subject, with at least 2
52
+ * complete rows.
41
53
  * @param options - See {@link Kappa2Options}.
42
54
  *
43
55
  * @example
@@ -48,11 +60,17 @@ const twoSidedP = (z) => 2 * pnorm(-Math.abs(z));
48
60
  * @category Agreement, reliability and factor analysis
49
61
  */
50
62
  export function kappa2(ratings, options = {}) {
63
+ checkOptions(options, KAPPA2_KEYS, "kappa2"); // generated: option-keys.mjs
51
64
  const weight = matchChoice(options.weight, ["unweighted", "equal", "squared"]);
52
65
  if (ratings.some((r) => r.length !== 2))
53
66
  throw new TypeError("'ratings' must be a matrix with two columns");
54
67
  const rows = ratings.filter((r) => !r.some(Number.isNaN));
55
68
  const n = rows.length;
69
+ if (n === 0)
70
+ throw new RangeError("no complete rating pairs");
71
+ // the variance of kappa is 0 / 0 with one subject (irr returns z and p NaN)
72
+ if (n < 2)
73
+ throw new RangeError("at least 2 complete rating pairs are needed");
56
74
  const first = rows.map((r) => formatR(r[0]));
57
75
  const second = rows.map((r) => formatR(r[1]));
58
76
  // the levels of both raters together, sorted as strings (by code point, as in R's C locale)
@@ -80,7 +98,7 @@ export function kappa2(ratings, options = {}) {
80
98
  const v = Array.from({ length: c }, (_, s) => sum(a.map((ar, r) => ar * W[r][s])));
81
99
  const variance0 = (terms((r, s) => a[r] * b[s] * (W[r][s] - (u[r] + v[s])) ** 2) - pe * pe) / (n * (1 - pe) ** 2);
82
100
  const statistic = value / Math.sqrt(variance0);
83
- return { value, statistic, pValue: twoSidedP(statistic) };
101
+ return { value, statistic, pValue: twoSidedP(statistic), warnings: [] };
84
102
  }
85
103
  /**
86
104
  * Fleiss' kappa for several raters (or Conger's exact kappa), with the z test of kappa = 0 for Fleiss' kappa.
@@ -99,11 +117,14 @@ export function kappa2(ratings, options = {}) {
99
117
  * @category Agreement, reliability and factor analysis
100
118
  */
101
119
  export function kappamFleiss(ratings, options = {}) {
120
+ checkOptions(options, KAPPAM_FLEISS_KEYS, "kappamFleiss"); // generated: option-keys.mjs
102
121
  const exact = options.exact ?? false;
103
122
  const cols = columnsOf(ratings, "ratings");
104
123
  requireComplete(ratings, "ratings");
105
124
  const n = ratings.length;
106
125
  const m = cols.length;
126
+ if (n < 2 || m < 2)
127
+ throw new RangeError("at least 2 subjects and 2 raters are needed");
107
128
  // (the categories as R's factor() makes them: numbers with the same 15-digit text are one category)
108
129
  const flat = ratings.flat();
109
130
  const levelOf = numberLevels(flat);
@@ -133,12 +154,12 @@ export function kappamFleiss(ratings, options = {}) {
133
154
  }
134
155
  const value = (po - pe) / (1 - pe);
135
156
  if (exact)
136
- return { value };
157
+ return { value, warnings: [] };
137
158
  const pq = sum(p.map((pj) => pj * (1 - pj)));
138
159
  const skew = sum(p.map((pj) => pj * (1 - pj) * (1 - pj - pj)));
139
160
  const variance0 = (2 / (pq * pq * n * m * (m - 1))) * (pq * pq - skew);
140
161
  const statistic = value / Math.sqrt(variance0);
141
- return { value, statistic, pValue: twoSidedP(statistic) };
162
+ return { value, statistic, pValue: twoSidedP(statistic), warnings: [] };
142
163
  }
143
164
  /**
144
165
  * Intraclass correlation coefficient with its F test and confidence interval (McGraw and Wong's forms).
@@ -156,25 +177,39 @@ export function kappamFleiss(ratings, options = {}) {
156
177
  * @category Agreement, reliability and factor analysis
157
178
  */
158
179
  export function icc(ratings, options = {}) {
180
+ checkOptions(options, ICC_KEYS, "icc"); // generated: option-keys.mjs
159
181
  const model = matchChoice(options.model, ["oneway", "twoway"]);
160
182
  const type = matchChoice(options.type, ["consistency", "agreement"]);
161
183
  const unit = matchChoice(options.unit, ["single", "average"]);
162
184
  const r0 = options.r0 ?? 0;
163
185
  const confLevel = options.confLevel ?? 0.95;
164
186
  checkConfLevelOpen(confLevel);
165
- const cols = columnsOf(ratings, "ratings");
187
+ columnsOf(ratings, "ratings");
166
188
  requireComplete(ratings, "ratings");
167
- const n = ratings.length;
189
+ // the ratings scaled by one power of 2 (exact), so that the mean squares stay in range; the ICC, F and bounds do
190
+ // not depend on the units
191
+ const rows = scaleToUnit(ratings).groups;
192
+ const cols = columnsOf(rows, "ratings");
193
+ const n = rows.length;
168
194
  const k = cols.length;
195
+ if (n < 2 || k < 2)
196
+ throw new RangeError("at least 2 subjects and 2 raters are needed");
197
+ if (!(r0 >= -1 && r0 < 1))
198
+ throw new RangeError("'r0' must be in [-1, 1)");
169
199
  const alpha = 1 - confLevel;
170
200
  // mean squares from sample variances
171
- const msr = variance(ratings.map((r) => mean(r))) * k;
201
+ const msr = variance(rows.map((r) => mean(r))) * k;
172
202
  const msc = variance(cols.map((c) => mean(c))) * n;
173
- const msw = mean(ratings.map((r) => variance(r)));
174
- const ssTotal = variance(ratings.flat()) * (n * k - 1);
175
- const mse = (ssTotal - msr * (n - 1) - msc * (k - 1)) / ((n - 1) * (k - 1));
203
+ const msw = mean(rows.map((r) => variance(r)));
204
+ const ssTotal = variance(rows.flat()) * (n * k - 1);
205
+ // the residual sum of squares by subtraction; where it cancels to below 2^-20 of the total (or to 0 or less) it
206
+ // is formed directly from the residuals in double-double (#392: subject and rater effects of 1e8 with an
207
+ // interaction of 1 gave mse 0, ICC 1 and F Infinity)
208
+ const ssE = ssTotal - msr * (n - 1) - msc * (k - 1);
209
+ const mse = ssE > 2 ** -20 * ssTotal ? ssE / ((n - 1) * (k - 1)) : residualSumOfSquares(rows) / ((n - 1) * (k - 1));
176
210
  const upper = (F, d1, d2) => pf1(F, d1, d2, false, false);
177
- const q = (d1, d2) => qf1(1 - alpha / 2, d1, d2, true, false);
211
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
212
+ const q = (d1, d2) => alpha / 2 < 1e-8 ? qf1(alpha / 2, d1, d2, false, false) : qf1(1 - alpha / 2, d1, d2, true, false);
178
213
  const df1 = n - 1;
179
214
  if (model === "oneway" || type === "consistency") {
180
215
  const ms = model === "oneway" ? msw : mse;
@@ -185,12 +220,12 @@ export function icc(ratings, options = {}) {
185
220
  const [value, Fvalue, bound] = unit === "single"
186
221
  ? [(msr - ms) / (msr + (k - 1) * ms), (ratio * (1 - r0)) / (1 + (k - 1) * r0), (f) => (f - 1) / (f + k - 1)]
187
222
  : [(msr - ms) / msr, ratio * (1 - r0), (f) => 1 - 1 / f];
188
- return { value, Fvalue, df1, df2, pValue: upper(Fvalue, df1, df2), lbound: bound(FL), ubound: bound(FU) };
223
+ return { value, Fvalue, fValue: Fvalue, df1, df2, pValue: upper(Fvalue, df1, df2), lbound: bound(FL), ubound: bound(FU), warnings: [] };
189
224
  }
190
225
  // two-way agreement: Satterthwaite's degrees of freedom v for the combination a MSc + b MSe
191
226
  const scale = unit === "single" ? k : 1;
192
227
  const coefficients = (r) => [(scale * r) / (n * (1 - r)), 1 + (scale * r * (n - 1)) / (n * (1 - r))];
193
- const dfOf = (a, b) => (a * msc + b * mse) ** 2 / ((a * msc) ** 2 / (k - 1) + (b * mse) ** 2 / ((n - 1) * (k - 1)));
228
+ const dfOf = (a, b) => satterthwaiteDf([a * msc, b * mse], [k - 1, (n - 1) * (k - 1)]);
194
229
  const value = unit === "single" ? (msr - mse) / (msr + (k - 1) * mse + (k / n) * (msc - mse)) : (msr - mse) / (msr + (msc - mse) / n);
195
230
  const [a0, b0] = coefficients(r0);
196
231
  const Fvalue = msr / (a0 * msc + b0 * mse);
@@ -206,7 +241,7 @@ export function icc(ratings, options = {}) {
206
241
  (n * (FU * msr - mse)) / (k * msc + (k * n - k - n) * mse + n * FU * msr),
207
242
  ]
208
243
  : [(n * (msr - FL * mse)) / (FL * (msc - mse) + n * msr), (n * (FU * msr - mse)) / (msc - mse + n * FU * msr)];
209
- return { value, Fvalue, df1, df2, pValue: upper(Fvalue, df1, df2), lbound, ubound };
244
+ return { value, Fvalue, fValue: Fvalue, df1, df2, pValue: upper(Fvalue, df1, df2), lbound, ubound, warnings: [] };
210
245
  }
211
246
  /** Raw alpha of the covariance matrix C restricted to the items `keep` */
212
247
  function rawAlphaOf(C, keep) {
@@ -220,7 +255,12 @@ function rawAlphaOf(C, keep) {
220
255
  * and alpha with each item dropped. Equivalent to `psych::alpha()` in R. It gives the `total` row and
221
256
  * `alpha.drop$raw_alpha` of `alpha(x)` with its defaults (no missing values, no reversed items).
222
257
  *
223
- * @param x - An n × k matrix (array of rows): k items observed on n subjects.
258
+ * As psych, `warnings` has "Item = had no variance and was deleted but still is counted in the score" for a constant
259
+ * item (an unnamed matrix's column has no name) and "Some items were negatively correlated with the first principal
260
+ * component and probably should be reversed. ..." (with psych's line breaks) where a loading of the first principal
261
+ * component of the correlations is negative. The warnings of the functions psych calls are not included.
262
+ *
263
+ * @param x - An n × k matrix (array of rows): k ≥ 2 items observed on n ≥ 2 subjects.
224
264
  *
225
265
  * @example
226
266
  * ```ts
@@ -234,19 +274,65 @@ export function cronbachAlpha(x) {
234
274
  requireComplete(x, "x");
235
275
  if (k < 2)
236
276
  throw new RangeError("'x' needs at least two items");
237
- const C = cov(x);
277
+ // the sample covariances divide by n - 1
278
+ if (x.length < 2)
279
+ throw new RangeError("'x' needs at least two subjects");
280
+ // the covariances of the data scaled by one power of 2 (exact): raw alpha is a ratio of them
281
+ const C = cov(scaleToUnit(x).groups);
238
282
  const R = cor(x);
239
283
  const items = Array.from({ length: k }, (_, i) => i);
240
284
  const sumR = sum(R.flat());
241
- const Rinv = solve(R);
242
- const smc = items.map((i) => 1 - 1 / Rinv[i][i]);
243
- return {
285
+ let smc;
286
+ try {
287
+ const Rinv = solve(R);
288
+ smc = items.map((i) => 1 - 1 / Rinv[i][i]);
289
+ }
290
+ catch (e) {
291
+ if (!R.flat().every(Number.isFinite))
292
+ throw e;
293
+ // A singular correlation matrix (a repeated item, an item that is the sum of others, or at least as many items as
294
+ // subjects): the SMC of item i is still the R^2 of lm(x_i ~ x_-i), here with R's QR (limited pivoting, tol 1e-7) on
295
+ // the data scaled by one power of 2. [[1, 1], [2, 2], [3, 3]] threw "exactly singular" (issue #468); psych's
296
+ // pseudo-inverse gives such items an SMC of 0 (G6 0.5), the R^2 is 1 (G6 1)
297
+ const xs = scaleToUnit(x).groups;
298
+ smc = items.map((i) => {
299
+ const y = xs.map((r) => r[i]);
300
+ const res = qrResid(qr(xs.map((r) => [1, ...r.filter((_, j) => j !== i)])), y);
301
+ const m = mean(y);
302
+ return 1 - sum(res.map((v) => v * v)) / sum(y.map((v) => (v - m) ** 2));
303
+ });
304
+ }
305
+ return reported("cronbachAlpha", {
244
306
  rawAlpha: rawAlphaOf(C, items),
245
307
  stdAlpha: ((1 - k / sumR) * k) / (k - 1),
246
308
  G6: 1 - (k - sum(smc)) / sumR,
247
309
  averageR: (sumR - k) / (k * (k - 1)),
248
310
  alphaDrop: items.map((i) => rawAlphaOf(C, items.filter((j) => j !== i))),
249
- };
311
+ warnings: alphaWarnings(x, R),
312
+ });
313
+ }
314
+ /**
315
+ * psych::alpha's own warnings (not those of the functions it calls): "Item = <name> had no variance and was deleted
316
+ * but still is counted in the score" for a constant item (the name of an unnamed matrix's column is empty), and
317
+ * "Some items were negatively correlated with the first principal component ..." where the loadings of the first
318
+ * principal component of the correlations of the other items (psych::principal: the eigenvector of the largest
319
+ * eigenvalue, signed so that its sum is not negative) are not all >= 0
320
+ */
321
+ function alphaWarnings(x, R) {
322
+ const warnings = [];
323
+ const keep = R.map((_, j) => j).filter((j) => x.some((r) => r[j] !== x[0][j]));
324
+ if (keep.length < R.length)
325
+ warnings.push("Item = had no variance and was deleted but still is counted in the score");
326
+ // one item left has the loading 1 (psych stops after it)
327
+ if (keep.length >= 2) {
328
+ const { vectors } = eigen(keep.map((i) => keep.map((j) => R[i][j])), { symmetric: true });
329
+ const first = vectors.map((r) => r[0]);
330
+ const sign = sum(first) < 0 ? -1 : 1;
331
+ if (first.some((v) => sign * v < 0)) {
332
+ warnings.push("Some items were negatively correlated with the first principal component and probably \nshould be reversed. \nTo do this, run the function again with the 'check.keys=TRUE' option");
333
+ }
334
+ }
335
+ return warnings;
250
336
  }
251
337
  /**
252
338
  * Partial correlation of columns `i` and `j` of `x` given all its other columns. Equivalent to
@@ -287,3 +373,18 @@ export function partialR(x, i, j) {
287
373
  }
288
374
  return P[0][1] / Math.sqrt(P[0][0] * P[1][1]);
289
375
  }
376
+ /** The residual sum of squares of the two-way layout, sum (x - row mean - column mean + grand mean)^2, in double-double */
377
+ function residualSumOfSquares(rows) {
378
+ const n = rows.length;
379
+ const k = rows[0].length;
380
+ const sumDD = (v) => v.reduce((a, x) => ddAdd(a, [x, 0]), [0, 0]);
381
+ const rm = rows.map((r) => ddDivNum(sumDD(r), k));
382
+ const cm = rows[0].map((_, j) => ddDivNum(sumDD(rows.map((r) => r[j])), n));
383
+ const gm = ddDivNum(sumDD(rows.flat()), n * k);
384
+ let ss = [0, 0];
385
+ rows.forEach((r, i) => r.forEach((x, j) => {
386
+ const e = ddAdd(ddSub(ddSub([x, 0], rm[i]), cm[j]), gm);
387
+ ss = ddAdd(ss, ddMul(e, e));
388
+ }));
389
+ return ss[0] + ss[1];
390
+ }
@@ -8,7 +8,12 @@ import { type Alternative, type HTest, type Sample } from "./types.js";
8
8
  export interface AnsariTestOptions {
9
9
  /** Alternative hypothesis (unambiguous abbreviations accepted). Default `"two.sided"`. */
10
10
  alternative?: Alternative | "two" | "l" | "g";
11
- /** Exact p-value. Default: exact when both samples have fewer than 50 values and there are no ties. */
11
+ /**
12
+ * Exact p-value. Default: exact when both samples have fewer than 50 values and there are no ties. The exact
13
+ * distribution keeps 2 (m + 1) (floor((m + n + 1)^2 / 4) + 1) doubles and makes m + n passes over half of them;
14
+ * beyond 2^24 doubles or 2^32 steps (m = n = 203, or m = 1 and n = 2047) it is a RangeError (R computes it however
15
+ * large).
16
+ */
12
17
  exact?: boolean;
13
18
  /** Compute a confidence interval for the ratio of scales and its estimate (R's `conf.int`). Default `false`. */
14
19
  confInt?: boolean;
@@ -23,7 +28,8 @@ export interface AnsariTestOptions {
23
28
  * estimate, both computed with the locations taken as 0 (exact without ties when both samples have fewer than 50
24
29
  * values, otherwise by the normal approximation, whose limits are roots found to a tolerance of 1e-4 as in R). Limits
25
30
  * that cannot be formed (the samples differ in location) are `NaN`. With ties and `exact` unset or `true`, R fails
26
- * ("object 'cint' not found"); rStats.js returns the normal-approximation interval, as with `exact: false`.
31
+ * ("object 'cint' not found"); rStats.js returns the normal-approximation interval, as with `exact: false`, and the
32
+ * warnings R gives before it stops.
27
33
  *
28
34
  * @example
29
35
  * ```ts
@@ -17,12 +17,18 @@
17
17
  // values and of the negative values. The candidate sets, evaluation points, search range, tolerance and the cases
18
18
  // returned as NaN (R's NA) follow R's documented and observed behaviour.
19
19
  import { pnorm, qnorm } from "../distributions/normal.js";
20
- import { rank } from "../internal/summary.js";
20
+ import { ldexp, rank } from "../internal/summary.js";
21
21
  import { uniroot } from "../internal/uniroot.js";
22
- import { pansariExact, qansariR } from "./core/ansari.js";
22
+ import { reported, Warnings } from "../internal/warnings.js";
23
+ import { checkAnsariExactSize, pansariExact, qansariR } from "./core/ansari.js";
23
24
  import { twoGroupData } from "./testFormula.js";
24
25
  import { checkConfLevelOpen, matchAlternative } from "./types.js";
26
+ import { maxOf, minOf } from "../internal/extremes.js";
27
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
28
+ import { checkOptions } from "../internal/checkOptions.js";
29
+ const ANSARI_TEST_KEYS = ["alternative", "exact", "confInt", "confLevel"];
25
30
  export function ansariTest(x, y, options = {}) {
31
+ checkOptions(options, ANSARI_TEST_KEYS, "ansariTest"); // generated: option-keys.mjs
26
32
  if (typeof x === "string") {
27
33
  const d = twoGroupData(x, y);
28
34
  return ansariTest(d.x, d.y, options);
@@ -48,9 +54,15 @@ export function ansariTest(x, y, options = {}) {
48
54
  statistic += a[i];
49
55
  const ties = new Set(r).size < N;
50
56
  const exact = options.exact ?? (m < 50 && n < 50 && !ties);
57
+ // R's exact, which does not look at the ties: with ties it takes the normal approximation, warns, and computes no
58
+ // interval (it then stops, "object 'cint' not found")
59
+ const exactR = options.exact ?? (m < 50 && n < 50);
60
+ const warnings = new Warnings();
51
61
  let pValue;
52
62
  let ci;
53
63
  if (exact && !ties) {
64
+ // (the exact distribution grows like m (m + n)^3: a RangeError before it is built when too large, #308)
65
+ checkAnsariExactSize(m, n);
54
66
  const upperFrom = (q) => pansariExact(q - 1, m, n, false); // P(AB >= q)
55
67
  const lowerTo = (q) => pansariExact(q, m, n, true); // P(AB <= q)
56
68
  if (alternative === "two.sided") {
@@ -64,7 +76,7 @@ export function ansariTest(x, y, options = {}) {
64
76
  else
65
77
  pValue = lowerTo(statistic);
66
78
  if (confInt)
67
- ci = exactInterval(xs, ys, alternative, confLevel);
79
+ ci = exactInterval(xs, ys, alternative, confLevel, warnings);
68
80
  }
69
81
  else {
70
82
  // mean and variance with the sum of the scores at its value without ties (N (N + 2) / 4 for even N,
@@ -85,8 +97,14 @@ export function ansariTest(x, y, options = {}) {
85
97
  : alternative === "less"
86
98
  ? pnorm(z, { lowerTail: false })
87
99
  : pnorm(z);
100
+ // (the interval R does not compute, with ties and exactR, gives none of its warnings)
88
101
  if (confInt)
89
- ci = normalInterval(xs, ys, alternative, confLevel);
102
+ ci = normalInterval(xs, ys, alternative, confLevel, exactR ? new Warnings() : warnings);
103
+ if (exactR && ties) {
104
+ warnings.add("cannot compute exact p-value with ties");
105
+ if (confInt)
106
+ warnings.add("cannot compute exact confidence intervals with ties");
107
+ }
90
108
  }
91
109
  const result = {
92
110
  method: "Ansari-Bradley test",
@@ -94,6 +112,7 @@ export function ansariTest(x, y, options = {}) {
94
112
  statistic,
95
113
  statisticName: "AB",
96
114
  pValue,
115
+ warnings: warnings.list,
97
116
  };
98
117
  if (ci !== undefined) {
99
118
  result.confInt = ci.confInt;
@@ -103,19 +122,74 @@ export function ansariTest(x, y, options = {}) {
103
122
  }
104
123
  result.nullValue = 1;
105
124
  result.nullValueName = "ratio of scales";
106
- return result;
125
+ return reported("ansariTest", result);
107
126
  }
108
127
  /** AB statistic of x / s against y, with the scores of all observations and whether there are ties */
109
128
  function scaledStatistic(xs, ys, s) {
110
129
  const m = xs.length;
111
130
  const N = m + ys.length;
112
- const r = rankNaNLast(xs.map((v) => v / s).concat(ys));
131
+ const q = xs.map((v) => v / s);
132
+ // x / s can overflow to Infinity or fall below the normal range (to 0) for a finite s, tying distinct observations
133
+ // (R's ansari.test does the same): only there rank by a comparison of x / s that keeps the order (#507)
134
+ const lossy = s > 0 && s < Infinity && q.some((v, i) => Number.isFinite(xs[i]) && (!Number.isFinite(v) || (xs[i] !== 0 && Math.abs(v) < MIN_NORMAL)));
135
+ const r = lossy ? orderedRanks(xs.map((v) => key(v, s)).concat(ys.map((v) => key(v, 1)))) : rankNaNLast(q.concat(ys));
113
136
  const a = r.map((v) => Math.min(v, N - v + 1));
114
137
  let ab = 0;
115
138
  for (let i = 0; i < m; i++)
116
139
  ab += a[i];
117
140
  return { ab, a, ties: new Set(r).size < N };
118
141
  }
142
+ const MIN_NORMAL = 2 ** -1022;
143
+ function key(v, d) {
144
+ if (v === 0)
145
+ return [0, 0, 0];
146
+ const sign = v > 0 ? 1 : -1;
147
+ if (!Number.isFinite(v))
148
+ return [sign, Infinity, 1];
149
+ const [ev, mv] = split(Math.abs(v));
150
+ const [ed, md] = split(d);
151
+ let m = mv / md;
152
+ let e = ev - ed;
153
+ if (m < 1) {
154
+ m *= 2;
155
+ e -= 1;
156
+ }
157
+ return [sign, e, m];
158
+ }
159
+ /** [e, m] with a = m 2^e, m in [1, 2), for a finite positive a */
160
+ function split(a) {
161
+ let e = Math.floor(Math.log2(a));
162
+ let m = ldexp(a, -e);
163
+ if (m >= 2) {
164
+ m /= 2;
165
+ e += 1;
166
+ }
167
+ else if (m < 1) {
168
+ m *= 2;
169
+ e -= 1;
170
+ }
171
+ return [e, m];
172
+ }
173
+ function compareKeys(a, b) {
174
+ if (a[0] !== b[0])
175
+ return a[0] - b[0];
176
+ const c = a[1] !== b[1] ? a[1] - b[1] : a[2] - b[2];
177
+ return a[0] * c;
178
+ }
179
+ /** Average ranks of the keys */
180
+ function orderedRanks(keys) {
181
+ const idx = keys.map((_, i) => i).sort((i, j) => compareKeys(keys[i], keys[j]));
182
+ const r = new Array(keys.length);
183
+ for (let lo = 0; lo < idx.length;) {
184
+ let hi = lo + 1;
185
+ while (hi < idx.length && compareKeys(keys[idx[lo]], keys[idx[hi]]) === 0)
186
+ hi++;
187
+ for (let k = lo; k < hi; k++)
188
+ r[idx[k]] = (lo + 1 + hi) / 2;
189
+ lo = hi;
190
+ }
191
+ return r;
192
+ }
119
193
  /** Average ranks with NaN (0 / 0 at s = 0) ranked last in order of appearance, as R's rank(na.last = TRUE) */
120
194
  function rankNaNLast(v) {
121
195
  const keep = v.filter((e) => !Number.isNaN(e));
@@ -135,7 +209,7 @@ function shapeInterval(alternative, a, limits) {
135
209
  return [0, limits(2 * a)[1]];
136
210
  }
137
211
  /** Exact interval and estimate from the candidate ratios x_i / y_j >= 0 */
138
- function exactInterval(xs, ys, alternative, confLevel) {
212
+ function exactInterval(xs, ys, alternative, confLevel, warnings) {
139
213
  const m = xs.length;
140
214
  const n = ys.length;
141
215
  const sigma = [];
@@ -145,8 +219,11 @@ function exactInterval(xs, ys, alternative, confLevel) {
145
219
  sigma.push(x / y);
146
220
  sigma.sort((p, q) => p - q);
147
221
  const L = sigma.length;
148
- if (L === 0)
222
+ // (R then stops: "object 'absigma' not found")
223
+ if (L === 0) {
224
+ warnings.add("cannot compute confidence set, returning NA");
149
225
  return { confInt: shapeInterval(alternative, 1 - confLevel, () => [NaN, NaN]), estimate: NaN };
226
+ }
150
227
  // AB between consecutive candidates, and at 2.01 times the largest
151
228
  const abs = sigma.map((v, k) => scaledStatistic(xs, ys, v + (k < L - 1 ? (sigma[k + 1] - v) / 2 : v * 1.01)).ab);
152
229
  // the largest candidate with the smallest positive AB - q (or the smallest with the smallest AB - q >= 0)
@@ -165,8 +242,10 @@ function exactInterval(xs, ys, alternative, confLevel) {
165
242
  const limits = (alpha) => {
166
243
  const qLow = qansariR(alpha / 2, m, n);
167
244
  const qHigh = qansariR(1 - alpha / 2, m, n);
168
- if (!abs.some((v) => v - qLow >= 0) || !abs.some((v) => v - qHigh > 0))
245
+ if (!abs.some((v) => v - qLow >= 0) || !abs.some((v) => v - qHigh > 0)) {
246
+ warnings.add("samples differ in location: cannot compute confidence set, returning NA");
169
247
  return [NaN, NaN];
248
+ }
170
249
  const lower = crossing(qLow, false, false);
171
250
  const upper = crossing(qHigh, true, true);
172
251
  // AB need not be monotone in s: if the limits come out in the wrong order, the quantiles are interchanged
@@ -184,11 +263,15 @@ function exactInterval(xs, ys, alternative, confLevel) {
184
263
  else
185
264
  above = Math.min(above, sigma[k]);
186
265
  });
187
- const estimate = below === -Infinity || above === Infinity ? NaN : (above + below) / 2;
266
+ // the midpoint as R's mean(c(u, l)); where the sum of two finite candidates overflows, from the halves (exact for
267
+ // them) (#209)
268
+ let estimate = below === -Infinity || above === Infinity ? NaN : (above + below) / 2;
269
+ if (estimate === Infinity)
270
+ estimate = above / 2 + below / 2;
188
271
  return { confInt, estimate };
189
272
  }
190
- /** Normal-approximation interval and estimate (undefined when the search range is not finite) */
191
- function normalInterval(xs, ys, alternative, confLevel) {
273
+ /** Normal-approximation interval and estimate (undefined when the search range is not finite, NaN when it is empty) */
274
+ function normalInterval(xs, ys, alternative, confLevel, warnings) {
192
275
  const m = xs.length;
193
276
  const n = ys.length;
194
277
  const N = m + n;
@@ -217,25 +300,40 @@ function normalInterval(xs, ys, alternative, confLevel) {
217
300
  const range = (xp, yp) => {
218
301
  if (xp.length === 0 || yp.length === 0)
219
302
  return;
220
- ends.push(Math.min(...xp) / Math.max(...yp), Math.max(...xp) / Math.min(...yp));
303
+ ends.push(minOf(xp) / maxOf(yp), maxOf(xp) / minOf(yp));
221
304
  };
222
305
  range(xs.filter((v) => v > 0), ys.filter((v) => v > 0));
223
306
  range(xs.filter((v) => v <= 0), ys.filter((v) => v < 0));
224
- if (ends.some((v) => !Number.isFinite(v)))
307
+ if (ends.some((v) => !Number.isFinite(v))) {
308
+ warnings.add("cannot compute asymptotic confidence set or estimator");
225
309
  return undefined;
226
- const lo = Math.min(...ends);
227
- const hi = Math.max(...ends);
310
+ }
311
+ // no positive ratio puts the samples across each other (all x positive and all y negative, or the reverse): the
312
+ // limits and the estimate cannot be formed, as in the exact path (R stops with "invalid 'xmin' value" after its
313
+ // "samples differ in location ... returning NA" warning) (#506). That warning is returned (not R's warnings of min and
314
+ // max of no values before it)
315
+ if (ends.length === 0) {
316
+ warnings.add("samples differ in location: cannot compute confidence set, returning NA");
317
+ return { confInt: shapeInterval(alternative, 1 - confLevel, () => [NaN, NaN]), estimate: NaN };
318
+ }
319
+ const lo = minOf(ends);
320
+ const hi = maxOf(ends);
228
321
  const root = (zq) => uniroot((s) => z(s, zq), lo, hi, { tol: 1e-4 });
229
322
  const limits = (alpha) => {
230
323
  const zLow = qnorm(alpha / 2);
231
324
  const zHigh = qnorm(alpha / 2, { lowerTail: false });
232
- if (z(lo, zLow) > 0 || z(hi, zHigh) < 0)
325
+ if (z(lo, zLow) > 0 || z(hi, zHigh) < 0) {
326
+ warnings.add("samples differ in location: cannot compute confidence set, returning NA");
233
327
  return [NaN, NaN];
328
+ }
234
329
  const u = root(zLow);
235
330
  const l = root(zHigh);
236
331
  return u <= l ? [u, l] : [l, u];
237
332
  };
238
333
  const confInt = shapeInterval(alternative, 1 - confLevel, limits);
239
- const estimate = z(lo, 0) > 0 || z(hi, 0) < 0 ? NaN : root(0);
334
+ const noEstimate = z(lo, 0) > 0 || z(hi, 0) < 0;
335
+ if (noEstimate)
336
+ warnings.add("cannot compute estimate, returning NA");
337
+ const estimate = noEstimate ? NaN : root(0);
240
338
  return { confInt, estimate };
241
339
  }
@@ -4,39 +4,28 @@ import type { DataFrame } from "../models/modelFrame.js";
4
4
  import { type GroupLabel } from "./groups.js";
5
5
  import { type Alternative, type HTest, type Sample } from "./types.js";
6
6
  /**
7
- * Result of {@link aov}: the one-way ANOVA table, rows "between groups" and "residuals".
7
+ * Analysis of variance. Equivalent to R's `aov()`. From samples, one way: the fit of the model `y ~ g` (as
8
+ * `aov("y ~ g", data)`), with the values in a column `y` and the groups as a factor `g`; {@link aovSummary} gives the
9
+ * table of R's `summary(aov(y ~ g))`.
8
10
  *
9
- * @category Linear models and ANOVA
10
- */
11
- export interface AovResult {
12
- /** Degrees of freedom `[k - 1, N - k]`. */
13
- df: [number, number];
14
- /** Sums of squares `[between, residual]`. */
15
- sumSq: [number, number];
16
- /** Mean squares `[between, residual]`. */
17
- meanSq: [number, number];
18
- /** F statistic. */
19
- fValue: number;
20
- /** p-value of the F test. */
21
- pValue: number;
22
- }
23
- /**
24
- * One-way analysis of variance. Equivalent to R's `aov()`. Gives the table of R's `summary(aov(y ~ g))` for one
25
- * factor.
11
+ * The levels of `g` are the group labels (sorted as R orders factor levels), or the positions of the samples in the
12
+ * list (from 1) for an array of samples, as in {@link TukeyHSD}. Missing values are left out, and a sample left empty
13
+ * has no level.
26
14
  *
27
15
  * @param x An array of samples (groups), or one sample with group labels `g`.
28
16
  * @param g Group labels, parallel to `x`.
29
17
  *
30
18
  * @example
31
19
  * ```ts
32
- * const r = aov([[2.9, 3.0, 2.5, 2.6, 3.2], [3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]);
33
- * r.fValue; // 0.56007326007326
34
- * r.pValue; // 0.586632991041738
20
+ * const fit = aov([[2.9, 3.0, 2.5, 2.6, 3.2], [3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]);
21
+ * const t = aovSummary(fit);
22
+ * t.rowNames; // ["g", "Residuals"]
23
+ * t.table[0]; // [2, 0.44678571428571, 0.22339285714286, 0.56007326007326, 0.58663299104174]
35
24
  * ```
36
25
  *
37
26
  * @category Linear models and ANOVA
38
27
  */
39
- export declare function aov(x: Sample | readonly Sample[], g?: readonly GroupLabel[]): AovResult;
28
+ export declare function aov(x: Sample | readonly Sample[], g?: readonly GroupLabel[]): LmFormulaResult;
40
29
  /**
41
30
  * Analysis of variance from a model formula, as R's `aov(formula, data)` (with `weights` and
42
31
  * `contrasts`): the same fit as {@link lm} with a formula; {@link aovSummary} gives the table of R's
@@ -53,13 +42,26 @@ export declare function aov(x: Sample | readonly Sample[], g?: readonly GroupLab
53
42
  * ```
54
43
  */
55
44
  export declare function aov(formula: string, data: DataFrame, options?: LmFormulaOptions): LmFormulaResult | AovStrataFit;
45
+ /** The one-way ANOVA table from groups (for leveneTest) */
46
+ export interface OnewayTable {
47
+ df: [number, number];
48
+ sumSq: [number, number];
49
+ meanSq: [number, number];
50
+ fValue: number;
51
+ pValue: number;
52
+ }
53
+ /**
54
+ * The one-way ANOVA table of groups: the sums of squares of groupMoments (double-double, on the data scaled by a
55
+ * power of 2), so that a within sum that is exactly 0 stays 0
56
+ */
57
+ export declare function onewayTable(groups: readonly (readonly number[])[]): OnewayTable;
56
58
  /**
57
59
  * Options for {@link TukeyHSD}.
58
60
  *
59
61
  * @category Multiple comparisons
60
62
  */
61
63
  export interface TukeyHSDOptions {
62
- /** Family-wise confidence level. Default `0.95`. */
64
+ /** Family-wise confidence level in [0, 1] (a RangeError otherwise). Default `0.95`. */
63
65
  confLevel?: number;
64
66
  }
65
67
  /**
@@ -85,6 +87,10 @@ export interface TukeyHSDResult {
85
87
  upr: number[];
86
88
  /** p-values adjusted for the multiple comparisons. */
87
89
  pAdj: number[];
90
+ /** Alias of `pAdj`: the same array. */
91
+ pAdjusted: number[];
92
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
93
+ warnings: string[];
88
94
  }
89
95
  /**
90
96
  * Tukey's honest significant differences between the group means of a one-way ANOVA (Tukey-Kramer for unequal