@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
@@ -4,12 +4,18 @@
4
4
  // the off-diagonal residuals by L-BFGS-B (this library's optim), the oblique rotation is GPArotation's quartimin
5
5
  // with its Barzilai-Borwein step and non-monotone line search, and the general factor comes from a one-factor
6
6
  // minres analysis of the factor correlations.
7
+ import { checkCovmat } from "../internal/covmat.js";
7
8
  import { eigen } from "../linalg/eigen.js";
8
9
  import { solve } from "../linalg/solve.js";
9
10
  import { svd } from "../linalg/svd.js";
10
11
  import { optim } from "../optim/optim.js";
11
12
  import { cor } from "./cov.js";
12
13
  import { sumOnce, varimax } from "./factanal.js";
14
+ import { maxOf } from "../internal/extremes.js";
15
+ import { reported, unreported } from "../internal/warnings.js";
16
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
+ import { checkOptions } from "../internal/checkOptions.js";
18
+ const OMEGA_KEYS = ["nfactors", "covmat"];
13
19
  const EPS = 2 ** -52;
14
20
  const TWO_FACTOR_MESSAGE = "\nThree factors are required for identification -- general factor loadings set to be equal. \nProceed with caution. \nThink about redoing the analysis with alternative values of the 'option' setting.\n\n";
15
21
  const matMul = (A, B) => A.map((row) => B[0].map((_, j) => {
@@ -81,13 +87,62 @@ function minres(S0, q, warnings, messages) {
81
87
  return h + v - S[i][i];
82
88
  });
83
89
  };
84
- const fit = optim(s.map((v) => 1 - v), objective, {
85
- gr: gradient,
86
- method: "L-BFGS-B",
87
- lower: 0.005,
88
- upper: Math.max(Math.max(...s), 1),
89
- control: { fnscale: 1, parscale: new Array(p).fill(0.01) },
90
- });
90
+ // The objective's own derivative, from the first-order perturbation of the eigen pairs of S* (diagonal 1 - psi):
91
+ // de_k = -v_ik^2, dv_k = -sum_{l != k} v_l v_il v_ik / (e_k - e_l); W the off-diagonal residual, B = V'WV
92
+ const trueGradient = (psi) => {
93
+ const E = eigen(S.map((r, i) => r.map((v, j) => (i === j ? 1 - psi[i] : v))), { symmetric: true });
94
+ const e = E.values;
95
+ const V = E.vectors;
96
+ const live = e.map((v) => v >= EPS);
97
+ const et = e.map((v) => (v < EPS ? 100 * EPS : v));
98
+ const W = S.map((r, i) => r.map((v, j) => {
99
+ if (i === j)
100
+ return 0;
101
+ let m = 0;
102
+ for (let k = 0; k < q; k++)
103
+ m += et[k] * V[i][k] * V[j][k];
104
+ return v - m;
105
+ }));
106
+ const WV = matMul(W, V);
107
+ const B = (k, l) => {
108
+ let b = 0;
109
+ for (let i = 0; i < p; i++)
110
+ b += V[i][k] * WV[i][l];
111
+ return b;
112
+ };
113
+ const g = new Array(p).fill(0);
114
+ for (let k = 0; k < q; k++) {
115
+ const add = (l, r) => {
116
+ if (r === 0)
117
+ return;
118
+ const b = r * B(k, l);
119
+ for (let i = 0; i < p; i++)
120
+ g[i] += b * V[i][k] * V[i][l];
121
+ };
122
+ if (live[k])
123
+ add(k, 1);
124
+ for (let l = k + 1; l < q; l++)
125
+ add(l, 2 * (live[k] && live[l] ? 1 : (et[k] - et[l]) / (e[k] - e[l])));
126
+ for (let l = q; l < p; l++)
127
+ add(l, (2 * et[k]) / (e[k] - e[l]));
128
+ }
129
+ return g;
130
+ };
131
+ const lower = 0.005;
132
+ const bounds = { method: "L-BFGS-B", lower, upper: Math.max(maxOf(s), 1) };
133
+ const parscale = new Array(p).fill(0.01);
134
+ let fit = unreported(() => optim(s.map((v) => 1 - v), objective, { gr: gradient, ...bounds, control: { fnscale: 1, parscale } }));
135
+ // psych's gradient is that of the residual sum of squares with the diagonal (zero where the off-diagonal objective
136
+ // is stationary), so its minimum is the objective's in the interior; with a uniqueness at the lower bound the two
137
+ // part, and the fit stops short of the minimum (#83). Go on from there with the objective's own gradient
138
+ if (fit.par.some((v) => v === lower)) {
139
+ fit = unreported(() => optim(fit.par, objective, { gr: trueGradient, ...bounds, control: { fnscale: 1, parscale, factr: 1e3 } }));
140
+ }
141
+ // psych's fa goes on from the last point without a word when optim does not converge; the loadings, omegas and G6
142
+ // then come from uniquenesses that are not a minimum, so say so (the values are kept, as psych's)
143
+ if (fit.convergence !== 0) {
144
+ addMessage(warnings, `minres did not converge (optim convergence code ${fit.convergence}): examine the results carefully`);
145
+ }
91
146
  const psi = fit.par;
92
147
  let L = principalLoadings(S, psi.map((v, i) => S[i][i] - v), q, (e) => Math.max(e, 0));
93
148
  L = signColumns(L, q);
@@ -163,7 +218,7 @@ function oblimin(A) {
163
218
  else {
164
219
  alpha = 2 * alpha;
165
220
  }
166
- const target = Math.max(...values.slice(-10));
221
+ const target = maxOf(values.slice(-10));
167
222
  let trial = cur;
168
223
  let Tt = T;
169
224
  for (let i = 0; i <= 10; i++) {
@@ -187,7 +242,7 @@ function oblimin(A) {
187
242
  * `option = "equal"`, `flip = TRUE`).
188
243
  *
189
244
  * @param x The data matrix (array of rows, NaN for missing values: correlations of pairwise complete observations),
190
- * or `null` with `options.covmat`.
245
+ * or `null` with `options.covmat`. At least 2 variables.
191
246
  * @param options See {@link OmegaOptions}.
192
247
  *
193
248
  * @example
@@ -209,11 +264,13 @@ function oblimin(A) {
209
264
  * @category Agreement, reliability and factor analysis
210
265
  */
211
266
  export function omega(x, options = {}) {
267
+ checkOptions(options, OMEGA_KEYS, "omega"); // generated: option-keys.mjs
212
268
  const q = options.nfactors ?? 3;
213
269
  if (!Number.isInteger(q) || q < 1)
214
270
  throw new RangeError("'nfactors' must be a positive integer");
215
271
  let R;
216
272
  if (options.covmat !== undefined) {
273
+ checkCovmat(options.covmat);
217
274
  R = toCorrelation(options.covmat);
218
275
  }
219
276
  else {
@@ -222,6 +279,13 @@ export function omega(x, options = {}) {
222
279
  R = cor(x, undefined, { use: "pairwise.complete.obs" });
223
280
  }
224
281
  const p = R.length;
282
+ // reliability of one item is not defined: psych stops ("'x' must be an array of at least two dimensions"); here
283
+ // omegaLim was Infinity and alpha NaN (#261)
284
+ if (p < 2)
285
+ throw new RangeError(`omega needs at least 2 variables (got ${p})`);
286
+ // psych stops on a subscript out of bounds there; the cause is said instead
287
+ if (q > p)
288
+ throw new RangeError(`'nfactors' (${q}) must not exceed the number of variables (${p})`);
225
289
  const warnings = [];
226
290
  const messages = [];
227
291
  const orthog = minres(R, q, warnings, messages);
@@ -331,5 +395,5 @@ export function omega(x, options = {}) {
331
395
  };
332
396
  if (phi !== undefined)
333
397
  out.phi = phi;
334
- return out;
398
+ return reported("omega", out);
335
399
  }
@@ -10,7 +10,7 @@ export interface PivotLongerOptions {
10
10
  cols: readonly string[] | ((name: string) => boolean);
11
11
  /**
12
12
  * The columns to make from the names, one per part of the names. `".value"` marks the part that names the value
13
- * columns. Default `"name"`.
13
+ * columns. With `[]`, no columns are made from the names (namesSep and namesPattern are not used). Default `"name"`.
14
14
  */
15
15
  namesTo?: string | readonly string[];
16
16
  /** A regular expression whose match at the start of the names is removed. */
@@ -19,7 +19,11 @@ export interface PivotLongerOptions {
19
19
  namesSep?: string;
20
20
  /** A regular expression whose capture groups are the parts of the names. */
21
21
  namesPattern?: string;
22
- /** Functions applied to the parts, by `namesTo` column (the part as a string; missing parts stay missing). */
22
+ /**
23
+ * Functions applied to the parts, by `namesTo` column (the part as a string; missing parts stay missing). Own
24
+ * properties only: a `namesTo` column named toString has no transform unless one is given. The transform of
25
+ * `".value"` gives the names of the value columns, and must return strings.
26
+ */
23
27
  namesTransform?: Readonly<Record<string, (part: string) => DataValue>>;
24
28
  /** The name of the value column (without `".value"` in `namesTo`). Default `"value"`. */
25
29
  valuesTo?: string;
@@ -27,10 +31,13 @@ export interface PivotLongerOptions {
27
31
  valuesDropNa?: boolean;
28
32
  /**
29
33
  * `"fastest"` (default): the pivoted columns vary within each input row; `"slowest"`: all rows for each column in
30
- * turn.
34
+ * turn. Any other value is an error, as in tidyr.
31
35
  */
32
36
  colsVary?: "fastest" | "slowest";
33
- /** Called with each of tidyr's warnings, once per distinct warning, in order. Default: the warnings are dropped. */
37
+ /**
38
+ * Called with each of tidyr's warnings, once per distinct warning, in order. Default: the warnings go to the handler
39
+ * of {@link setWarningHandler} (none by default).
40
+ */
34
41
  onWarning?: (message: string) => void;
35
42
  }
36
43
  /**
@@ -45,13 +52,13 @@ export type PivotSummary = (values: DataValue[]) => DataValue;
45
52
  * @category Data frames
46
53
  */
47
54
  export interface PivotWiderOptions {
48
- /** The column (or columns) whose values name the new columns. Default `"name"`. */
55
+ /** The column (or columns) whose values name the new columns (at least one). Default `"name"`. */
49
56
  namesFrom?: string | readonly string[];
50
- /** The column (or columns) whose values fill the new columns. Default `"value"`. */
57
+ /** The column (or columns) whose values fill the new columns (at least one). Default `"value"`. */
51
58
  valuesFrom?: string | readonly string[];
52
59
  /**
53
60
  * The columns that identify a row of the result. Default: every column not in `namesFrom` or `valuesFrom`, in the
54
- * data's order; when given, the other columns are dropped.
61
+ * data's order; when given, the other columns are dropped (a column of `namesFrom` or `valuesFrom` is an error).
55
62
  */
56
63
  idCols?: string | readonly string[];
57
64
  /** Put before each new name. Default `""`. */
@@ -62,12 +69,20 @@ export interface PivotWiderOptions {
62
69
  namesSort?: boolean;
63
70
  /**
64
71
  * With several `valuesFrom`: `"fastest"` (default) all names for each value column; `"slowest"` each value column
65
- * for each name.
72
+ * for each name. Any other value is an error, as in tidyr.
66
73
  */
67
74
  namesVary?: "fastest" | "slowest";
68
- /** The value of a cell that no row fills, or such values by value column. Default: missing. */
75
+ /**
76
+ * The value of a cell that no row fills, or such values by value column. Default: missing. As in tidyr, it is cast
77
+ * to the type of the value column: a boolean becomes 0 or 1 in a numeric column, 0 and 1 become false and true in a
78
+ * boolean column (NaN missing); any other mix (a string with a number or a boolean) is an error.
79
+ */
69
80
  valuesFill?: DataValue | Readonly<Record<string, DataValue>>;
70
- /** Summarises the values of each filled cell, or such functions by value column. */
81
+ /**
82
+ * Summarises the values of each filled cell, or such functions by value column. As in tidyr, the results for one
83
+ * value column take one common type: booleans become 0 and 1 if any result is a number; strings mixed with numbers
84
+ * or booleans are an error.
85
+ */
71
86
  valuesFn?: PivotSummary | Readonly<Record<string, PivotSummary>>;
72
87
  }
73
88
  /**
@@ -8,11 +8,34 @@
8
8
  // its `onWarning` option.
9
9
  import { formatR } from "../htest/core/simulate.js";
10
10
  import { addColumn, compareValues, isMissing, pick, rowCount } from "./dataFrames.js";
11
+ import { reportWarnings } from "../internal/warnings.js";
12
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
13
+ import { checkOptions } from "../internal/checkOptions.js";
14
+ const PIVOT_LONGER_KEYS = /* @__PURE__ */ new Set([
15
+ "cols", "namesTo", "namesPrefix", "namesSep", "namesPattern", "namesTransform", "valuesTo", "valuesDropNa",
16
+ "colsVary", "onWarning",
17
+ ]);
18
+ const PIVOT_WIDER_KEYS = /* @__PURE__ */ new Set([
19
+ "namesFrom", "valuesFrom", "idCols", "namesPrefix", "namesSep", "namesSort", "namesVary", "valuesFill", "valuesFn",
20
+ ]);
11
21
  const nameList = (v) => (typeof v === "string" ? [v] : [...v]);
22
+ /**
23
+ * colsVary or namesVary, checked as tidyr's arg_match: exactly "fastest" or "slowest" (default "fastest"); anything
24
+ * else was taken as "fastest" (#256)
25
+ */
26
+ function varyArg(arg, v) {
27
+ if (v === undefined || v === null)
28
+ return "fastest";
29
+ if (v === "fastest" || v === "slowest")
30
+ return v;
31
+ if (typeof v !== "string")
32
+ throw new TypeError(`\`${arg}\` must be a string or character vector.`);
33
+ throw new RangeError(`\`${arg}\` must be one of "fastest" or "slowest", not "${v}".`);
34
+ }
12
35
  function requireColumns(data, names) {
13
36
  for (const n of names)
14
37
  if (!Object.hasOwn(data, n))
15
- throw new Error(`Column \`${n}\` doesn't exist.`);
38
+ throw new RangeError(`Column \`${n}\` doesn't exist.`);
16
39
  }
17
40
  /** The type of a column; `null` for an array of missing values only (which combines with any type) */
18
41
  function columnType(name, col) {
@@ -52,28 +75,48 @@ function commonType(data, sources) {
52
75
  function captures(names, pattern, count) {
53
76
  const groups = new RegExp(`${pattern}|`).exec("").length - 1;
54
77
  if (groups !== count)
55
- throw new Error(`\`regex\` should define ${count} groups; ${groups} found.`);
78
+ throw new TypeError(`\`regex\` should define ${count} groups; ${groups} found.`);
56
79
  const re = new RegExp(pattern);
57
80
  return names.map((name) => {
58
81
  const m = re.exec(name);
59
82
  return Array.from({ length: count }, (_, j) => (m === null ? null : (m[j + 1] ?? null)));
60
83
  });
61
84
  }
85
+ /** The number of UTF-16 code units of the character at i: 2 for a surrogate pair, else 1 */
86
+ function codePointLength(s, i) {
87
+ const c = s.charCodeAt(i);
88
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
89
+ const d = s.charCodeAt(i + 1);
90
+ if (d >= 0xdc00 && d <= 0xdfff)
91
+ return 2;
92
+ }
93
+ return 1;
94
+ }
62
95
  /** The names split at the separator into `count` parts, and tidyr's warnings for names with more or fewer pieces */
63
96
  function separated(names, sep, count, warnings) {
64
97
  const re = new RegExp(sep, "g");
65
98
  const extra = [];
66
99
  const short = [];
67
100
  const parts = names.map((name, i) => {
101
+ // The pieces between the matches, as tidyr (R's gregexpr(perl = TRUE) and regmatches(invert = TRUE)): after a
102
+ // zero-width match the search goes on one character later, and it stops once it reaches the end of the name. A
103
+ // character is a code point: a surrogate pair is passed whole, as stringr's str_split (#500; R's gregexpr went on
104
+ // inside the character's UTF-8 bytes and gave empty pieces)
68
105
  const pieces = [];
69
106
  let start = 0;
70
- for (const m of name.matchAll(re)) {
71
- if (m[0].length === 0)
72
- continue;
73
- pieces.push(name.slice(start, m.index));
74
- start = m.index + m[0].length;
107
+ let prev = 0;
108
+ for (;;) {
109
+ re.lastIndex = start;
110
+ const m = re.exec(name);
111
+ if (m === null)
112
+ break;
113
+ pieces.push(name.slice(prev, m.index));
114
+ prev = m.index + m[0].length;
115
+ start = m[0].length === 0 ? m.index + codePointLength(name, m.index) : prev;
116
+ if (start >= name.length)
117
+ break;
75
118
  }
76
- pieces.push(name.slice(start));
119
+ pieces.push(name.slice(prev));
77
120
  if (pieces.length > count)
78
121
  extra.push(i + 1);
79
122
  if (pieces.length < count)
@@ -87,19 +130,26 @@ function separated(names, sep, count, warnings) {
87
130
  warnings.push(`Expected ${count} pieces. Missing pieces filled with \`NA\` in ${rows(short)}.`);
88
131
  return parts;
89
132
  }
133
+ /** The transform of a `namesTo` column (own properties only: toString has no transform unless one is given, #436) */
134
+ function ownTransform(transforms, to) {
135
+ return transforms !== undefined && Object.hasOwn(transforms, to) ? transforms[to] : undefined;
136
+ }
90
137
  /** The parts of each name, one per element of `namesTo` */
91
138
  function nameParts(names, namesTo, options, warnings) {
92
139
  const { namesSep, namesPattern } = options;
140
+ // no names: no parts, and namesSep and namesPattern are not used (as tidyr's build_longer_spec)
141
+ if (namesTo.length === 0)
142
+ return names.map(() => []);
93
143
  if (namesTo.length === 1) {
94
144
  if (namesSep !== undefined)
95
- throw new Error("`names_sep` can't be used with a length 1 `names_to`.");
145
+ throw new TypeError("`names_sep` can't be used with a length 1 `names_to`.");
96
146
  if (namesPattern === undefined)
97
147
  return names.map((n) => [n]);
98
- const re = new RegExp(namesPattern);
99
- return names.map((n) => [re.exec(n)?.[1] ?? null]);
148
+ // exactly one capture group, as tidyr (no group gave null parts, a second group was ignored, #255)
149
+ return captures(names, namesPattern, 1);
100
150
  }
101
151
  if ((namesSep === undefined) === (namesPattern === undefined)) {
102
- throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");
152
+ throw new TypeError("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");
103
153
  }
104
154
  return namesSep !== undefined
105
155
  ? separated(names, namesSep, namesTo.length, warnings)
@@ -121,16 +171,18 @@ function nameParts(names, namesTo, options, warnings) {
121
171
  * @category Data frames
122
172
  */
123
173
  export function pivotLonger(data, options) {
174
+ checkOptions(options, PIVOT_LONGER_KEYS, "pivotLonger"); // generated: option-keys.mjs
175
+ const colsVary = varyArg("cols_vary", options.colsVary);
124
176
  const n = rowCount(data);
125
177
  const allNames = Object.keys(data);
126
178
  const cols = typeof options.cols === "function" ? allNames.filter(options.cols) : [...new Set(options.cols)];
127
179
  requireColumns(data, cols);
128
180
  if (cols.length === 0)
129
- throw new Error("`cols` must select at least one column.");
181
+ throw new RangeError("`cols` must select at least one column.");
130
182
  const namesTo = nameList(options.namesTo ?? "name");
131
183
  const valuePosition = namesTo.indexOf(".value");
132
184
  if (namesTo.lastIndexOf(".value") !== valuePosition)
133
- throw new Error('`names_to` may contain ".value" only once');
185
+ throw new RangeError('`names_to` may contain ".value" only once');
134
186
  const warnings = [];
135
187
  const prefix = options.namesPrefix === undefined ? null : new RegExp(`^(?:${options.namesPrefix})`);
136
188
  const stripped = cols.map((c) => (prefix === null ? c : c.replace(prefix, "")));
@@ -145,6 +197,7 @@ export function pivotLonger(data, options) {
145
197
  else {
146
198
  const keyIndex = new Map();
147
199
  const valueIndex = new Map();
200
+ const valueTransform = ownTransform(options.namesTransform, ".value");
148
201
  parts.forEach((p, c) => {
149
202
  const key = p.filter((_, j) => j !== valuePosition);
150
203
  const id = JSON.stringify(key);
@@ -156,7 +209,13 @@ export function pivotLonger(data, options) {
156
209
  for (const v of values)
157
210
  v.sources.push(null);
158
211
  }
159
- const name = p[valuePosition] ?? "NA";
212
+ // the transform of ".value" names the value columns, as tidyr (missing parts stay missing)
213
+ const part = p[valuePosition] ?? null;
214
+ const transformed = part === null || valueTransform === undefined ? part : valueTransform(part);
215
+ if (transformed !== null && typeof transformed !== "string") {
216
+ throw new TypeError(`the transform of \`.value\` must give strings, not ${typeof transformed}`);
217
+ }
218
+ const name = transformed ?? "NA";
160
219
  let value = valueIndex.get(name);
161
220
  if (value === undefined) {
162
221
  value = { name, sources: keys.map(() => null) };
@@ -164,14 +223,14 @@ export function pivotLonger(data, options) {
164
223
  values.push(value);
165
224
  }
166
225
  if (value.sources[k] !== null)
167
- throw new Error(`the names give the value column '${name}' twice for one key`);
226
+ throw new RangeError(`the names give the value column '${name}' twice for one key`);
168
227
  value.sources[k] = cols[c];
169
228
  });
170
229
  }
171
230
  const types = values.map((v) => commonType(data, v.sources.filter((s) => s !== null)));
172
231
  // Rows of the result: [input row, key]
173
232
  let rows = [];
174
- if (options.colsVary === "slowest") {
233
+ if (colsVary === "slowest") {
175
234
  for (let k = 0; k < keys.length; k++)
176
235
  for (let i = 0; i < n; i++)
177
236
  rows.push([i, k]);
@@ -196,7 +255,7 @@ export function pivotLonger(data, options) {
196
255
  namesTo.forEach((to, j) => {
197
256
  if (j === valuePosition)
198
257
  return;
199
- const transform = options.namesTransform?.[to];
258
+ const transform = ownTransform(options.namesTransform, to);
200
259
  const part = (k) => {
201
260
  const p = keys[k][j < valuePosition || valuePosition < 0 ? j : j - 1];
202
261
  return p === null || transform === undefined ? p : transform(p);
@@ -219,9 +278,31 @@ export function pivotLonger(data, options) {
219
278
  if (options.onWarning !== undefined)
220
279
  for (const w of new Set(warnings))
221
280
  options.onWarning(w);
281
+ else
282
+ reportWarnings("pivotLonger", warnings);
222
283
  return out;
223
284
  }
224
285
  // ---- pivotWider ----
286
+ const typeOfValue = (x) => typeof x === "number" ? "double" : typeof x === "string" ? "character" : "logical";
287
+ /** valuesFill cast to the type of the value column, as vctrs' vec_cast (a missing fill goes with any type) */
288
+ function castFill(fill, type) {
289
+ if (fill === null || type === null)
290
+ return fill;
291
+ const from = typeOfValue(fill);
292
+ if (from === type)
293
+ return fill;
294
+ if (type === "double" && from === "logical")
295
+ return Number(fill);
296
+ if (type === "logical" && from === "double") {
297
+ const x = fill;
298
+ if (Number.isNaN(x))
299
+ return null;
300
+ if (x === 0 || x === 1)
301
+ return x === 1;
302
+ throw new TypeError("Can't convert from `fill` <double> to <logical> due to loss of precision.");
303
+ }
304
+ throw new TypeError(`Can't convert \`fill\` <${from}> to <${type}>.`);
305
+ }
225
306
  /** A value as an exact key (missing values are all one key) */
226
307
  const keyOf = (v) => isMissing(v) ? "NA" : typeof v === "number" ? `n${v}` : typeof v === "string" ? `s${v}` : `b${String(v)}`;
227
308
  /**
@@ -253,11 +334,14 @@ function labelText(v) {
253
334
  return v ? "TRUE" : "FALSE";
254
335
  return v;
255
336
  }
256
- /** An option given once for all value columns or by value column */
337
+ /** An option given once for all value columns or by value column (own properties only: a column named toString or
338
+ * __proto__ has no setting unless one is given) */
257
339
  function perColumn(option, isSingle, name) {
258
340
  if (option === undefined)
259
341
  return undefined;
260
- return isSingle(option) ? option : option[name];
342
+ if (isSingle(option))
343
+ return option;
344
+ return Object.hasOwn(option, name) ? option[name] : undefined;
261
345
  }
262
346
  /**
263
347
  * Reshapes a data frame from long to wide: the values of `namesFrom` become columns, filled from `valuesFrom`.
@@ -276,13 +360,30 @@ function perColumn(option, isSingle, name) {
276
360
  * @category Data frames
277
361
  */
278
362
  export function pivotWider(data, options = {}) {
363
+ checkOptions(options, PIVOT_WIDER_KEYS, "pivotWider"); // generated: option-keys.mjs
364
+ const namesVary = varyArg("names_vary", options.namesVary);
279
365
  const n = rowCount(data);
280
- const namesFrom = nameList(options.namesFrom ?? "name");
281
- const valuesFrom = nameList(options.valuesFrom ?? "value");
366
+ // As tidyr: names_from, then values_from, each existing and not empty; then id_cols. A name given twice is
367
+ // selected once, at its first place (as tidyselect)
368
+ const selection = (v, arg) => {
369
+ const names = [...new Set(nameList(v))];
370
+ requireColumns(data, names);
371
+ if (names.length === 0)
372
+ throw new RangeError(`\`${arg}\` must select at least one column.`);
373
+ return names;
374
+ };
375
+ const namesFrom = selection(options.namesFrom ?? "name", "names_from");
376
+ const valuesFrom = selection(options.valuesFrom ?? "value", "values_from");
282
377
  const idCols = options.idCols === undefined
283
378
  ? Object.keys(data).filter((c) => !namesFrom.includes(c) && !valuesFrom.includes(c))
284
- : nameList(options.idCols);
285
- requireColumns(data, [...idCols, ...namesFrom, ...valuesFrom]);
379
+ : [...new Set(nameList(options.idCols))];
380
+ requireColumns(data, idCols);
381
+ for (const c of idCols) {
382
+ const by = namesFrom.includes(c) ? "names_from" : valuesFrom.includes(c) ? "values_from" : null;
383
+ if (by !== null) {
384
+ throw new RangeError(`\`id_cols\` can't select a column already selected by \`${by}\`. Column \`${c}\` has already been selected.`);
385
+ }
386
+ }
286
387
  const prefix = options.namesPrefix ?? "";
287
388
  const sep = options.namesSep ?? "_";
288
389
  const ids = combinations(idCols.map((c) => data[c]), n);
@@ -307,33 +408,72 @@ export function pivotWider(data, options = {}) {
307
408
  cellRows[ids.codes[i] * nNames + labels.codes[i]].push(i);
308
409
  const isSummary = (o) => typeof o === "function";
309
410
  const isFill = (o) => typeof o !== "object" || o === null;
310
- const columnOf = (value, m) => {
411
+ for (const value of valuesFrom) {
412
+ if (perColumn(options.valuesFn, isSummary, value) === undefined && cellRows.some((rows) => rows.length > 1)) {
413
+ throw new RangeError(`values from '${value}' are not uniquely identified; use valuesFn to summarise them`);
414
+ }
415
+ }
416
+ // As tidyr: the filled cells of a value column (after valuesFn, called in order of first appearance of the cell)
417
+ // have one common type over all its new columns (numbers absorb booleans, strings combine with neither), and
418
+ // valuesFill is cast to that type (#437, #445)
419
+ const typed = new Map();
420
+ for (const value of valuesFrom) {
311
421
  const source = data[value];
312
422
  const summary = perColumn(options.valuesFn, isSummary, value);
313
- const fill = perColumn(options.valuesFill, isFill, value) ?? null;
314
- const cells = ids.firsts.map((_, r) => {
315
- const rows = cellRows[r * nNames + m];
316
- if (rows.length === 0)
317
- return fill;
318
- if (summary !== undefined)
319
- return summary(rows.map((i) => source[i]));
320
- return source[rows[0]];
321
- });
322
- if (source instanceof Float64Array && cells.every((x) => x === null || typeof x === "number")) {
323
- return Float64Array.from(cells, (x) => (x === null ? NaN : x));
423
+ const cells = new Array(cellRows.length).fill(null);
424
+ let type = null;
425
+ if (summary === undefined) {
426
+ type = columnType(value, source);
427
+ cellRows.forEach((rows, c) => {
428
+ if (rows.length > 0)
429
+ cells[c] = source[rows[0]];
430
+ });
324
431
  }
325
- return cells;
326
- };
327
- for (const value of valuesFrom) {
328
- if (perColumn(options.valuesFn, isSummary, value) === undefined && cellRows.some((rows) => rows.length > 1)) {
329
- throw new Error(`values from '${value}' are not uniquely identified; use valuesFn to summarise them`);
432
+ else {
433
+ const done = new Uint8Array(cellRows.length);
434
+ let first = 0;
435
+ let k = 0;
436
+ for (let i = 0; i < n; i++) {
437
+ const c = ids.codes[i] * nNames + labels.codes[i];
438
+ if (done[c] === 1)
439
+ continue;
440
+ done[c] = 1;
441
+ k++;
442
+ const x = summary(cellRows[c].map((j) => source[j]));
443
+ cells[c] = x;
444
+ if (x === null || x === undefined)
445
+ continue;
446
+ const t = typeOfValue(x);
447
+ if (type === null || (type === "logical" && t === "double")) {
448
+ type = t;
449
+ first = k;
450
+ }
451
+ else if (t !== type && (type === "character" || t === "character")) {
452
+ throw new TypeError(`Can't combine \`x[[${first}]]\` <${type}> and \`x[[${k}]]\` <${t}>.`);
453
+ }
454
+ }
330
455
  }
456
+ const fill = castFill(perColumn(options.valuesFill, isFill, value) ?? null, type);
457
+ typed.set(value, { cells, type: type ?? (fill === null ? null : typeOfValue(fill)), fill });
331
458
  }
459
+ const columnOf = (value, m) => {
460
+ const source = data[value];
461
+ const { cells, type, fill } = typed.get(value);
462
+ const col = ids.firsts.map((_, r) => {
463
+ const c = r * nNames + m;
464
+ const x = cellRows[c].length === 0 ? fill : cells[c];
465
+ return type === "double" && typeof x === "boolean" ? Number(x) : x;
466
+ });
467
+ if (source instanceof Float64Array && (type === "double" || type === null)) {
468
+ return Float64Array.from(col, (x) => (x === null ? NaN : x));
469
+ }
470
+ return col;
471
+ };
332
472
  const out = {};
333
473
  for (const c of idCols)
334
474
  addColumn(out, c, pick(data[c], ids.firsts));
335
475
  const columnName = (value, m) => valuesFrom.length === 1 ? nameText[m] : `${value}${sep}${nameText[m]}`;
336
- if (options.namesVary === "slowest") {
476
+ if (namesVary === "slowest") {
337
477
  for (const m of nameOrder)
338
478
  for (const v of valuesFrom)
339
479
  addColumn(out, columnName(v, m), columnOf(v, m));
@@ -8,6 +8,12 @@
8
8
  // position meant to be an integer is not lost to rounding, and treat a fractional part below 4 eps as 0. fivenum is
9
9
  // Tukey's five-number summary; mad scales by 1.4826 by default.
10
10
  import { median, values } from "./basic.js";
11
+ import { midpoint } from "../internal/extremes.js";
12
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
13
+ import { checkOptions } from "../internal/checkOptions.js";
14
+ const QUANTILE_KEYS = ["type", "naRm"];
15
+ const IQR_KEYS = ["type", "naRm"];
16
+ const MAD_KEYS = ["center", "constant", "low", "high", "naRm"];
11
17
  /** Relative fuzz for the positions of types 1 to 6, 8 and 9 */
12
18
  const FUZZ = 4 * Number.EPSILON;
13
19
  /** (a, b) of the continuous types 4 to 6, 8 and 9 (Hyndman and Fan's p(k) = (k - a) / (n + 1 - a - b)) */
@@ -63,6 +69,7 @@ function quantileOfSorted(s, p, type) {
63
69
  return lower;
64
70
  }
65
71
  export function quantile(x, probs = [0, 0.25, 0.5, 0.75, 1], options = {}) {
72
+ checkOptions(options, QUANTILE_KEYS, "quantile"); // generated: option-keys.mjs
66
73
  const type = options.type ?? 7;
67
74
  if (!(Number.isInteger(type) && type >= 1 && type <= 9))
68
75
  throw new RangeError("'type' must be an integer in 1..9");
@@ -92,6 +99,7 @@ export function quantile(x, probs = [0, 0.25, 0.5, 0.75, 1], options = {}) {
92
99
  * @category Descriptive statistics
93
100
  */
94
101
  export function IQR(x, options = {}) {
102
+ checkOptions(options, IQR_KEYS, "IQR"); // generated: option-keys.mjs
95
103
  const [a, b] = quantile(x, [0.25, 0.75], options);
96
104
  return b - a;
97
105
  }
@@ -115,7 +123,7 @@ export function fivenum(x) {
115
123
  return [NaN, NaN, NaN, NaN, NaN];
116
124
  const n4 = Math.floor((n + 3) / 2) / 2;
117
125
  const d = [1, n4, (n + 1) / 2, n + 1 - n4, n];
118
- return d.map((v) => 0.5 * (s[Math.floor(v) - 1] + s[Math.ceil(v) - 1]));
126
+ return d.map((v) => midpoint(s[Math.floor(v) - 1], s[Math.ceil(v) - 1]));
119
127
  }
120
128
  /**
121
129
  * Median absolute deviation, scaled. Equivalent to R's `mad()`.
@@ -129,6 +137,7 @@ export function fivenum(x) {
129
137
  * @category Descriptive statistics
130
138
  */
131
139
  export function mad(x, options = {}) {
140
+ checkOptions(options, MAD_KEYS, "mad"); // generated: option-keys.mjs
132
141
  // Missing values stay in (and count in n) unless naRm removes them, as in R
133
142
  const given = Array.from(x);
134
143
  const xs = given.filter((v) => !Number.isNaN(v));