@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,22 +10,35 @@
10
10
  // of these matrices times (P'P)^-1, and the epsilons and Mauchly's W follow from P'EP (src/models/ddMatrix.ts).
11
11
  import { pf1 } from "../distributions/f.js";
12
12
  import { levelText, numberLevels } from "../internal/levels.js";
13
+ import { ldexp, scaleToUnit } from "../internal/summary.js";
14
+ import { chol } from "../linalg/chol.js";
13
15
  import { eigen } from "../linalg/eigen.js";
14
16
  import { qr } from "../linalg/qr.js";
15
17
  import { ddAdd, ddDiv, ddDivNum, ddMul, ddMulNum } from "../special/dd.js";
16
18
  import { Anova } from "./carAnova.js";
17
19
  import { ddLeastSquaresMulti } from "./ddLeastSquares.js";
18
- import { ddHi, ddInverse, ddMatMul, ddTrace } from "./ddMatrix.js";
20
+ import { ddHi, ddInverse, ddMatMul, ddTrace, ddTranspose } from "./ddMatrix.js";
19
21
  import { lm } from "./lm.js";
20
22
  import { mauchlyPValue, sphericityW } from "./mauchly.js";
21
23
  import { compareCodePoints } from "./modelFrame.js";
22
24
  import { modelMatrix } from "./modelMatrix.js";
25
+ import { scaledTables } from "./scaledTables.js";
26
+ import { reported, unreported } from "../internal/warnings.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 AOV_EZ_KEYS = ["id", "dv", "between", "within", "type", "correction", "es", "observed"];
23
30
  const list = (v) => (v === undefined ? [] : typeof v === "string" ? [v] : [...v]);
24
- const SQRT_EPS = Math.sqrt(2.220446049250313e-16);
31
+ /** Eigenvalues of the error SSP matrix below this fraction of the largest one count as 0 */
32
+ const REL_RANK_TOL = 1e-12;
33
+ /**
34
+ * Eigenvalues of the error SSP matrix below this fraction of the sum of squares of the wide data count as 0: the
35
+ * rounding of the data (relative 2^-53 of each value) alone makes eigenvalues near 1e-32 of it
36
+ */
37
+ const ABS_RANK_TOL = 1e-24;
25
38
  function column(data, name) {
26
39
  const c = Object.prototype.hasOwnProperty.call(data, name) ? data[name] : undefined;
27
40
  if (c === undefined)
28
- throw new Error(`object '${name}' not found`);
41
+ throw new RangeError(`object '${name}' not found`);
29
42
  return Array.from(c);
30
43
  }
31
44
  const label = (v) => (typeof v === "boolean" ? (v ? "TRUE" : "FALSE") : levelText(v));
@@ -36,18 +49,22 @@ function sortedLevels(values) {
36
49
  return distinct.sort((a, b) => a - b).map(label);
37
50
  return [...new Set(distinct.map(label))].sort(compareCodePoints);
38
51
  }
39
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
52
+ // Whether a variable is one of the components of a term name such as "a:b" (compared as names, so that a name that is
53
+ // not a run of word characters, such as ".grp", is found too)
54
+ const inTerm = (variable, term) => term.split(":").includes(variable);
40
55
  /**
41
56
  * The anova table from the rows (intercept excluded) with the effect sizes; `errorSS` are the error sums of squares of
42
- * all rows of the univariate table (intercept included)
57
+ * each error stratum (keyed by its within-subject term, so that two strata whose sums happen to be equal both count).
58
+ * The sums of squares are those of the scaled response: the
59
+ * effect sizes are ratios of them, and only the MSE is scaled back (`unscale`)
43
60
  */
44
- function anovaTable(rows, errorSS, es, observed) {
45
- const isObserved = (name) => observed.some((o) => new RegExp(`\\b${escapeRegExp(o)}\\b`).test(name));
61
+ function anovaTable(rows, errorSS, es, observed, unscale) {
62
+ const isObserved = (name) => observed.some((o) => inTerm(o, name));
46
63
  for (const o of observed) {
47
- if (!rows.some((r) => new RegExp(`\\b${escapeRegExp(o)}\\b`).test(r.name)))
48
- throw new Error(`Observed variable not in data: ${o}`);
64
+ if (!rows.some((r) => inTerm(o, r.name)))
65
+ throw new RangeError(`Observed variable not in data: ${o}`);
49
66
  }
50
- const distinctError = [...new Set(errorSS)].reduce((s, v) => s + v, 0);
67
+ const distinctError = [...errorSS.values()].reduce((s, v) => s + v, 0);
51
68
  const O = rows.reduce((s, r) => (isObserved(r.name) ? s + r.ss : s), 0);
52
69
  const want = ["pes", "ges"].filter((e) => es.includes(e));
53
70
  return {
@@ -55,7 +72,7 @@ function anovaTable(rows, errorSS, es, observed) {
55
72
  rowNames: rows.map((r) => r.name),
56
73
  table: rows.map((r) => {
57
74
  const effects = want.map((e) => e === "pes" ? r.ss / (r.ss + r.errSS) : r.ss / (r.ss + distinctError + O - (isObserved(r.name) ? r.ss : 0)));
58
- return [r.numDf, r.denDf, r.errSS / r.denDf, r.f, ...effects, r.p];
75
+ return [r.numDf, r.denDf, unscale(r.errSS / r.denDf), r.f, ...effects, r.p];
59
76
  }),
60
77
  };
61
78
  }
@@ -84,29 +101,58 @@ function anovaTable(rows, errorSS, es, observed) {
84
101
  * @category Linear models and ANOVA
85
102
  */
86
103
  export function aovEz(data, options) {
104
+ checkOptions(options, AOV_EZ_KEYS, "aovEz"); // generated: option-keys.mjs
87
105
  const between = list(options.between);
88
106
  const within = list(options.within);
89
107
  if (between.length === 0 && within.length === 0)
90
108
  throw new Error("Either between or within need to be non-NULL!");
109
+ // A repeated name is an error, not one factor (afex drops repeats silently; #296)
110
+ for (const [name, names] of [["between", between], ["within", within]]) {
111
+ const repeated = names.filter((n, i) => names.indexOf(n) !== i);
112
+ if (repeated.length > 0)
113
+ throw new RangeError(`duplicated factor names in '${name}': ${[...new Set(repeated)].join(", ")}`);
114
+ }
115
+ const both = between.filter((n) => within.includes(n));
116
+ if (both.length > 0)
117
+ throw new RangeError(`factors in both 'between' and 'within': ${both.join(", ")}`);
91
118
  const type = options.type ?? 3;
92
119
  if (type !== 2 && type !== 3)
93
120
  throw new RangeError(`invalid type (${String(type)}): use 2 or 3`);
94
121
  const correction = options.correction ?? "GG";
122
+ if (!["GG", "HF", "none"].includes(correction))
123
+ throw new RangeError(`invalid 'correction': ${String(correction)}`);
95
124
  const es = list(options.es ?? "ges");
125
+ for (const e of es)
126
+ if (e !== "ges" && e !== "pes")
127
+ throw new RangeError(`invalid 'es': ${String(e)}`);
96
128
  const observed = list(options.observed);
97
129
  const warnings = [];
98
130
  // 1. the columns as factors
99
131
  // (the id and factor columns as R's factor() makes them: numbers with the same 15-digit text are one level)
100
- const ids = numberLevels(column(data, options.id)).map(label);
101
- const dv = column(data, options.dv).map((v) => {
132
+ // Rows with a missing id or factor value (null, undefined or NaN) are dropped, as from a model frame. A missing
133
+ // response (null or NaN) makes its cell missing, so that its id is removed in step 6, as afex does
134
+ const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
135
+ const dvRaw = column(data, options.dv);
136
+ const keyCols = [options.id, ...between, ...within].map((c) => column(data, c));
137
+ for (const c of keyCols)
138
+ if (c.length !== dvRaw.length)
139
+ throw new RangeError("the columns must have the same length");
140
+ const keep = dvRaw.map((_, i) => keyCols.every((c) => !isMissing(c[i])));
141
+ const used = (c) => c.filter((_, i) => keep[i]);
142
+ const ids = numberLevels(used(keyCols[0])).map(label);
143
+ const dvUsed = used(dvRaw).map((v) => {
144
+ if (isMissing(v))
145
+ return NaN;
102
146
  if (typeof v !== "number")
103
147
  throw new TypeError(`the response '${options.dv}' must be numeric`);
148
+ if (!Number.isFinite(v))
149
+ throw new RangeError(`the response '${options.dv}' must be finite`);
104
150
  return v;
105
151
  });
106
- const bcols = between.map((b) => numberLevels(column(data, b)));
107
- const wcols = within.map((w) => numberLevels(column(data, w)));
152
+ const bcols = between.map((_, k) => numberLevels(used(keyCols[1 + k])));
153
+ const wcols = within.map((_, k) => numberLevels(used(keyCols[1 + between.length + k])));
108
154
  const nrow = ids.length;
109
- for (const c of [dv, ...bcols, ...wcols])
155
+ for (const c of [dvUsed, ...bcols, ...wcols])
110
156
  if (c.length !== nrow)
111
157
  throw new RangeError("the columns must have the same length");
112
158
  const blevels = bcols.map((c) => sortedLevels(c));
@@ -118,6 +164,11 @@ export function aovEz(data, options) {
118
164
  if (l.length < 2)
119
165
  throw new Error(`Factor "${between[k]}" consists of one level only. Remove factor from model?`);
120
166
  });
167
+ // a within factor with one level is also an error (afex returns an empty table, which hides the mistake)
168
+ wlevels.forEach((l, k) => {
169
+ if (l.length < 2)
170
+ throw new Error(`Factor "${within[k]}" consists of one level only. Remove factor from model?`);
171
+ });
121
172
  // 3. ids in more than one between cell
122
173
  const idOrder = [...new Set(ids)];
123
174
  const cellOf = new Map();
@@ -142,6 +193,25 @@ export function aovEz(data, options) {
142
193
  const present = new Set(ids.map((_, i) => cellKey(i)));
143
194
  if (cells.some((c) => !present.has(JSON.stringify(c))))
144
195
  throw new Error("Empty cells in within-subjects design (i.e., bad data structure).");
196
+ // the ids removed in step 6: a cell without rows, or a missing response in one
197
+ const seen = new Map();
198
+ const withNaN = new Set();
199
+ ids.forEach((id, i) => {
200
+ let s = seen.get(id);
201
+ if (s === undefined)
202
+ seen.set(id, (s = new Set()));
203
+ s.add(cellKey(i));
204
+ if (Number.isNaN(dvUsed[i]))
205
+ withNaN.add(id);
206
+ });
207
+ const missing = idOrder.filter((id) => withNaN.has(id) || seen.get(id).size < cells.length);
208
+ // The response scaled by 2^-k (exact), so that its cross-products stay in range; sums of squares are scaled back by
209
+ // 2^2k for output, and F, the epsilons and Mauchly's W do not depend on the units. k is set by the ids kept: a
210
+ // removed id with an extreme response scaled the others into the subnormals (#508)
211
+ const removed = new Set(missing);
212
+ const dvExp = scaleToUnit([dvUsed.filter((_, i) => !removed.has(ids[i]))]).k;
213
+ const dv = dvExp === 0 ? dvUsed : dvUsed.map((v) => ldexp(v, -dvExp));
214
+ const unscale = (v) => ldexp(v, 2 * dvExp);
145
215
  // 5. the wide data (means of the rows of an id and a cell)
146
216
  const nc = cells.length;
147
217
  const sums = new Map();
@@ -156,8 +226,7 @@ export function aovEz(data, options) {
156
226
  if ([...sums.values()].some((e) => e.n.some((v) => v > 1))) {
157
227
  warnings.push("More than one observation per design cell, aggregating data using `fun_aggregate = mean`.\nTo turn off this warning, pass `fun_aggregate = mean` explicitly.");
158
228
  }
159
- // 6. ids that miss a cell are removed
160
- const missing = idOrder.filter((id) => sums.get(id).n.some((v) => v === 0));
229
+ // 6. ids that miss a cell (or have a missing response in one) are removed (found above)
161
230
  if (missing.length > 0) {
162
231
  // the ids sorted as the levels of a factor; afex goes on with a printout of the data, which is not reproduced
163
232
  const sorted = [...missing].sort(compareCodePoints);
@@ -178,16 +247,21 @@ export function aovEz(data, options) {
178
247
  const blevelOpt = Object.fromEntries(between.map((b, k) => [b, blevels[k]]));
179
248
  const rankDeficient = "Rank deficient model matrix; insufficient data to estimate full model.";
180
249
  if (nc === 1)
181
- return betweenOnly();
182
- return withinAnalysis();
250
+ return reported("aovEz", betweenOnly());
251
+ return reported("aovEz", withinAnalysis());
183
252
  /** Without within-subject factors (or a single within cell): lm on one value per subject and car's Anova */
184
253
  function betweenOnly() {
185
- const dvName = between.includes("y") ? "y_" : "y";
254
+ // a response name that is none of the between factors (with factors y and y_, "y_" replaced the factor y_, #295)
255
+ let dvName = "y";
256
+ while (between.includes(dvName))
257
+ dvName += "_";
186
258
  const frame = { ...bdata, [dvName]: Y.map((r) => r[0][0]) };
187
- const fit = lm(`${dvName} ~ ${between.length > 0 ? between.join(" * ") : "1"}`, frame, { contrasts: sum, levels: blevelOpt });
259
+ const fit = unreported(() => lm(`${dvName} ~ ${between.length > 0 ? between.join(" * ") : "1"}`, frame, { contrasts: sum, levels: blevelOpt }));
188
260
  if (fit.rank < fit.coefNames.length)
189
261
  throw new Error(rankDeficient);
190
- const tab = Anova(fit, { type });
262
+ if (fit.dfResidual <= 0)
263
+ throw new RangeError(`no residual degrees of freedom: ${Y.length} subject(s) for ${fit.rank} parameter(s)`);
264
+ const tab = unreported(() => Anova(fit, { type }));
191
265
  warnings.push(...tab.warnings.filter((w) => !warnings.includes(w)));
192
266
  const rdf = fit.dfResidual;
193
267
  const rows = tab.rowNames.flatMap((name, i) => {
@@ -196,23 +270,31 @@ export function aovEz(data, options) {
196
270
  const [ss, df, f, p] = tab.table[i];
197
271
  return [{ name, ss: ss, numDf: df, errSS: fit.rss, denDf: rdf, f: f, p: p }];
198
272
  });
199
- return {
200
- anova: anovaTable(rows, [fit.rss], es, observed),
201
- univariate: { colNames: tab.colNames, rowNames: tab.rowNames, table: tab.table },
273
+ const ssCol = tab.colNames.indexOf("Sum Sq");
274
+ const result = {
275
+ anova: anovaTable(rows, new Map([[0, fit.rss]]), es, observed, unscale),
276
+ univariate: { colNames: tab.colNames, rowNames: tab.rowNames, table: tab.table.map((r) => r.map((v, j) => (j === ssCol ? unscale(v) : v))) },
202
277
  within,
203
278
  warnings,
204
279
  };
280
+ // (tab has the sums of squares as fitted: scaledTables.ts)
281
+ scaledTables.set(result, { colNames: tab.colNames, rowNames: tab.rowNames, table: tab.table });
282
+ return result;
205
283
  }
206
284
  function withinAnalysis() {
207
285
  const n = subjects.length;
286
+ // the sum of squares of the wide data (scaled), the reference of the rounding of the data for the rank of P'EP
287
+ const dataSS = Y.reduce((s, r) => r.reduce((t, v) => t + v[0] * v[0], s), 0);
208
288
  // without between factors (an empty data frame) the model matrix is the column of ones
209
289
  const X = between.length > 0
210
- ? modelMatrix(`~ ${between.join(" * ")}`, bdata, { contrasts: sum, levels: blevelOpt })
290
+ ? unreported(() => modelMatrix(`~ ${between.join(" * ")}`, bdata, { contrasts: sum, levels: blevelOpt }))
211
291
  : { colNames: ["(Intercept)"], assign: [0], x: subjects.map(() => [1]), termLabels: [], factors: [] };
212
292
  const px = X.colNames.length;
213
293
  if (n === 0 || qr(X.x).rank < px)
214
294
  throw new Error(rankDeficient);
215
295
  const d = n - px;
296
+ if (d <= 0)
297
+ throw new RangeError(`no residual degrees of freedom: ${n} subject(s) for ${px} between-subject parameter(s)`);
216
298
  const bterms = [0, ...X.termLabels.map((_, j) => j + 1)];
217
299
  const blabs = ["(Intercept)", ...X.termLabels];
218
300
  const colsOf = (terms) => X.assign.flatMap((a, j) => (terms.includes(a) ? [j] : []));
@@ -230,10 +312,10 @@ export function aovEz(data, options) {
230
312
  };
231
313
  // the within design over the cells
232
314
  const cdata = Object.fromEntries(within.map((w, k) => [w, cells.map((c) => c[k])]));
233
- const W = modelMatrix(`~ ${within.join(" * ")}`, cdata, {
315
+ const W = unreported(() => modelMatrix(`~ ${within.join(" * ")}`, cdata, {
234
316
  contrasts: Object.fromEntries(within.map((w) => [w, "contr.sum"])),
235
317
  levels: Object.fromEntries(within.map((w, k) => [w, wlevels[k]])),
236
- });
318
+ }));
237
319
  const wterms = [0, ...W.termLabels.map((_, j) => j + 1)];
238
320
  const wlabs = ["(Intercept)", ...W.termLabels];
239
321
  const cross = (C) => {
@@ -245,12 +327,14 @@ export function aovEz(data, options) {
245
327
  }));
246
328
  };
247
329
  const uni = [];
330
+ // (the same rows with the sums of squares as fitted, for the effect sizes: scaledTables.ts)
331
+ const uniScaled = [];
248
332
  const uniNames = [];
249
333
  const corr = [];
250
334
  const sph = [];
251
335
  const corrNames = [];
252
336
  const rows = [];
253
- const errorSS = [];
337
+ const errorSS = new Map();
254
338
  let hfAbove = false;
255
339
  for (const wt of wterms) {
256
340
  const wc = W.assign.flatMap((a, j) => (a === wt ? [j] : []));
@@ -268,15 +352,41 @@ export function aovEz(data, options) {
268
352
  let mp = NaN;
269
353
  let corrected = false;
270
354
  if (p >= 2) {
271
- const ev = eigen(ddHi(PEP), { symmetric: true, onlyValues: true }).values;
272
- if (ev.filter((v) => v >= SQRT_EPS).length === p) {
355
+ // Each correction is judged on its own condition (car gives none of them for a singular error SSP matrix):
356
+ // - GG: tr(A)^2 / (p tr(A^2)) is defined for any nonzero A, singular or not (1/p for rank 1)
357
+ // - HF: needs d - p GG > 0
358
+ // - Mauchly: needs a nonsingular matrix.
359
+ // The eigenvalues are those of R PEP R' (M = R'R), the same as those of A whatever the contrasts P, in the
360
+ // units of the squared response. An eigenvalue counts as 0 below a fraction of the largest one (exactly
361
+ // singular matrices, from d < p or collinear measurements, have eigenvalues near 1e-16 of it) or of the sum of
362
+ // squares of the wide data (an error SSP matrix made only of the rounding of additive data, at any scale).
363
+ // An absolute threshold, as car's, would depend on the units of the response.
364
+ const term = wlabs[wt];
365
+ const Rm = chol(ddHi(M)).map((r) => r.map((v) => [v, 0]));
366
+ const S = ddHi(ddMatMul(ddMatMul(Rm, PEP), ddTranspose(Rm)));
367
+ const ev = eigen(S, { symmetric: true, onlyValues: true }).values;
368
+ const top = ev.reduce((a, b) => Math.max(a, b), 0);
369
+ const zero = Math.max(top * REL_RANK_TOL, dataSS * ABS_RANK_TOL);
370
+ const tA = ddTrace(A);
371
+ const tAA = ddTrace(ddMatMul(A, A));
372
+ if (top > dataSS * ABS_RANK_TOL && tAA[0] > 0 && Number.isFinite(tAA[0])) {
273
373
  corrected = true;
274
- const tA = ddTrace(A);
275
- gg = ddDiv(ddMul(tA, tA), ddMulNum(ddTrace(ddMatMul(A, A)), p))[0];
276
- hf = ((d + 1) * p * gg - 2) / (p * (d - p * gg));
374
+ gg = ddDiv(ddMul(tA, tA), ddMulNum(tAA, p))[0];
375
+ if (d - p * gg > 0)
376
+ hf = ((d + 1) * p * gg - 2) / (p * (d - p * gg));
377
+ else
378
+ warnings.push(`The Huynh-Feldt epsilon of ${term} is undefined (d - p GG <= 0)${correction === "HF" ? ": corrected with GG" : ""}`);
379
+ }
380
+ else {
381
+ warnings.push(`The error SSP matrix of ${term} is 0 (or at the rounding level of the data): no sphericity corrections (the p-values are uncorrected)`);
382
+ }
383
+ if (corrected && ev.every((v) => v > zero)) {
277
384
  mw = sphericityW(ddMatMul(M, PEP));
278
385
  mp = mauchlyPValue(mw, p, d, nc);
279
386
  }
387
+ else if (corrected) {
388
+ warnings.push(`The error SSP matrix of ${term} is singular: no Mauchly test (the epsilons are still defined)`);
389
+ }
280
390
  }
281
391
  for (let bi = 0; bi < bterms.length; bi++) {
282
392
  const bt = bterms[bi];
@@ -297,9 +407,10 @@ export function aovEz(data, options) {
297
407
  const f = ss / numDf / (errSS / denDf);
298
408
  const pval = pf1(f, numDf, denDf, false, false);
299
409
  const name = wt === 0 ? blabs[bi] : bt === 0 ? wlabs[wt] : `${blabs[bi]}:${wlabs[wt]}`;
300
- uni.push([ss, numDf, errSS, denDf, f, pval]);
410
+ uni.push([unscale(ss), numDf, unscale(errSS), denDf, f, pval]);
411
+ uniScaled.push([ss, numDf, errSS, denDf, f, pval]);
301
412
  uniNames.push(name);
302
- errorSS.push(errSS);
413
+ errorSS.set(wt, errSS);
303
414
  let row = { name, ss, numDf, errSS, denDf, f, p: pval };
304
415
  if (corrected) {
305
416
  const hf1 = Math.min(1, hf);
@@ -313,7 +424,10 @@ export function aovEz(data, options) {
313
424
  else if (correction === "HF") {
314
425
  if (hf > 1)
315
426
  hfAbove = true;
316
- row = { ...row, numDf: hf1 * numDf, denDf: hf1 * denDf, p: phf };
427
+ // an undefined HF epsilon falls back on GG (with the warning above), not on the uncorrected test
428
+ row = Number.isNaN(hf)
429
+ ? { ...row, numDf: gg * numDf, denDf: gg * denDf, p: pgg }
430
+ : { ...row, numDf: hf1 * numDf, denDf: hf1 * denDf, p: phf };
317
431
  }
318
432
  }
319
433
  if (!(wt === 0 && bt === 0))
@@ -323,7 +437,7 @@ export function aovEz(data, options) {
323
437
  if (hfAbove)
324
438
  warnings.push("HF eps > 1 treated as 1");
325
439
  const out = {
326
- anova: anovaTable(rows, errorSS, es, observed),
440
+ anova: anovaTable(rows, errorSS, es, observed, unscale),
327
441
  univariate: { colNames: ["Sum Sq", "num Df", "Error SS", "den Df", "F value", "Pr(>F)"], rowNames: uniNames, table: uni },
328
442
  within,
329
443
  warnings,
@@ -332,6 +446,7 @@ export function aovEz(data, options) {
332
446
  out.corrections = { colNames: ["GG eps", "Pr(>F[GG])", "HF eps", "Pr(>F[HF])"], rowNames: corrNames, table: corr };
333
447
  out.sphericity = { colNames: ["Test statistic", "p-value"], rowNames: [...corrNames], table: sph };
334
448
  }
449
+ scaledTables.set(out, { colNames: out.univariate.colNames, rowNames: uniNames, table: uniScaled });
335
450
  return out;
336
451
  }
337
452
  }
@@ -6,18 +6,31 @@
6
6
  // its orthonormal Q, computed in double-double (src/models/ddLeastSquares.ts), splits the space of the observations
7
7
  // into strata: the columns of each term of the error model orthogonal to the earlier ones, and the rest ("Within").
8
8
  // In the coordinates of a stratum (Q'v restricted to it, which keeps lengths and inner products of the projections),
9
- // the treatment columns whose projection has a squared length greater than 1e-5 are kept, and the projected response
9
+ // the treatment columns whose projection has a squared length greater than 1e-14 times the column's own are kept, that
10
+ // is, those not orthogonal to the stratum up to rounding (R's aov compares the squared length with 1e-5 itself, which
11
+ // depends on the units: a covariate in small units lost its effect, and one in large units kept a projection that is
12
+ // rounding error; a threshold relative to the column's mean square instead dropped the small within-subject part of a
13
+ // covariate that varies mostly between subjects). Q is accurate to double-double, so the projection of a column
14
+ // lying in other strata is far below the threshold, and the projected response
10
15
  // is fitted on them in order with the same pivoting QR (tolerance 1e-7) as lm; the effects give the sums of squares.
11
16
  import { pf1 } from "../distributions/f.js";
17
+ import { ldexp, scaleToUnit } from "../internal/summary.js";
12
18
  import { qr } from "../linalg/qr.js";
13
19
  import { ddAdd, ddMul } from "../special/dd.js";
14
20
  import { ddLeastSquares, ddLeastSquaresMulti, ddSumSquares } from "./ddLeastSquares.js";
15
21
  import { termsOf } from "./formula.js";
16
22
  import { design } from "./modelMatrix.js";
23
+ import { rssWithinRounding } from "./anovaSequential.js";
24
+ import { scaledTables } from "./scaledTables.js";
25
+ /** Squared length of a column's projection on a stratum, relative to its own, below which it is not in the stratum */
26
+ const STRATUM_TOL = 1e-14;
17
27
  /** The table of a stratum: terms that have columns in it, then Residuals when its df is positive */
18
- function stratumTable(name, zy, zcols, assign, labels) {
28
+ function stratumTable(name, zy, zcols, assign, labels, columnSS, k, wy) {
29
+ // zy is the response scaled by 2^-k: F and p come from it, the sums of squares are scaled back by 2^2k (the second
30
+ // table keeps them as fitted, for the effect sizes: see scaledTables.ts)
31
+ const scaleBack = (v) => ldexp(v, 2 * k);
19
32
  const dim = zy.length;
20
- const kept = zcols.flatMap((c, j) => (ddSumSquares(c)[0] > 1e-5 ? [j] : []));
33
+ const kept = zcols.flatMap((c, j) => (ddSumSquares(c)[0] > STRATUM_TOL * columnSS[j] ? [j] : []));
21
34
  let rank = 0;
22
35
  let order = [];
23
36
  let qty = zy.slice();
@@ -37,24 +50,35 @@ function stratumTable(name, zy, zcols, assign, labels) {
37
50
  row.ss = ddAdd(row.ss, ddMul(qty[k], qty[k]));
38
51
  });
39
52
  const rdf = dim - rank;
40
- const rss = ddSumSquares(qty, rank)[0];
41
- const rows = terms.filter((r) => r.term !== 0);
42
- const rowNames = rows.map((r) => labels[r.term - 1]);
43
- if (rdf > 0) {
44
- const rms = rss / rdf;
45
- const table = rows.map(({ df, ss }) => {
46
- const f = ss[0] / df / rms;
47
- return [df, ss[0], ss[0] / df, f, pf1(f, df, rdf, false, false)];
48
- });
49
- table.push([rdf, rss, rms, NaN, NaN]);
50
- return { stratum: `Error: ${name}`, colNames: ["Df", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"], rowNames: [...rowNames, "Residuals"], table };
53
+ let rss = ddSumSquares(qty, rank)[0];
54
+ let rows = terms.filter((r) => r.term !== 0);
55
+ // A residual sum of squares at the level of rounding (below 1e-24 times the sum of squares of the response wy, as in
56
+ // anova and Anova: rssWithinRounding) is the residue of an exact fit in the stratum: it is taken as 0 (F = Inf),
57
+ // with the sums of squares of the terms at that level (0 / 0: F = NaN). R keeps the residue (F = 2.9e33). Other
58
+ // strata keep their bits
59
+ if (rdf > 0 && rssWithinRounding(wy, rss)) {
60
+ rss = 0;
61
+ rows = rows.map((r) => (rssWithinRounding(wy, r.ss[0]) ? { ...r, ss: [0, 0] } : r));
51
62
  }
52
- return {
53
- stratum: `Error: ${name}`,
54
- colNames: ["Df", "Sum Sq", "Mean Sq"],
55
- rowNames,
56
- table: rows.map(({ df, ss }) => [df, ss[0], ss[0] / df]),
63
+ const rowNames = rows.map((r) => labels[r.term - 1]);
64
+ const build = (back) => {
65
+ if (rdf > 0) {
66
+ const rms = rss / rdf;
67
+ const table = rows.map(({ df, ss }) => {
68
+ const f = ss[0] / df / rms;
69
+ return [df, back(ss[0]), back(ss[0] / df), f, pf1(f, df, rdf, false, false)];
70
+ });
71
+ table.push([rdf, back(rss), back(rms), NaN, NaN]);
72
+ return { stratum: `Error: ${name}`, colNames: ["Df", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"], rowNames: [...rowNames, "Residuals"], table };
73
+ }
74
+ return {
75
+ stratum: `Error: ${name}`,
76
+ colNames: ["Df", "Sum Sq", "Mean Sq"],
77
+ rowNames,
78
+ table: rows.map(({ df, ss }) => [df, back(ss[0]), back(ss[0] / df)]),
79
+ };
57
80
  };
81
+ return [build(scaleBack), build((v) => v)];
58
82
  }
59
83
  /**
60
84
  * The multistratum fit of `y ~ treatment + Error(e)`.
@@ -73,6 +97,9 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
73
97
  const y = dt.y;
74
98
  if (y === undefined)
75
99
  throw new TypeError("the formula has no response");
100
+ // as R and the fit without Error() (#299: an infinite response gave NaN tables)
101
+ if (y.some((v) => !Number.isFinite(v)))
102
+ throw new RangeError("NA/NaN/Inf in 'y'");
76
103
  const de = design({ response: parsed.response, rhs: errorRhs }, data, {
77
104
  ...(options.levels === undefined ? {} : { levels: options.levels }),
78
105
  allContrasts: "contr.helmert",
@@ -83,14 +110,28 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
83
110
  const n = y.length;
84
111
  const warnings = [...dt.warnings, ...de.warnings.filter((w) => !dt.warnings.includes(w))];
85
112
  const pe = de.colNames.length;
86
- const qe = pe > 0 ? qr(de.x) : undefined;
113
+ // each column of the error model divided by its own power of 2 (exact): the strata depend only on the space the
114
+ // columns span, but the double-double decomposition squares them (a covariate around 1e-200 in Error() underflowed
115
+ // and gave other strata); columns of 0 and 1 are unchanged
116
+ const ecols = de.colNames.map((_, j) => scaleToUnit([de.x.map((r) => r[j])]).groups[0]);
117
+ const ex = de.x.map((_, i) => ecols.map((c) => c[i]));
118
+ const qe = pe > 0 ? qr(ex) : undefined;
87
119
  const re = qe?.rank ?? 0;
88
120
  if (re < pe)
89
121
  warnings.push("Error() model is singular");
90
122
  const kept = qe?.pivot.slice(0, re) ?? [];
91
123
  const toDD = (v) => v.map((t) => [t, 0]);
92
- const tcols = dt.colNames.map((_, j) => toDD(dt.x.map((r) => r[j])));
93
- const { fit, qtv } = ddLeastSquaresMulti(kept.map((j) => toDD(de.x.map((r) => r[j]))), toDD(y), tcols);
124
+ // each treatment column divided by its own power of 2 (exact): a stratum's sums of squares depend only on the space
125
+ // the columns span, and the test of a column's projection is a ratio, but its squares overflowed for a covariate
126
+ // around 1e200 and the term was dropped from every stratum
127
+ const tcols = dt.colNames.map((_, j) => toDD(scaleToUnit([dt.x.map((r) => r[j])]).groups[0]));
128
+ // the response scaled by 2^-k (exact, src/internal/summary.ts), so that its sums of squares stay in range
129
+ const { groups: scaledY, k: yScale } = scaleToUnit([y]);
130
+ const { fit, qtv } = ddLeastSquaresMulti(kept.map((j) => toDD(ecols[j])), toDD(scaledY[0]), tcols);
131
+ // the scaled response with weights 1, for the check of a residual sum of squares at the level of rounding
132
+ const wy = scaledY[0].map((v) => [1, v]);
133
+ // the squared length of each treatment column (the scale of its threshold in stratumTable)
134
+ const columnSS = tcols.map((c) => ddSumSquares(c)[0]);
94
135
  // the strata: positions of Q's columns by term of the error model, then the rest
95
136
  const groups = [];
96
137
  kept.forEach((j, k) => {
@@ -103,6 +144,9 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
103
144
  });
104
145
  if (n > re)
105
146
  groups.push({ name: "Within", idx: Array.from({ length: n - re }, (_, i) => re + i) });
106
- const strata = groups.map((g) => stratumTable(g.name, g.idx.map((i) => fit.qty[i]), qtv.map((c) => g.idx.map((i) => c[i])), dt.assign, dt.terms.termLabels));
107
- return { formula, multistratum: true, strata, rows: dt.frame.rows, warnings };
147
+ const both = groups.map((g) => stratumTable(g.name, g.idx.map((i) => fit.qty[i]), qtv.map((c) => g.idx.map((i) => c[i])), dt.assign, dt.terms.termLabels, columnSS, yScale, wy));
148
+ const strata = both.map((b) => b[0]);
149
+ const result = { formula, multistratum: true, strata, rows: dt.frame.rows, warnings };
150
+ scaledTables.set(result, both.map((b) => b[1]));
151
+ return result;
108
152
  }
@@ -1,4 +1,4 @@
1
- import type { AnovaTable } from "./anovaSequential.js";
1
+ import { type AnovaTable } from "./anovaSequential.js";
2
2
  import type { LmFormulaResult } from "./lm.js";
3
3
  /**
4
4
  * Options for {@link Anova}.