@numero-uno-jpn/rstats 0.16.0 → 1.0.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 (243) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/README.ja.md +57 -23
  3. package/README.md +60 -23
  4. package/dist/chunks/{chunk-5UQCRBAG.js → chunk-3W5NFFAA.js} +1 -1
  5. package/dist/chunks/chunk-4F2IALD4.js +3 -0
  6. package/dist/chunks/{chunk-QNNL7AZ3.js → chunk-4OLDGML4.js} +2 -2
  7. package/dist/chunks/chunk-63OPBEYO.js +2 -0
  8. package/dist/chunks/chunk-6XJBCRBV.js +2 -0
  9. package/dist/chunks/chunk-BQSIBJVX.js +2 -0
  10. package/dist/chunks/chunk-BWKHYRM6.js +3 -0
  11. package/dist/chunks/{chunk-W26LRYOJ.js → chunk-CKV4JWW2.js} +1 -1
  12. package/dist/chunks/chunk-DCAWMF4K.js +2 -0
  13. package/dist/chunks/chunk-F7YGX7PN.js +2 -0
  14. package/dist/chunks/chunk-H7I32ZZE.js +2 -0
  15. package/dist/chunks/chunk-IEOD5GWC.js +3 -0
  16. package/dist/chunks/chunk-KICBQGFN.js +2 -0
  17. package/dist/chunks/chunk-LROMWFAK.js +2 -0
  18. package/dist/chunks/chunk-NSWENS3S.js +2 -0
  19. package/dist/chunks/chunk-O2SQMGE3.js +2 -0
  20. package/dist/chunks/chunk-QQX46TCI.js +2 -0
  21. package/dist/chunks/chunk-QZK3CCBA.js +2 -0
  22. package/dist/chunks/chunk-UJ66VQIG.js +2 -0
  23. package/dist/chunks/chunk-UKNDX4BA.js +2 -0
  24. package/dist/chunks/chunk-WIBKS73G.js +2 -0
  25. package/dist/chunks/{chunk-URIO5LY5.js → chunk-WQWZ7FND.js} +2 -2
  26. package/dist/chunks/chunk-WWVMVZUL.js +2 -0
  27. package/dist/chunks/chunk-YG5S5AVP.js +2 -0
  28. package/dist/chunks/chunk-YHNMBYSW.js +2 -0
  29. package/dist/data/grouping.js +6 -2
  30. package/dist/descriptive/basic.js +20 -0
  31. package/dist/descriptive/cov.js +11 -0
  32. package/dist/descriptive/dataFrames.js +13 -5
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +10 -2
  35. package/dist/descriptive/hist.js +6 -0
  36. package/dist/descriptive/moments.js +14 -0
  37. package/dist/descriptive/omega.js +8 -3
  38. package/dist/descriptive/pivot.d.ts +4 -1
  39. package/dist/descriptive/pivot.js +27 -13
  40. package/dist/descriptive/quantile.js +8 -0
  41. package/dist/descriptive/rank.js +4 -0
  42. package/dist/descriptive/table.d.ts +20 -1
  43. package/dist/descriptive/table.js +14 -14
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +8 -0
  46. package/dist/distributions/beta.js +9 -0
  47. package/dist/distributions/binomial.js +9 -0
  48. package/dist/distributions/cauchy.js +9 -0
  49. package/dist/distributions/chisq.js +9 -0
  50. package/dist/distributions/exponential.js +9 -0
  51. package/dist/distributions/f.js +9 -0
  52. package/dist/distributions/gamma.js +8 -0
  53. package/dist/distributions/geometric.js +9 -0
  54. package/dist/distributions/hypergeometric.js +8 -0
  55. package/dist/distributions/invgamma.js +8 -0
  56. package/dist/distributions/kumaraswamy.js +9 -0
  57. package/dist/distributions/laplace.js +9 -0
  58. package/dist/distributions/logistic.js +9 -0
  59. package/dist/distributions/lognormal.js +8 -0
  60. package/dist/distributions/multinomial.js +4 -0
  61. package/dist/distributions/negbinomial.js +8 -0
  62. package/dist/distributions/normal.js +8 -0
  63. package/dist/distributions/pareto.js +8 -0
  64. package/dist/distributions/poisson.js +9 -0
  65. package/dist/distributions/signrank.js +9 -0
  66. package/dist/distributions/summary.d.ts +2 -1
  67. package/dist/distributions/summary.js +31 -1
  68. package/dist/distributions/t.js +9 -0
  69. package/dist/distributions/triangular.js +9 -0
  70. package/dist/distributions/tukey.js +6 -0
  71. package/dist/distributions/uniform.js +8 -0
  72. package/dist/distributions/weibull.js +8 -0
  73. package/dist/distributions/wilcox.js +9 -0
  74. package/dist/distributions.js +2 -2
  75. package/dist/entries/descriptive.d.ts +3 -1
  76. package/dist/entries/descriptive.js +1 -1
  77. package/dist/entries/distributions.d.ts +1 -0
  78. package/dist/entries/distributions.js +2 -0
  79. package/dist/entries/linalg.d.ts +3 -1
  80. package/dist/entries/mixed.d.ts +9 -0
  81. package/dist/entries/mixed.js +8 -1
  82. package/dist/entries/numerics.d.ts +2 -1
  83. package/dist/entries/tests.d.ts +8 -5
  84. package/dist/entries/tests.js +3 -1
  85. package/dist/htest/agreement.d.ts +13 -0
  86. package/dist/htest/agreement.js +46 -7
  87. package/dist/htest/ansariTest.d.ts +2 -1
  88. package/dist/htest/ansariTest.js +43 -12
  89. package/dist/htest/aov.d.ts +28 -22
  90. package/dist/htest/aov.js +42 -13
  91. package/dist/htest/binomTest.js +6 -0
  92. package/dist/htest/brunnerMunzelTest.js +5 -0
  93. package/dist/htest/chisqTest.d.ts +3 -1
  94. package/dist/htest/chisqTest.js +21 -3
  95. package/dist/htest/cor.d.ts +7 -1
  96. package/dist/htest/cor.js +40 -7
  97. package/dist/htest/core/simulate.d.ts +6 -0
  98. package/dist/htest/core/simulate.js +20 -0
  99. package/dist/htest/effectSize.d.ts +3 -0
  100. package/dist/htest/effectSize.js +28 -8
  101. package/dist/htest/fisherTest.d.ts +2 -1
  102. package/dist/htest/fisherTest.js +52 -6
  103. package/dist/htest/ksTest.d.ts +4 -0
  104. package/dist/htest/ksTest.js +13 -4
  105. package/dist/htest/leveneTest.d.ts +2 -0
  106. package/dist/htest/leveneTest.js +9 -3
  107. package/dist/htest/mantelhaenTest.js +7 -0
  108. package/dist/htest/mcnemarTest.js +8 -0
  109. package/dist/htest/multipleComparisons.d.ts +16 -25
  110. package/dist/htest/multipleComparisons.js +26 -43
  111. package/dist/htest/normalityTests.js +10 -4
  112. package/dist/htest/onewayTest.js +10 -0
  113. package/dist/htest/pAdjust.js +4 -0
  114. package/dist/htest/pairwise.d.ts +2 -0
  115. package/dist/htest/pairwise.js +29 -6
  116. package/dist/htest/poissonTest.js +6 -0
  117. package/dist/htest/polycor.js +20 -10
  118. package/dist/htest/power.d.ts +4 -0
  119. package/dist/htest/power.js +16 -2
  120. package/dist/htest/propTest.d.ts +3 -0
  121. package/dist/htest/propTest.js +23 -2
  122. package/dist/htest/pwr.d.ts +38 -1
  123. package/dist/htest/pwr.js +38 -15
  124. package/dist/htest/rankTests.js +7 -1
  125. package/dist/htest/tTest.d.ts +2 -0
  126. package/dist/htest/tTest.js +9 -0
  127. package/dist/htest/testFormula.js +11 -11
  128. package/dist/htest/trendTests.d.ts +21 -1
  129. package/dist/htest/trendTests.js +13 -18
  130. package/dist/htest/types.d.ts +2 -0
  131. package/dist/htest/varTest.js +7 -0
  132. package/dist/htest/wilcoxTest.js +51 -9
  133. package/dist/internal/checkOptions.d.ts +11 -0
  134. package/dist/internal/checkOptions.js +31 -0
  135. package/dist/internal/optionalArgs.d.ts +12 -0
  136. package/dist/internal/optionalArgs.js +46 -0
  137. package/dist/internal/warnings.d.ts +66 -0
  138. package/dist/internal/warnings.js +122 -0
  139. package/dist/linalg/basic.js +7 -0
  140. package/dist/linalg/chol.js +6 -0
  141. package/dist/linalg/eigen.js +4 -0
  142. package/dist/linalg/expm.js +4 -0
  143. package/dist/linalg/kappa.js +6 -0
  144. package/dist/linalg/lu.js +5 -0
  145. package/dist/linalg/norm.js +4 -0
  146. package/dist/linalg/ops.d.ts +27 -2
  147. package/dist/linalg/ops.js +14 -13
  148. package/dist/linalg/qr.js +14 -0
  149. package/dist/linalg/solve.js +9 -0
  150. package/dist/linalg/svd.js +6 -2
  151. package/dist/linalg.js +2 -2
  152. package/dist/mixed.js +5 -4
  153. package/dist/models/anovaSequential.d.ts +16 -1
  154. package/dist/models/anovaSequential.js +50 -7
  155. package/dist/models/aovEz.js +16 -11
  156. package/dist/models/aovStrata.js +15 -4
  157. package/dist/models/carAnova.js +11 -17
  158. package/dist/models/coxph.d.ts +6 -0
  159. package/dist/models/coxph.js +21 -6
  160. package/dist/models/formula.d.ts +5 -2
  161. package/dist/models/formula.js +31 -8
  162. package/dist/models/glm.d.ts +22 -2
  163. package/dist/models/glm.js +32 -22
  164. package/dist/models/glmAnova.js +8 -3
  165. package/dist/models/glmConfint.js +6 -2
  166. package/dist/models/glmFamily.d.ts +1 -6
  167. package/dist/models/glmFamily.js +3 -22
  168. package/dist/models/glmer.d.ts +255 -0
  169. package/dist/models/glmer.js +635 -0
  170. package/dist/models/glmerAnova.d.ts +81 -0
  171. package/dist/models/glmerAnova.js +139 -0
  172. package/dist/models/glmerDeviance.d.ts +98 -0
  173. package/dist/models/glmerDeviance.js +576 -0
  174. package/dist/models/glmerFamily.d.ts +57 -0
  175. package/dist/models/glmerFamily.js +236 -0
  176. package/dist/models/glmerGradient.d.ts +46 -0
  177. package/dist/models/glmerGradient.js +301 -0
  178. package/dist/models/glmerStructure.d.ts +45 -0
  179. package/dist/models/glmerStructure.js +168 -0
  180. package/dist/models/glmerSummary.d.ts +102 -0
  181. package/dist/models/glmerSummary.js +94 -0
  182. package/dist/models/lm.js +13 -3
  183. package/dist/models/lmer.d.ts +27 -6
  184. package/dist/models/lmer.js +75 -321
  185. package/dist/models/lmerAnova.d.ts +52 -3
  186. package/dist/models/lmerAnova.js +101 -45
  187. package/dist/models/lmerTest.d.ts +12 -5
  188. package/dist/models/lmerTest.js +39 -18
  189. package/dist/models/mauchly.d.ts +2 -0
  190. package/dist/models/mauchly.js +7 -2
  191. package/dist/models/mixedDeviance.d.ts +28 -2
  192. package/dist/models/mixedDeviance.js +84 -56
  193. package/dist/models/mixedMinimiser.d.ts +83 -0
  194. package/dist/models/mixedMinimiser.js +438 -0
  195. package/dist/models/mixedPredict.d.ts +121 -0
  196. package/dist/models/mixedPredict.js +530 -0
  197. package/dist/models/mixedStructure.d.ts +62 -3
  198. package/dist/models/mixedStructure.js +74 -29
  199. package/dist/models/modelFrame.js +2 -2
  200. package/dist/models/modelMatrix.d.ts +8 -1
  201. package/dist/models/modelMatrix.js +56 -39
  202. package/dist/models/survival.d.ts +6 -0
  203. package/dist/models/survival.js +9 -2
  204. package/dist/numerics/deriv.js +8 -0
  205. package/dist/numerics/integrate.js +8 -0
  206. package/dist/numerics/interp.d.ts +32 -7
  207. package/dist/numerics/interp.js +27 -9
  208. package/dist/numerics/ode.js +4 -0
  209. package/dist/numerics.js +2 -2
  210. package/dist/optim/optim.js +17 -2
  211. package/dist/random/beta.js +5 -0
  212. package/dist/random/continuous.js +17 -0
  213. package/dist/random/extra.js +13 -0
  214. package/dist/random/gamma.js +11 -0
  215. package/dist/random/poisson.js +5 -0
  216. package/dist/random/rng.js +4 -0
  217. package/dist/random/sample.js +6 -0
  218. package/dist/rstats.js +17 -14
  219. package/dist/special/besselIK.js +7 -0
  220. package/dist/special/choose.js +7 -0
  221. package/dist/special/psigamma.js +7 -0
  222. package/dist/special.js +2 -2
  223. package/dist/tests.js +14 -11
  224. package/llms.txt +15 -4
  225. package/package.json +19 -10
  226. package/dist/chunks/chunk-2D2IQWUQ.js +0 -2
  227. package/dist/chunks/chunk-6CSTWA5E.js +0 -2
  228. package/dist/chunks/chunk-72Y3HZID.js +0 -2
  229. package/dist/chunks/chunk-BG2KLEHM.js +0 -2
  230. package/dist/chunks/chunk-CMEKBNHQ.js +0 -2
  231. package/dist/chunks/chunk-FLJNSXSW.js +0 -2
  232. package/dist/chunks/chunk-GM53LWSR.js +0 -2
  233. package/dist/chunks/chunk-JBCA56ZS.js +0 -3
  234. package/dist/chunks/chunk-K3RJAD2T.js +0 -2
  235. package/dist/chunks/chunk-KAZRWIB5.js +0 -2
  236. package/dist/chunks/chunk-KBVVIMXX.js +0 -3
  237. package/dist/chunks/chunk-N3SIFCZX.js +0 -2
  238. package/dist/chunks/chunk-SC6CV4Z3.js +0 -2
  239. package/dist/chunks/chunk-SYWOBOTR.js +0 -2
  240. package/dist/chunks/chunk-VTUGG2SV.js +0 -2
  241. package/dist/chunks/chunk-XHETEYVC.js +0 -2
  242. package/dist/chunks/chunk-YRZWONZB.js +0 -3
  243. package/dist/chunks/chunk-ZGABZMWX.js +0 -2
@@ -11,12 +11,19 @@ import { pf1, qf1 } from "../distributions/f.js";
11
11
  import { pnorm } from "../distributions/normal.js";
12
12
  import { numberLevels } from "../internal/levels.js";
13
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";
15
16
  import { qr, qrResid } from "../linalg/qr.js";
16
17
  import { ddAdd, ddDivNum, ddMul, ddSub } from "../special/dd.js";
17
18
  import { formatR } from "./core/simulate.js";
18
19
  import { matchChoice } from "./power.js";
19
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"];
20
27
  /** Columns of a matrix given as an array of rows, after checking that it is rectangular */
21
28
  function columnsOf(x, what) {
22
29
  const k = x[0]?.length ?? 0;
@@ -53,6 +60,7 @@ const twoSidedP = (z) => 2 * pnorm(-Math.abs(z));
53
60
  * @category Agreement, reliability and factor analysis
54
61
  */
55
62
  export function kappa2(ratings, options = {}) {
63
+ checkOptions(options, KAPPA2_KEYS, "kappa2"); // generated: option-keys.mjs
56
64
  const weight = matchChoice(options.weight, ["unweighted", "equal", "squared"]);
57
65
  if (ratings.some((r) => r.length !== 2))
58
66
  throw new TypeError("'ratings' must be a matrix with two columns");
@@ -90,7 +98,7 @@ export function kappa2(ratings, options = {}) {
90
98
  const v = Array.from({ length: c }, (_, s) => sum(a.map((ar, r) => ar * W[r][s])));
91
99
  const variance0 = (terms((r, s) => a[r] * b[s] * (W[r][s] - (u[r] + v[s])) ** 2) - pe * pe) / (n * (1 - pe) ** 2);
92
100
  const statistic = value / Math.sqrt(variance0);
93
- return { value, statistic, pValue: twoSidedP(statistic) };
101
+ return { value, statistic, pValue: twoSidedP(statistic), warnings: [] };
94
102
  }
95
103
  /**
96
104
  * Fleiss' kappa for several raters (or Conger's exact kappa), with the z test of kappa = 0 for Fleiss' kappa.
@@ -109,6 +117,7 @@ export function kappa2(ratings, options = {}) {
109
117
  * @category Agreement, reliability and factor analysis
110
118
  */
111
119
  export function kappamFleiss(ratings, options = {}) {
120
+ checkOptions(options, KAPPAM_FLEISS_KEYS, "kappamFleiss"); // generated: option-keys.mjs
112
121
  const exact = options.exact ?? false;
113
122
  const cols = columnsOf(ratings, "ratings");
114
123
  requireComplete(ratings, "ratings");
@@ -145,12 +154,12 @@ export function kappamFleiss(ratings, options = {}) {
145
154
  }
146
155
  const value = (po - pe) / (1 - pe);
147
156
  if (exact)
148
- return { value };
157
+ return { value, warnings: [] };
149
158
  const pq = sum(p.map((pj) => pj * (1 - pj)));
150
159
  const skew = sum(p.map((pj) => pj * (1 - pj) * (1 - pj - pj)));
151
160
  const variance0 = (2 / (pq * pq * n * m * (m - 1))) * (pq * pq - skew);
152
161
  const statistic = value / Math.sqrt(variance0);
153
- return { value, statistic, pValue: twoSidedP(statistic) };
162
+ return { value, statistic, pValue: twoSidedP(statistic), warnings: [] };
154
163
  }
155
164
  /**
156
165
  * Intraclass correlation coefficient with its F test and confidence interval (McGraw and Wong's forms).
@@ -168,6 +177,7 @@ export function kappamFleiss(ratings, options = {}) {
168
177
  * @category Agreement, reliability and factor analysis
169
178
  */
170
179
  export function icc(ratings, options = {}) {
180
+ checkOptions(options, ICC_KEYS, "icc"); // generated: option-keys.mjs
171
181
  const model = matchChoice(options.model, ["oneway", "twoway"]);
172
182
  const type = matchChoice(options.type, ["consistency", "agreement"]);
173
183
  const unit = matchChoice(options.unit, ["single", "average"]);
@@ -210,7 +220,7 @@ export function icc(ratings, options = {}) {
210
220
  const [value, Fvalue, bound] = unit === "single"
211
221
  ? [(msr - ms) / (msr + (k - 1) * ms), (ratio * (1 - r0)) / (1 + (k - 1) * r0), (f) => (f - 1) / (f + k - 1)]
212
222
  : [(msr - ms) / msr, ratio * (1 - r0), (f) => 1 - 1 / f];
213
- 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: [] };
214
224
  }
215
225
  // two-way agreement: Satterthwaite's degrees of freedom v for the combination a MSc + b MSe
216
226
  const scale = unit === "single" ? k : 1;
@@ -231,7 +241,7 @@ export function icc(ratings, options = {}) {
231
241
  (n * (FU * msr - mse)) / (k * msc + (k * n - k - n) * mse + n * FU * msr),
232
242
  ]
233
243
  : [(n * (msr - FL * mse)) / (FL * (msc - mse) + n * msr), (n * (FU * msr - mse)) / (msc - mse + n * FU * msr)];
234
- 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: [] };
235
245
  }
236
246
  /** Raw alpha of the covariance matrix C restricted to the items `keep` */
237
247
  function rawAlphaOf(C, keep) {
@@ -245,6 +255,11 @@ function rawAlphaOf(C, keep) {
245
255
  * and alpha with each item dropped. Equivalent to `psych::alpha()` in R. It gives the `total` row and
246
256
  * `alpha.drop$raw_alpha` of `alpha(x)` with its defaults (no missing values, no reversed items).
247
257
  *
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
+ *
248
263
  * @param x - An n × k matrix (array of rows): k ≥ 2 items observed on n ≥ 2 subjects.
249
264
  *
250
265
  * @example
@@ -287,13 +302,37 @@ export function cronbachAlpha(x) {
287
302
  return 1 - sum(res.map((v) => v * v)) / sum(y.map((v) => (v - m) ** 2));
288
303
  });
289
304
  }
290
- return {
305
+ return reported("cronbachAlpha", {
291
306
  rawAlpha: rawAlphaOf(C, items),
292
307
  stdAlpha: ((1 - k / sumR) * k) / (k - 1),
293
308
  G6: 1 - (k - sum(smc)) / sumR,
294
309
  averageR: (sumR - k) / (k * (k - 1)),
295
310
  alphaDrop: items.map((i) => rawAlphaOf(C, items.filter((j) => j !== i))),
296
- };
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;
297
336
  }
298
337
  /**
299
338
  * Partial correlation of columns `i` and `j` of `x` given all its other columns. Equivalent to
@@ -28,7 +28,8 @@ export interface AnsariTestOptions {
28
28
  * estimate, both computed with the locations taken as 0 (exact without ties when both samples have fewer than 50
29
29
  * values, otherwise by the normal approximation, whose limits are roots found to a tolerance of 1e-4 as in R). Limits
30
30
  * that cannot be formed (the samples differ in location) are `NaN`. With ties and `exact` unset or `true`, R fails
31
- * ("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.
32
33
  *
33
34
  * @example
34
35
  * ```ts
@@ -19,11 +19,16 @@
19
19
  import { pnorm, qnorm } from "../distributions/normal.js";
20
20
  import { ldexp, rank } from "../internal/summary.js";
21
21
  import { uniroot } from "../internal/uniroot.js";
22
+ import { reported, Warnings } from "../internal/warnings.js";
22
23
  import { checkAnsariExactSize, pansariExact, qansariR } from "./core/ansari.js";
23
24
  import { twoGroupData } from "./testFormula.js";
24
25
  import { checkConfLevelOpen, matchAlternative } from "./types.js";
25
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"];
26
30
  export function ansariTest(x, y, options = {}) {
31
+ checkOptions(options, ANSARI_TEST_KEYS, "ansariTest"); // generated: option-keys.mjs
27
32
  if (typeof x === "string") {
28
33
  const d = twoGroupData(x, y);
29
34
  return ansariTest(d.x, d.y, options);
@@ -49,6 +54,10 @@ export function ansariTest(x, y, options = {}) {
49
54
  statistic += a[i];
50
55
  const ties = new Set(r).size < N;
51
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();
52
61
  let pValue;
53
62
  let ci;
54
63
  if (exact && !ties) {
@@ -67,7 +76,7 @@ export function ansariTest(x, y, options = {}) {
67
76
  else
68
77
  pValue = lowerTo(statistic);
69
78
  if (confInt)
70
- ci = exactInterval(xs, ys, alternative, confLevel);
79
+ ci = exactInterval(xs, ys, alternative, confLevel, warnings);
71
80
  }
72
81
  else {
73
82
  // mean and variance with the sum of the scores at its value without ties (N (N + 2) / 4 for even N,
@@ -88,8 +97,14 @@ export function ansariTest(x, y, options = {}) {
88
97
  : alternative === "less"
89
98
  ? pnorm(z, { lowerTail: false })
90
99
  : pnorm(z);
100
+ // (the interval R does not compute, with ties and exactR, gives none of its warnings)
91
101
  if (confInt)
92
- 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
+ }
93
108
  }
94
109
  const result = {
95
110
  method: "Ansari-Bradley test",
@@ -97,6 +112,7 @@ export function ansariTest(x, y, options = {}) {
97
112
  statistic,
98
113
  statisticName: "AB",
99
114
  pValue,
115
+ warnings: warnings.list,
100
116
  };
101
117
  if (ci !== undefined) {
102
118
  result.confInt = ci.confInt;
@@ -106,7 +122,7 @@ export function ansariTest(x, y, options = {}) {
106
122
  }
107
123
  result.nullValue = 1;
108
124
  result.nullValueName = "ratio of scales";
109
- return result;
125
+ return reported("ansariTest", result);
110
126
  }
111
127
  /** AB statistic of x / s against y, with the scores of all observations and whether there are ties */
112
128
  function scaledStatistic(xs, ys, s) {
@@ -193,7 +209,7 @@ function shapeInterval(alternative, a, limits) {
193
209
  return [0, limits(2 * a)[1]];
194
210
  }
195
211
  /** Exact interval and estimate from the candidate ratios x_i / y_j >= 0 */
196
- function exactInterval(xs, ys, alternative, confLevel) {
212
+ function exactInterval(xs, ys, alternative, confLevel, warnings) {
197
213
  const m = xs.length;
198
214
  const n = ys.length;
199
215
  const sigma = [];
@@ -203,8 +219,11 @@ function exactInterval(xs, ys, alternative, confLevel) {
203
219
  sigma.push(x / y);
204
220
  sigma.sort((p, q) => p - q);
205
221
  const L = sigma.length;
206
- if (L === 0)
222
+ // (R then stops: "object 'absigma' not found")
223
+ if (L === 0) {
224
+ warnings.add("cannot compute confidence set, returning NA");
207
225
  return { confInt: shapeInterval(alternative, 1 - confLevel, () => [NaN, NaN]), estimate: NaN };
226
+ }
208
227
  // AB between consecutive candidates, and at 2.01 times the largest
209
228
  const abs = sigma.map((v, k) => scaledStatistic(xs, ys, v + (k < L - 1 ? (sigma[k + 1] - v) / 2 : v * 1.01)).ab);
210
229
  // the largest candidate with the smallest positive AB - q (or the smallest with the smallest AB - q >= 0)
@@ -223,8 +242,10 @@ function exactInterval(xs, ys, alternative, confLevel) {
223
242
  const limits = (alpha) => {
224
243
  const qLow = qansariR(alpha / 2, m, n);
225
244
  const qHigh = qansariR(1 - alpha / 2, m, n);
226
- 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");
227
247
  return [NaN, NaN];
248
+ }
228
249
  const lower = crossing(qLow, false, false);
229
250
  const upper = crossing(qHigh, true, true);
230
251
  // AB need not be monotone in s: if the limits come out in the wrong order, the quantiles are interchanged
@@ -250,7 +271,7 @@ function exactInterval(xs, ys, alternative, confLevel) {
250
271
  return { confInt, estimate };
251
272
  }
252
273
  /** Normal-approximation interval and estimate (undefined when the search range is not finite, NaN when it is empty) */
253
- function normalInterval(xs, ys, alternative, confLevel) {
274
+ function normalInterval(xs, ys, alternative, confLevel, warnings) {
254
275
  const m = xs.length;
255
276
  const n = ys.length;
256
277
  const N = m + n;
@@ -283,26 +304,36 @@ function normalInterval(xs, ys, alternative, confLevel) {
283
304
  };
284
305
  range(xs.filter((v) => v > 0), ys.filter((v) => v > 0));
285
306
  range(xs.filter((v) => v <= 0), ys.filter((v) => v < 0));
286
- 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");
287
309
  return undefined;
310
+ }
288
311
  // no positive ratio puts the samples across each other (all x positive and all y negative, or the reverse): the
289
312
  // limits and the estimate cannot be formed, as in the exact path (R stops with "invalid 'xmin' value" after its
290
- // "samples differ in location ... returning NA" warning) (#506)
291
- if (ends.length === 0)
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");
292
317
  return { confInt: shapeInterval(alternative, 1 - confLevel, () => [NaN, NaN]), estimate: NaN };
318
+ }
293
319
  const lo = minOf(ends);
294
320
  const hi = maxOf(ends);
295
321
  const root = (zq) => uniroot((s) => z(s, zq), lo, hi, { tol: 1e-4 });
296
322
  const limits = (alpha) => {
297
323
  const zLow = qnorm(alpha / 2);
298
324
  const zHigh = qnorm(alpha / 2, { lowerTail: false });
299
- 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");
300
327
  return [NaN, NaN];
328
+ }
301
329
  const u = root(zLow);
302
330
  const l = root(zHigh);
303
331
  return u <= l ? [u, l] : [l, u];
304
332
  };
305
333
  const confInt = shapeInterval(alternative, 1 - confLevel, limits);
306
- 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);
307
338
  return { confInt, estimate };
308
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,6 +42,19 @@ 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
  *
@@ -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
package/dist/htest/aov.js CHANGED
@@ -1,11 +1,12 @@
1
- // One-way analysis of variance (the table of R's summary(aov(y ~ g))), aov from a model formula (the fit of
2
- // src/models/lm.ts; its table is aovSummary in src/models/anovaSequential.ts), Tukey's honest significant differences (R's
3
- // TukeyHSD) and the z test with known standard deviations (as BSDA's z.test).
1
+ // aov from a model formula or from samples (the fit of src/models/lm.ts, with samples as the model y ~ g; its table
2
+ // is aovSummary in src/models/anovaSequential.ts), the one-way table that leveneTest uses, Tukey's honest significant
3
+ // differences (R's TukeyHSD) and the z test with known standard deviations (as BSDA's z.test).
4
4
  //
5
- // Written for rStats.js from the textbook formulas. The sums of squares are accumulated in
6
- // double-double: between groups sum n_i (m_i - m)^2, within groups sum (x - m_i)^2, so a within sum that is exactly
7
- // 0 stays 0 (F = Inf; R's QR leaves rounding residue there). TukeyHSD uses the Tukey-Kramer standard error
8
- // sqrt(MSE / 2 (1/n_i + 1/n_j)) with the studentized range distribution for the interval and the adjusted p-value.
5
+ // Written for rStats.js from the textbook formulas. The sums of squares of the one-way table and of TukeyHSD are
6
+ // accumulated in double-double: between groups sum n_i (m_i - m)^2, within groups sum (x - m_i)^2, so a within sum
7
+ // that is exactly 0 stays 0 (F = Inf; R's QR leaves rounding residue there). TukeyHSD uses the Tukey-Kramer standard
8
+ // error sqrt(MSE / 2 (1/n_i + 1/n_j)) with the studentized range distribution for the interval and the adjusted
9
+ // p-value.
9
10
  // zTest is the textbook z test (standard error sigma / sqrt(n), or sqrt(sigma_x^2/n_x + sigma_y^2/n_y) for two
10
11
  // samples, normal quantiles for the interval around the estimate); its input checks (at least 3 observations,
11
12
  // confLevel allowed in the closed [0, 1]) follow BSDA's documented/observed behaviour, with messages of our own.
@@ -17,12 +18,20 @@ import { parseFormula, splitErrorTerms } from "../models/formula.js";
17
18
  import { aovStrataFit } from "../models/aovStrata.js";
18
19
  import { lmFormulaFit } from "../models/lm.js";
19
20
  import { design } from "../models/modelMatrix.js";
20
- import { labelledGroups, toGroups } from "./groups.js";
21
+ import { labelledGroups } from "./groups.js";
21
22
  import { checkConfLevel, matchAlternative } from "./types.js";
23
+ import { reported } from "../internal/warnings.js";
24
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
25
+ import { checkOptions } from "../internal/checkOptions.js";
26
+ import { isOptionsObject } from "../internal/optionalArgs.js";
27
+ const AOV_KEYS = ["weights", "contrasts", "levels"];
28
+ const TUKEY_HSD_KEYS = ["confLevel"];
29
+ const Z_TEST_KEYS = ["sigmaX", "sigmaY", "mu", "alternative", "confLevel"];
22
30
  export function aov(x, g, options = {}) {
31
+ checkOptions(options, AOV_KEYS, "aov"); // generated: option-keys.mjs
23
32
  if (typeof x === "string")
24
- return aovFormula(x, g, options);
25
- return aovOneway(x, g);
33
+ return reported("aov", aovFormula(x, g, options));
34
+ return reported("aov", aovGroups(x, g));
26
35
  }
27
36
  /** aov from a formula (without Error() strata) */
28
37
  function aovFormula(formula, data, options) {
@@ -34,8 +43,20 @@ function aovFormula(formula, data, options) {
34
43
  return aovStrataFit(formula, parsed, treatment, errors[0], data, options);
35
44
  return lmFormulaFit(formula, design(parsed, data, { ...options, dropUnusedLevels: true }, treatment), true);
36
45
  }
37
- function aovOneway(x, g) {
38
- const groups = toGroups(x, g);
46
+ /** aov(x, g): the fit of y ~ g, with the groups as a factor whose levels are the group labels in order */
47
+ function aovGroups(x, g) {
48
+ const { labels, groups } = labelledGroups(x, g);
49
+ if (groups.length < 2)
50
+ throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
51
+ const y = groups.flat();
52
+ const gs = groups.flatMap((s, i) => s.map(() => labels[i]));
53
+ return aovFormula("y ~ g", { y, g: gs }, { levels: { g: labels } });
54
+ }
55
+ /**
56
+ * The one-way ANOVA table of groups: the sums of squares of groupMoments (double-double, on the data scaled by a
57
+ * power of 2), so that a within sum that is exactly 0 stays 0
58
+ */
59
+ export function onewayTable(groups) {
39
60
  const k = groups.length;
40
61
  if (k < 2)
41
62
  throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
@@ -75,6 +96,9 @@ function aovOneway(x, g) {
75
96
  * @category Multiple comparisons
76
97
  */
77
98
  export function TukeyHSD(x, g, options = {}) {
99
+ if (isOptionsObject(g))
100
+ checkOptions(g, TUKEY_HSD_KEYS, "TukeyHSD"); // generated: option-keys.mjs
101
+ checkOptions(options, TUKEY_HSD_KEYS, "TukeyHSD"); // generated: option-keys.mjs
78
102
  let labels;
79
103
  if (g !== undefined && !Array.isArray(g))
80
104
  options = g;
@@ -102,7 +126,8 @@ export function TukeyHSD(x, g, options = {}) {
102
126
  const { ssWithin: ssw, mean: means, k: e } = groupMoments(groups);
103
127
  const mse = ssw / df;
104
128
  const q = qtukey(confLevel, k, df);
105
- const out = { names: [], i: [], j: [], diff: [], lwr: [], upr: [], pAdj: [] };
129
+ const pAdj = [];
130
+ const out = { names: [], i: [], j: [], diff: [], lwr: [], upr: [], pAdj, pAdjusted: pAdj, warnings: [] };
106
131
  for (let b = 0; b < k - 1; b++) {
107
132
  for (let a = b + 1; a < k; a++) {
108
133
  const diff = means[a] - means[b];
@@ -131,6 +156,9 @@ export function TukeyHSD(x, g, options = {}) {
131
156
  * @category Hypothesis tests
132
157
  */
133
158
  export function zTest(x, y, options = {}) {
159
+ if (isOptionsObject(y))
160
+ checkOptions(y, Z_TEST_KEYS, "zTest"); // generated: option-keys.mjs
161
+ checkOptions(options, Z_TEST_KEYS, "zTest"); // generated: option-keys.mjs
134
162
  let ys;
135
163
  if (y !== undefined && !ArrayBuffer.isView(y) && !Array.isArray(y))
136
164
  options = y;
@@ -209,5 +237,6 @@ export function zTest(x, y, options = {}) {
209
237
  estimateNames: twoSample ? ["mean of x", "mean of y"] : "mean of x",
210
238
  nullValue: mu,
211
239
  nullValueName: twoSample ? "difference in means" : "mean",
240
+ warnings: [],
212
241
  };
213
242
  }
@@ -11,6 +11,9 @@ import { qbeta1 } from "../distributions/beta.js";
11
11
  import { firstTrue, lastTrue } from "../internal/discrete.js";
12
12
  import { twoSum } from "../special/dd.js";
13
13
  import { checkConfLevelOpen, isCount, matchAlternative } from "./types.js";
14
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
15
+ import { checkOptions } from "../internal/checkOptions.js";
16
+ const BINOM_TEST_KEYS = ["p", "alternative", "confLevel"];
14
17
  /** Relative slack when comparing outcome probabilities with the observed one */
15
18
  const SLACK = 1 + 1e-7;
16
19
  /**
@@ -70,6 +73,8 @@ function twoSidedP(x, n, p) {
70
73
  * @category Hypothesis tests
71
74
  */
72
75
  export function binomTest(x, n, options = {}) {
76
+ checkOptions(n, BINOM_TEST_KEYS, "binomTest"); // generated: option-keys.mjs
77
+ checkOptions(options, BINOM_TEST_KEYS, "binomTest"); // generated: option-keys.mjs
73
78
  let xs;
74
79
  let ns;
75
80
  if (typeof x !== "number") {
@@ -143,5 +148,6 @@ export function binomTestCounts(xs, ns, options = {}) {
143
148
  estimateNames: "probability of success",
144
149
  nullValue: p,
145
150
  nullValueName: "probability of success",
151
+ warnings: [],
146
152
  };
147
153
  }
@@ -14,6 +14,9 @@
14
14
  import { pt1, qt1 } from "../distributions/t.js";
15
15
  import { rank } from "../internal/summary.js";
16
16
  import { checkConfLevel, matchAlternative } from "./types.js";
17
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
18
+ import { checkOptions } from "../internal/checkOptions.js";
19
+ const BRUNNER_MUNZEL_TEST_KEYS = ["alternative", "confLevel"];
17
20
  /**
18
21
  * Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
19
22
  * variances or shapes. Equivalent to `lawstat::brunner.munzel.test()` in R. `NaN` values are dropped.
@@ -34,6 +37,7 @@ import { checkConfLevel, matchAlternative } from "./types.js";
34
37
  * @category Hypothesis tests
35
38
  */
36
39
  export function brunnerMunzelTest(x, y, options = {}) {
40
+ checkOptions(options, BRUNNER_MUNZEL_TEST_KEYS, "brunnerMunzelTest"); // generated: option-keys.mjs
37
41
  const xs = Array.from(x).filter((v) => !Number.isNaN(v));
38
42
  const ys = Array.from(y).filter((v) => !Number.isNaN(v));
39
43
  const n1 = xs.length;
@@ -86,5 +90,6 @@ export function brunnerMunzelTest(x, y, options = {}) {
86
90
  confLevel,
87
91
  estimate,
88
92
  estimateNames: "P(X<Y)+.5*P(X=Y)",
93
+ warnings: [],
89
94
  };
90
95
  }
@@ -78,7 +78,9 @@ export type Factor = readonly (string | null | undefined)[];
78
78
  * Given two factor vectors (arrays of labels of the same length), tests independence in their contingency table, as
79
79
  * R's `chisq.test(x, y)`; pairs with a missing label are dropped and the levels are sorted by code point.
80
80
  *
81
- * R's warning for expected counts below 5 is not issued.
81
+ * As R, `warnings` has "Chi-squared approximation may be incorrect" where an expected count is below 5 (unless the
82
+ * p-value is simulated), and "cannot compute simulated p-value with zero marginals" where `simulatePValue` is asked for
83
+ * a table with a zero row or column sum (the ordinary test is done).
82
84
  *
83
85
  * @param x Counts, or a contingency table as an array of rows (or a factor, with `y`).
84
86
  * @param options See {@link ChisqTestOptions}.
@@ -15,7 +15,10 @@
15
15
  // observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) one at a time (the uniforms of
16
16
  // R's sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
17
17
  // (src/random/r2dtable.ts). The statistic is then the uncorrected one, and the parameter is NaN (R's NA). Tables
18
- // with a zero margin are not simulated (ordinary test), as in R
18
+ // with a zero margin are not simulated (ordinary test), as in R, with R's warning "cannot compute simulated p-value
19
+ // with zero marginals"
20
+ // - R's warning "Chi-squared approximation may be incorrect" where an expected count is below 5 and the p-value is
21
+ // not simulated
19
22
  // - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
20
23
  import { pgamma1 } from "../distributions/gamma.js";
21
24
  import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
@@ -24,6 +27,11 @@ import { ldexp, productOver, squareOver } from "../internal/summary.js";
24
27
  import { compareCodePoints } from "../models/modelFrame.js";
25
28
  import { ddAdd, ddDiv, ddMul, ddSub } from "../special/dd.js";
26
29
  import { simulatedMethod } from "./core/simulate.js";
30
+ import { reported } from "../internal/warnings.js";
31
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
32
+ import { checkOptions } from "../internal/checkOptions.js";
33
+ import { isOptionsObject } from "../internal/optionalArgs.js";
34
+ const CHISQ_TEST_KEYS = ["correct", "p", "rescaleP", "simulatePValue", "B"];
27
35
  /** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
28
36
  function ddSum(x) {
29
37
  let s = [0, 0];
@@ -35,10 +43,15 @@ function ddSum(x) {
35
43
  return Number.isFinite(plain) ? s[0] : plain;
36
44
  }
37
45
  export function chisqTest(x, yOrOptions, maybeOptions) {
46
+ if (isOptionsObject(yOrOptions))
47
+ checkOptions(yOrOptions, CHISQ_TEST_KEYS, "chisqTest"); // generated: option-keys.mjs
48
+ checkOptions(maybeOptions, CHISQ_TEST_KEYS, "chisqTest"); // generated: option-keys.mjs
38
49
  if (Array.isArray(yOrOptions))
39
- return chisqFactors(x, yOrOptions, maybeOptions ?? {});
40
- return chisqCounts(x, yOrOptions ?? {});
50
+ return reported("chisqTest", chisqFactors(x, yOrOptions, maybeOptions ?? {}));
51
+ return reported("chisqTest", chisqCounts(x, yOrOptions ?? {}));
41
52
  }
53
+ /** R's warning where an expected count is below 5 and the p-value is not simulated */
54
+ const APPROXIMATION = "Chi-squared approximation may be incorrect";
42
55
  function chisqFactors(x, y, options) {
43
56
  if (x.length !== y.length)
44
57
  throw new RangeError("'x' and 'y' must have the same length");
@@ -181,6 +194,7 @@ function goodnessOfFit(x, options) {
181
194
  expected: E,
182
195
  residuals: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Es[i]), s / 2)),
183
196
  stdres: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Vs[i]), s / 2)),
197
+ warnings: Number.isFinite(df) && E.some((e) => e < 5) ? [APPROXIMATION] : [],
184
198
  };
185
199
  }
186
200
  /**
@@ -253,6 +267,9 @@ function contingency(x, options) {
253
267
  let pValue;
254
268
  const simulate = (options.simulatePValue ?? false) && sr.every((v) => v > 0) && sc.every((v) => v > 0);
255
269
  const yates = !simulate && correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
270
+ const warnings = [];
271
+ if ((options.simulatePValue ?? false) && !simulate)
272
+ warnings.push("cannot compute simulated p-value with zero marginals");
256
273
  if (simulate) {
257
274
  // counts are integers for the simulation: the simulated tables have integer margins, and fractional observed
258
275
  // counts would be compared with them (R truncates the margins and runs it)
@@ -283,6 +300,7 @@ function contingency(x, options) {
283
300
  expected: E,
284
301
  residuals: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j]))),
285
302
  stdres: contingencyStdres(x, n, sr, sc, E, diff),
303
+ warnings: Number.isFinite(df) && E.some((r) => r.some((e) => e < 5)) ? [...warnings, APPROXIMATION] : warnings,
286
304
  };
287
305
  }
288
306
  /**
@@ -8,7 +8,8 @@ import { type Alternative, type HTest, type Sample } from "./types.js";
8
8
  */
9
9
  export type CorMethod = "pearson" | "kendall" | "spearman";
10
10
  /**
11
- * Options for {@link cor}.
11
+ * The base of {@link CorTestOptions}: the options {@link corTest} shares with the coefficient. The options of the
12
+ * exported `cor` (descriptive statistics) are {@link CovOptions}.
12
13
  *
13
14
  * @category Hypothesis tests
14
15
  */
@@ -92,6 +93,11 @@ export declare function kendall(x: readonly number[], y: readonly number[]): Ken
92
93
  * arithmetic, so results can differ from R's when r is very close to ±1, where R's own
93
94
  * value is less accurate.
94
95
  *
96
+ * As R, `warnings` has "the standard deviation is zero" where x or y is constant (the correlation is `NaN`), and
97
+ * "Cannot compute exact p-value with ties" where Kendall's or Spearman's exact p-value is asked for or the default
98
+ * but there are ties (the approximation is used), and "NaNs produced" where Spearman's t approximation has 2 pairs
99
+ * (0 degrees of freedom: the p-value is `NaN`).
100
+ *
95
101
  * @param x First sample.
96
102
  * @param y Second sample, of the same length as `x`.
97
103
  * @param options See {@link CorTestOptions}.