@numero-uno-jpn/rstats 0.15.3 → 0.16.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 (285) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +24 -4
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +12 -4
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +5 -0
  52. package/dist/distributions/f.js +32 -17
  53. package/dist/distributions/gamma.js +27 -3
  54. package/dist/distributions/geometric.js +49 -13
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +2 -1
  58. package/dist/distributions/laplace.js +27 -6
  59. package/dist/distributions/logistic.js +4 -1
  60. package/dist/distributions/lognormal.js +8 -2
  61. package/dist/distributions/multinomial.js +54 -11
  62. package/dist/distributions/nbeta.js +62 -11
  63. package/dist/distributions/nchisq.js +30 -6
  64. package/dist/distributions/negbinomial.js +94 -17
  65. package/dist/distributions/normal.js +9 -4
  66. package/dist/distributions/nt.js +392 -17
  67. package/dist/distributions/pareto.js +4 -1
  68. package/dist/distributions/poisson.js +28 -3
  69. package/dist/distributions/signrank.js +7 -4
  70. package/dist/distributions/summary.js +450 -60
  71. package/dist/distributions/triangular.js +10 -5
  72. package/dist/distributions/tukey.js +5 -2
  73. package/dist/distributions/weibull.js +10 -0
  74. package/dist/distributions/wilcox.d.ts +9 -3
  75. package/dist/distributions/wilcox.js +155 -26
  76. package/dist/distributions.js +2 -2
  77. package/dist/htest/agreement.d.ts +3 -2
  78. package/dist/htest/agreement.js +76 -14
  79. package/dist/htest/ansariTest.d.ts +6 -1
  80. package/dist/htest/ansariTest.js +75 -8
  81. package/dist/htest/aov.d.ts +1 -1
  82. package/dist/htest/aov.js +48 -34
  83. package/dist/htest/binomTest.d.ts +5 -0
  84. package/dist/htest/binomTest.js +41 -17
  85. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  86. package/dist/htest/brunnerMunzelTest.js +7 -5
  87. package/dist/htest/chisqTest.d.ts +2 -1
  88. package/dist/htest/chisqTest.js +130 -43
  89. package/dist/htest/cor.d.ts +2 -1
  90. package/dist/htest/cor.js +17 -19
  91. package/dist/htest/core/ansari.d.ts +9 -0
  92. package/dist/htest/core/ansari.js +21 -1
  93. package/dist/htest/core/kolmogorov.d.ts +25 -0
  94. package/dist/htest/core/kolmogorov.js +123 -0
  95. package/dist/htest/core/mantelhaen.js +6 -4
  96. package/dist/htest/core/shapiro.d.ts +1 -1
  97. package/dist/htest/core/shapiro.js +5 -1
  98. package/dist/htest/dunnett.js +14 -5
  99. package/dist/htest/effectSize.d.ts +2 -0
  100. package/dist/htest/effectSize.js +91 -29
  101. package/dist/htest/fisherTest.d.ts +2 -2
  102. package/dist/htest/fisherTest.js +36 -18
  103. package/dist/htest/groups.d.ts +7 -0
  104. package/dist/htest/groups.js +21 -4
  105. package/dist/htest/ksTest.d.ts +3 -1
  106. package/dist/htest/ksTest.js +23 -2
  107. package/dist/htest/leveneTest.js +19 -3
  108. package/dist/htest/mantelhaenTest.js +125 -25
  109. package/dist/htest/mcnemarTest.js +32 -11
  110. package/dist/htest/multipleComparisons.d.ts +8 -1
  111. package/dist/htest/multipleComparisons.js +44 -21
  112. package/dist/htest/normalityTests.js +44 -10
  113. package/dist/htest/onewayTest.js +96 -5
  114. package/dist/htest/pAdjust.d.ts +3 -2
  115. package/dist/htest/pAdjust.js +38 -6
  116. package/dist/htest/pairwise.d.ts +1 -1
  117. package/dist/htest/pairwise.js +17 -15
  118. package/dist/htest/poissonTest.d.ts +1 -1
  119. package/dist/htest/poissonTest.js +111 -59
  120. package/dist/htest/polycor.js +27 -7
  121. package/dist/htest/power.d.ts +11 -1
  122. package/dist/htest/power.js +112 -8
  123. package/dist/htest/propTest.js +21 -4
  124. package/dist/htest/pwr.js +121 -24
  125. package/dist/htest/rankTests.js +29 -5
  126. package/dist/htest/tTest.js +44 -21
  127. package/dist/htest/trendTests.d.ts +7 -3
  128. package/dist/htest/trendTests.js +114 -20
  129. package/dist/htest/types.d.ts +5 -0
  130. package/dist/htest/types.js +7 -0
  131. package/dist/htest/varTest.js +45 -14
  132. package/dist/htest/wilcoxTest.js +114 -21
  133. package/dist/integrate/quadpack.js +27 -5
  134. package/dist/internal/covmat.d.ts +5 -0
  135. package/dist/internal/covmat.js +20 -0
  136. package/dist/internal/ddexp.d.ts +15 -1
  137. package/dist/internal/ddexp.js +59 -6
  138. package/dist/internal/discrete.d.ts +14 -0
  139. package/dist/internal/discrete.js +78 -5
  140. package/dist/internal/extremes.d.ts +9 -0
  141. package/dist/internal/extremes.js +24 -0
  142. package/dist/internal/fround.js +13 -4
  143. package/dist/internal/integer.d.ts +9 -0
  144. package/dist/internal/integer.js +12 -0
  145. package/dist/internal/invert.js +15 -2
  146. package/dist/internal/scaledInverse.d.ts +10 -0
  147. package/dist/internal/scaledInverse.js +22 -0
  148. package/dist/internal/seq.js +15 -2
  149. package/dist/internal/summary.d.ts +90 -0
  150. package/dist/internal/summary.js +458 -39
  151. package/dist/internal/uniroot.d.ts +7 -0
  152. package/dist/internal/uniroot.js +28 -3
  153. package/dist/linalg/basic.d.ts +3 -1
  154. package/dist/linalg/basic.js +51 -7
  155. package/dist/linalg/chol.js +4 -1
  156. package/dist/linalg/dot.d.ts +29 -0
  157. package/dist/linalg/dot.js +132 -0
  158. package/dist/linalg/eigen.d.ts +6 -1
  159. package/dist/linalg/eigen.js +71 -14
  160. package/dist/linalg/expm.d.ts +3 -2
  161. package/dist/linalg/expm.js +109 -15
  162. package/dist/linalg/kappa.js +58 -10
  163. package/dist/linalg/lu.d.ts +2 -1
  164. package/dist/linalg/lu.js +35 -5
  165. package/dist/linalg/matrix.d.ts +14 -0
  166. package/dist/linalg/matrix.js +24 -0
  167. package/dist/linalg/ops.js +60 -13
  168. package/dist/linalg/qr.d.ts +2 -1
  169. package/dist/linalg/qr.js +91 -23
  170. package/dist/linalg/schur.js +11 -3
  171. package/dist/linalg/solve.d.ts +6 -1
  172. package/dist/linalg/solve.js +147 -26
  173. package/dist/linalg/svd.d.ts +9 -2
  174. package/dist/linalg/svd.js +29 -11
  175. package/dist/linalg.js +2 -2
  176. package/dist/mixed.js +4 -4
  177. package/dist/models/anovaSequential.d.ts +16 -1
  178. package/dist/models/anovaSequential.js +124 -25
  179. package/dist/models/aovEz.js +140 -30
  180. package/dist/models/aovStrata.js +55 -22
  181. package/dist/models/carAnova.d.ts +1 -1
  182. package/dist/models/carAnova.js +83 -32
  183. package/dist/models/coxph.js +148 -66
  184. package/dist/models/estimable.d.ts +15 -0
  185. package/dist/models/estimable.js +68 -0
  186. package/dist/models/formula.d.ts +1 -1
  187. package/dist/models/formula.js +26 -8
  188. package/dist/models/glm.d.ts +35 -5
  189. package/dist/models/glm.js +398 -55
  190. package/dist/models/glmAnova.js +84 -13
  191. package/dist/models/glmConfint.d.ts +1 -1
  192. package/dist/models/glmConfint.js +115 -27
  193. package/dist/models/glmFamily.d.ts +10 -0
  194. package/dist/models/glmFamily.js +244 -40
  195. package/dist/models/lm.d.ts +12 -1
  196. package/dist/models/lm.js +235 -36
  197. package/dist/models/lmer.d.ts +20 -1
  198. package/dist/models/lmer.js +109 -27
  199. package/dist/models/lmerAnova.js +37 -4
  200. package/dist/models/lmerHypotheses.d.ts +6 -2
  201. package/dist/models/lmerHypotheses.js +14 -2
  202. package/dist/models/lmerTest.d.ts +9 -2
  203. package/dist/models/lmerTest.js +64 -19
  204. package/dist/models/mauchly.d.ts +4 -1
  205. package/dist/models/mauchly.js +34 -13
  206. package/dist/models/mixedStructure.js +6 -0
  207. package/dist/models/modelFrame.js +8 -2
  208. package/dist/models/modelMatrix.d.ts +3 -1
  209. package/dist/models/modelMatrix.js +40 -15
  210. package/dist/models/scaledTables.d.ts +8 -0
  211. package/dist/models/scaledTables.js +6 -0
  212. package/dist/models/survival.d.ts +6 -1
  213. package/dist/models/survival.js +67 -27
  214. package/dist/models/tiedTimes.d.ts +2 -0
  215. package/dist/models/tiedTimes.js +34 -0
  216. package/dist/numerics/deriv.d.ts +1 -1
  217. package/dist/numerics/deriv.js +64 -8
  218. package/dist/numerics/integrate.d.ts +9 -1
  219. package/dist/numerics/integrate.js +103 -16
  220. package/dist/numerics/interp.d.ts +8 -2
  221. package/dist/numerics/interp.js +352 -50
  222. package/dist/numerics/ode.js +55 -1
  223. package/dist/numerics.js +2 -2
  224. package/dist/optim/localmin.js +4 -0
  225. package/dist/optim/optim.d.ts +3 -1
  226. package/dist/optim/optim.js +80 -8
  227. package/dist/random/beta.js +53 -4
  228. package/dist/random/binomial.d.ts +14 -3
  229. package/dist/random/binomial.js +59 -24
  230. package/dist/random/continuous.js +33 -5
  231. package/dist/random/extra.js +42 -9
  232. package/dist/random/gamma.d.ts +4 -1
  233. package/dist/random/gamma.js +36 -8
  234. package/dist/random/hyper.js +9 -6
  235. package/dist/random/mt.js +17 -2
  236. package/dist/random/poisson.js +26 -3
  237. package/dist/random/r2dtable.d.ts +8 -1
  238. package/dist/random/r2dtable.js +24 -3
  239. package/dist/random/rank.d.ts +2 -0
  240. package/dist/random/rank.js +44 -4
  241. package/dist/random/sample.d.ts +12 -2
  242. package/dist/random/sample.js +57 -20
  243. package/dist/random/streams.js +4 -2
  244. package/dist/rstats.js +14 -14
  245. package/dist/special/besselIK.d.ts +12 -0
  246. package/dist/special/besselIK.js +168 -23
  247. package/dist/special/besselJY.d.ts +11 -1
  248. package/dist/special/besselJY.js +127 -19
  249. package/dist/special/besselSeries.d.ts +27 -0
  250. package/dist/special/besselSeries.js +45 -2
  251. package/dist/special/beta.js +4 -1
  252. package/dist/special/choose.js +17 -8
  253. package/dist/special/dd.js +122 -18
  254. package/dist/special/extra.js +14 -2
  255. package/dist/special/gamma.js +11 -2
  256. package/dist/special/incbet.js +30 -4
  257. package/dist/special/incbetTemme.d.ts +7 -0
  258. package/dist/special/incbetTemme.js +45 -12
  259. package/dist/special/loader.d.ts +1 -1
  260. package/dist/special/loader.js +117 -20
  261. package/dist/special/log1pmx.js +4 -0
  262. package/dist/special.js +2 -2
  263. package/dist/tests.js +11 -11
  264. package/llms.txt +12 -6
  265. package/package.json +1 -1
  266. package/dist/chunks/chunk-3THFTB36.js +0 -2
  267. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  268. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  269. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  270. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  271. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  272. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  273. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  274. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  275. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  276. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  277. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  278. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  279. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  280. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  281. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  282. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  283. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  284. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  285. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -47,8 +47,10 @@ export interface MergeOptions {
47
47
  }
48
48
  /**
49
49
  * Join two data frames on key columns. Equivalent to R's `merge()`. For data frames: every pair of rows of x and y
50
- * with equal keys (missing keys match each other), and with `allX` / `allY` the rows without a match. Columns: the keys
51
- * (named as in x), x's other columns, y's other columns; a non-key name present in both gets the suffixes. Rows are
50
+ * with equal keys (missing keys match each other; key columns of different types are compared in their common type,
51
+ * as R's match: text, or numbers with TRUE as 1), and with `allX` / `allY` the rows without a match. Columns: the
52
+ * keys (named as in x; in the common type when rows only in y are kept), x's other columns, y's other columns; a
53
+ * non-key name present in both gets the suffixes. Rows are
52
54
  * ordered by the key unless `sort` is false (several keys: as text joined with "\r" unless `allX` or `allY`, as R
53
55
  * does); without key columns, the cross join (x varying fastest).
54
56
  *
@@ -37,7 +37,8 @@ export function pick(col, rows) {
37
37
  export function addColumn(out, name, col) {
38
38
  if (Object.hasOwn(out, name))
39
39
  throw new Error(`duplicate column name '${name}'`);
40
- out[name] = col;
40
+ // defineProperty, so that a column named "__proto__" is an own column rather than setting the prototype
41
+ Object.defineProperty(out, name, { value: col, enumerable: true, writable: true, configurable: true });
41
42
  }
42
43
  /**
43
44
  * A number as R's as.character writes it: up to 15 significant digits, in fixed notation unless the scientific one
@@ -151,8 +152,10 @@ function keyColumns(frame, names) {
151
152
  }
152
153
  /**
153
154
  * Join two data frames on key columns. Equivalent to R's `merge()`. For data frames: every pair of rows of x and y
154
- * with equal keys (missing keys match each other), and with `allX` / `allY` the rows without a match. Columns: the keys
155
- * (named as in x), x's other columns, y's other columns; a non-key name present in both gets the suffixes. Rows are
155
+ * with equal keys (missing keys match each other; key columns of different types are compared in their common type,
156
+ * as R's match: text, or numbers with TRUE as 1), and with `allX` / `allY` the rows without a match. Columns: the
157
+ * keys (named as in x; in the common type when rows only in y are kept), x's other columns, y's other columns; a
158
+ * non-key name present in both gets the suffixes. Rows are
156
159
  * ordered by the key unless `sort` is false (several keys: as text joined with "\r" unless `allX` or `allY`, as R
157
160
  * does); without key columns, the cross join (x varying fastest).
158
161
  *
@@ -194,12 +197,28 @@ export function merge(x, y, options = {}) {
194
197
  pairs.push([i, j]);
195
198
  }
196
199
  else {
200
+ // Each key column of x and y compared in their common type, as R's match: text if either holds text, numbers
201
+ // (TRUE as 1) if numbers meet logicals (merge({ id: [1] }, { id: ["1"] }) matched nothing, #82)
202
+ const common = keysX.map((cx, k) => {
203
+ const kinds = new Set([...cx, ...keysY[k]].filter((v) => !isMissing(v)).map((v) => typeof v));
204
+ if (kinds.has("string"))
205
+ return (v) => (typeof v === "string" ? v : valueText(v));
206
+ if (kinds.has("number") && kinds.has("boolean"))
207
+ return (v) => (typeof v === "boolean" ? Number(v) : v);
208
+ return (v) => v;
209
+ });
210
+ const commonAt = (cols, k, i) => {
211
+ const v = valueAt(cols[k], i);
212
+ return isMissing(v) ? MISSING_KEY : common[k](v);
213
+ };
197
214
  const keyOf = byX.length === 1
198
- ? (cols, i) => {
199
- const v = valueAt(cols[0], i);
200
- return isMissing(v) ? MISSING_KEY : v;
201
- }
202
- : (cols, i) => cols.map((c) => valueText(valueAt(c, i))).join("\r");
215
+ ? (cols, i) => commonAt(cols, 0, i)
216
+ : // Matched on the values' text, as R, but encoded unambiguously: R pastes them with "\r", so that a key
217
+ // containing "\r", or "NA" against a missing value, matches a different key
218
+ (cols, i) => JSON.stringify(cols.map((_, k) => {
219
+ const v = commonAt(cols, k, i);
220
+ return v === MISSING_KEY ? null : valueText(v);
221
+ }));
203
222
  const kx = Array.from({ length: nx }, (_, i) => keyOf(keysX, i));
204
223
  const ky = Array.from({ length: ny }, (_, j) => keyOf(keysY, j));
205
224
  const inY = new Set(ky);
@@ -228,13 +247,21 @@ export function merge(x, y, options = {}) {
228
247
  for (const j of sy.alone)
229
248
  pairs.push([-1, j]);
230
249
  }
250
+ // The key columns of the result (in the order of pairs): x's values, and y's for the rows only in y; those rows
251
+ // bring the columns to their common type, as R's rbind of the two sides does (x's type otherwise)
252
+ const yOnly = pairs.some(([i]) => i < 0);
253
+ const fromX = pairs.some(([i]) => i >= 0);
254
+ const keyCols = keysX.map((cx, k) => {
255
+ const cy = keysY[k];
256
+ // a Float64Array when the columns the values come from are (x's alone without rows only in y, #449)
257
+ const sources = fromX || !yOnly ? (yOnly ? [cx, cy] : [cx]) : [cy];
258
+ const col = gather(sources, pairs.map(([i, j]) => (i >= 0 ? [cx, i] : [cy, j])));
259
+ return yOnly ? commonType(col) : col;
260
+ });
231
261
  // Rows sorted stably by the key
232
262
  let order = pairs.map((_, r) => r);
233
263
  if (sort && byX.length > 0) {
234
- const keyValue = (r, k) => {
235
- const [i, j] = pairs[r];
236
- return i >= 0 ? valueAt(keysX[k], i) : valueAt(keysY[k], j);
237
- };
264
+ const keyValue = (r, k) => valueAt(keyCols[k], r);
238
265
  if (byX.length > 1 && !allX && !allY) {
239
266
  const text = pairs.map((_, r) => byX.map((_, k) => valueText(keyValue(r, k))).join("\r"));
240
267
  order.sort((a, b) => compareCodePoints(text[a], text[b]));
@@ -252,11 +279,7 @@ export function merge(x, y, options = {}) {
252
279
  }
253
280
  const sorted = order.map((r) => pairs[r]);
254
281
  const out = {};
255
- byX.forEach((n, k) => {
256
- const cx = keysX[k];
257
- const cy = keysY[k];
258
- addColumn(out, n, gather([cx, cy], sorted.map(([i, j]) => (i >= 0 ? [cx, i] : [cy, j]))));
259
- });
282
+ byX.forEach((n, k) => addColumn(out, n, pick(keyCols[k], order)));
260
283
  for (const n of restX) {
261
284
  const c = x[n];
262
285
  addColumn(out, nameX(n), gather([c], sorted.map(([i]) => (i >= 0 ? [c, i] : null))));
@@ -320,10 +343,25 @@ export function rbindFrames(frames) {
320
343
  for (const n of names) {
321
344
  const cols = frames.map((f) => f[n]);
322
345
  const rows = cols.flatMap((c) => Array.from({ length: c.length }, (_, i) => [c, i]));
323
- out[n] = gather(cols, rows);
346
+ addColumn(out, n, commonType(gather(cols, rows)));
324
347
  }
325
348
  return out;
326
349
  }
350
+ /**
351
+ * A column of mixed value types converted to their common type, as R's rbind does: text if any value is text
352
+ * (numbers as as.character writes them, logicals as "TRUE" / "FALSE"), otherwise numbers (TRUE as 1) when numbers
353
+ * and logicals are mixed
354
+ */
355
+ function commonType(col) {
356
+ if (col instanceof Float64Array)
357
+ return col;
358
+ const kinds = new Set(col.filter((v) => !isMissing(v)).map((v) => typeof v));
359
+ if (kinds.size < 2)
360
+ return col;
361
+ if (kinds.has("string"))
362
+ return col.map((v) => (isMissing(v) ? null : typeof v === "string" ? v : valueText(v)));
363
+ return col.map((v) => (isMissing(v) ? null : typeof v === "boolean" ? (v ? 1 : 0) : v));
364
+ }
327
365
  /**
328
366
  * Puts data frames with the same number of rows side by side. The data frame form of R's `cbind()`; see
329
367
  * {@link cbind}. A column name that occurs twice is an error (an object cannot hold two columns of the same name).
@@ -2,6 +2,7 @@
2
2
  // from the specification oracle/factanal-behaviour.md (no R code was read or used): the uniquenesses minimise the
3
3
  // likelihood criterion by L-BFGS-B (this library's optim), the loadings come from the eigendecomposition of the
4
4
  // scaled correlation matrix, and the rotations are Kaiser's varimax (normalised) and Hendrickson and White's promax.
5
+ import { checkCovmat } from "../internal/covmat.js";
5
6
  import { pchisq } from "../distributions/chisq.js";
6
7
  import { eigen } from "../linalg/eigen.js";
7
8
  import { qr, qrCoef } from "../linalg/qr.js";
@@ -54,11 +55,17 @@ const transpose = (A) => A[0].map((_, j) => A.map((r) => r[j]));
54
55
  /** Varimax rotation (normalised, eps 1e-5, at most 1000 iterations); also used by omega */
55
56
  export function varimax(L) {
56
57
  const k = L[0].length;
57
- const p = L.length;
58
58
  const len = L.map((r) => Math.sqrt(sumOnce(r.map((v) => v * v))));
59
- const X = L.map((r, i) => r.map((v) => v / len[i]));
60
- const Xt = transpose(X);
59
+ // Rows of zero loadings have no Kaiser normalisation (0/0) and say nothing about the rotation: the rotation is that
60
+ // of the other rows (as R's varimax of them), and they stay 0. R's varimax and factanal failed on them ("infinite or
61
+ // missing values in 'x'" in the SVD; issue #21)
62
+ const kept = L.flatMap((_, i) => (len[i] > 0 ? [i] : []));
63
+ const X = kept.map((i) => L[i].map((v) => v / len[i]));
64
+ const p = X.length;
61
65
  let T = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (_, j) => (i === j ? 1 : 0)));
66
+ if (p === 0)
67
+ return { loadings: L.map((r) => r.slice()), rotmat: T };
68
+ const Xt = transpose(X);
62
69
  let total = 0;
63
70
  for (let it = 0; it < 1000; it++) {
64
71
  const Z = matMul(X, T);
@@ -78,7 +85,9 @@ export function varimax(L) {
78
85
  break;
79
86
  }
80
87
  const Z = matMul(X, T);
81
- return { loadings: Z.map((r, i) => r.map((v) => v * len[i])), rotmat: T };
88
+ const loadings = L.map((r) => r.map(() => 0));
89
+ kept.forEach((i, a) => (loadings[i] = Z[a].map((v) => v * len[i])));
90
+ return { loadings, rotmat: T };
82
91
  }
83
92
  /** Promax rotation (m = 4) */
84
93
  function promax(L) {
@@ -118,6 +127,7 @@ export function factanal(x, factors, options = {}) {
118
127
  if (options.covmat !== undefined) {
119
128
  if (scores !== "none")
120
129
  throw new RangeError("requested scores without an 'x' matrix");
130
+ checkCovmat(options.covmat);
121
131
  cv = options.covmat.map((r) => r.slice());
122
132
  nObs = options.nObs ?? NaN;
123
133
  }
@@ -166,15 +176,14 @@ export function factanal(x, factors, options = {}) {
166
176
  let L = orderAndSignColumns(loadingsAt(S, psi, q)).L;
167
177
  let rotmat;
168
178
  const rotation = options.rotation ?? "varimax";
179
+ if (rotation !== "varimax" && rotation !== "promax" && rotation !== "none")
180
+ throw new RangeError(`unknown rotation '${String(rotation)}'`);
169
181
  if (rotation !== "none" && q >= 2) {
170
182
  const r = rotation === "varimax" ? varimax(L) : promax(L);
171
183
  const sorted = orderAndSignColumns(r.loadings, r.rotmat);
172
184
  L = sorted.L;
173
185
  rotmat = sorted.rot;
174
186
  }
175
- else if (rotation !== "varimax" && rotation !== "promax" && rotation !== "none") {
176
- throw new RangeError(`unknown rotation '${String(rotation)}'`);
177
- }
178
187
  let STATISTIC = NaN;
179
188
  let PVAL = NaN;
180
189
  if (!Number.isNaN(nObs) && dof > 0) {
@@ -15,11 +15,14 @@ export interface PrettyOptions {
15
15
  * towards 0 to an integer (as in R); `NaN`, a negative value or one greater than `n` is an error.
16
16
  */
17
17
  minN?: number;
18
- /** Factor applied to the cell when the range is very small. Default `0.75`. */
18
+ /** Factor applied to the cell when the range is very small. Default `0.75`. Must be finite and positive (as in R). */
19
19
  shrinkSml?: number;
20
- /** Bias towards larger units. Default `1.5`. */
20
+ /** Bias towards larger units. Default `1.5`. Must be finite and non-negative (as in R). */
21
21
  highUBias?: number;
22
- /** Bias towards 5 over 2 times a power of 10. Default `0.5 + 1.5 * highUBias`. */
22
+ /**
23
+ * Bias towards 5 over 2 times a power of 10. Default `0.5 + 1.5 * highUBias`. Must be finite and non-negative (as
24
+ * in R).
25
+ */
23
26
  u5Bias?: number;
24
27
  }
25
28
  /**
@@ -41,8 +44,8 @@ export declare function pretty(x: Sample, options?: PrettyOptions): number[];
41
44
  */
42
45
  export interface HistOptions {
43
46
  /**
44
- * Break points, a number of cells (a suggestion for pretty), or a rule: `"Sturges"` (default), `"Scott"` or
45
- * `"FD"` (Freedman-Diaconis).
47
+ * Break points (finite: an infinite or NaN one is an error), a number of cells (a suggestion for pretty), or a
48
+ * rule: `"Sturges"` (default), `"Scott"` or `"FD"` (Freedman-Diaconis).
46
49
  */
47
50
  breaks?: readonly number[] | number | "Sturges" | "Scott" | "FD" | "Freedman-Diaconis";
48
51
  /** Cells closed on the right, (a, b] (default `true`). */
@@ -11,6 +11,8 @@
11
11
  import { median, range, sd } from "./basic.js";
12
12
  import { IQR, quantile } from "./quantile.js";
13
13
  import { seqLength } from "../internal/seq.js";
14
+ import { midpoint, minOf } from "../internal/extremes.js";
15
+ import { ldexp, scaleToUnit } from "../internal/summary.js";
14
16
  /**
15
17
  * About n + 1 equally spaced "round" values (1, 2 or 5 times a power of 10) covering the range of `x`. Equivalent to
16
18
  * R's `pretty()`.
@@ -36,9 +38,17 @@ export function pretty(x, options = {}) {
36
38
  throw new RangeError("invalid 'min.n' argument");
37
39
  }
38
40
  const minN = Math.trunc(minNGiven);
41
+ // R's checks (after n and min.n): shrink.sml finite and positive, the biases finite and non-negative. A NaN or
42
+ // non-positive shrink.sml left the unit NaN, and the search for a finite multiple of it did not end (#330)
39
43
  const shrink = options.shrinkSml ?? 0.75;
44
+ if (!Number.isFinite(shrink) || shrink <= 0)
45
+ throw new RangeError("invalid 'shrink.sml' argument");
40
46
  const h = options.highUBias ?? 1.5;
47
+ if (!Number.isFinite(h) || h < 0)
48
+ throw new RangeError("invalid 'high.u.bias' argument");
41
49
  const h5 = options.u5Bias ?? 0.5 + 1.5 * h;
50
+ if (!Number.isFinite(h5) || h5 < 0)
51
+ throw new RangeError("invalid 'u5.bias' argument");
42
52
  let lo = Infinity;
43
53
  let up = -Infinity;
44
54
  for (const v of finite) {
@@ -130,15 +140,8 @@ export function pretty(x, options = {}) {
130
140
  // Step 6: the sequence, with values that are zero up to rounding set to 0
131
141
  if (k <= 0)
132
142
  return [L];
133
- let out;
134
- if (Number.isFinite(U - L))
135
- out = seqLength(L, U, k + 1);
136
- else {
137
- // U - L overflows: step by U/k - L/k instead
138
- const step = U / k - L / k;
139
- out = Array.from({ length: k + 1 }, (_, i) => L + i * step);
140
- out[k] = U;
141
- }
143
+ // seqLength works in half coordinates when U - L overflows (L + i (U/k - L/k) overflowed at interior points, #81)
144
+ const out = seqLength(L, U, k + 1);
142
145
  const delta = U / k - L / k;
143
146
  return out.map((v) => (Math.abs(v) < 1e-14 * delta ? 0 : v));
144
147
  }
@@ -151,39 +154,55 @@ function round5(v) {
151
154
  /** Suggested number of classes for the data `xs` (finite values) by the named rule */
152
155
  function classCount(xs, rule) {
153
156
  const n = xs.length;
154
- const [lo, hi] = range(xs);
155
- const r = hi - lo;
156
157
  switch (rule.toLowerCase()) {
157
158
  case "sturges":
158
159
  return Math.ceil(Math.log2(n) + 1);
159
160
  case "scott": {
160
- const h = 3.5 * sd(xs) * n ** (-1 / 3);
161
- return h > 0 ? Math.max(1, Math.ceil(r / h)) : 1;
161
+ const scott = (v) => [range(v), 3.5 * sd(v) * n ** (-1 / 3)];
162
+ let [[a, b], h] = scott(xs);
163
+ // the range or the width overflows (#230): both from the data divided by a power of 2 (the ratio is scale free)
164
+ if (!(Number.isFinite(b - a) && Number.isFinite(h)))
165
+ [[a, b], h] = scott(scaleToUnit([xs]).groups[0]);
166
+ return h > 0 ? Math.max(1, Math.ceil((b - a) / h)) : 1;
162
167
  }
163
168
  case "fd":
164
169
  case "freedman-diaconis": {
170
+ // the range and the width from the data v and the data rounded to 5 significant digits vr
171
+ const fd = (v, vr) => {
172
+ let h = 2 * IQR(vr);
173
+ for (let alpha = 1 / 8; h === 0 && alpha >= 1 / 512; alpha /= 2) {
174
+ const [qa, qb] = quantile(vr, [alpha, 1 - alpha]);
175
+ h = (qb - qa) / (1 - 2 * alpha);
176
+ }
177
+ if (h === 0)
178
+ h = 3.5 * sd(v);
179
+ return [range(v), h];
180
+ };
165
181
  const xr = xs.map(round5);
166
- let h = 2 * IQR(xr);
167
- for (let alpha = 1 / 8; h === 0 && alpha >= 1 / 512; alpha /= 2) {
168
- const [qa, qb] = quantile(xr, [alpha, 1 - alpha]);
169
- h = (qb - qa) / (1 - 2 * alpha);
182
+ let [[a, b], h] = fd(xs, xr);
183
+ // the range or the width overflows (#231): both from the data divided by a power of 2, the rounding to 5 digits
184
+ // (not scale free) done first
185
+ if (!(Number.isFinite(b - a) && Number.isFinite(h))) {
186
+ const { k } = scaleToUnit([xs]);
187
+ [[a, b], h] = fd(xs.map((v) => ldexp(v, -k)), xr.map((v) => ldexp(v, -k)));
170
188
  }
171
- if (h === 0)
172
- h = 3.5 * sd(xs);
173
- return h > 0 ? Math.ceil((r / h) * n ** (1 / 3)) : 1;
189
+ return h > 0 ? Math.ceil(((b - a) / h) * n ** (1 / 3)) : 1;
174
190
  }
175
191
  default:
176
192
  throw new RangeError("unknown 'breaks' algorithm");
177
193
  }
178
194
  }
179
- /** Reference cell size for the counting fuzz: median width (> 5 breaks), data range (<= 3), smallest positive width */
180
- function fuzzScale(br, dataRange) {
195
+ /**
196
+ * The counting fuzz, 1e-7 times a reference cell size: the median width (> 5 breaks), the data range [lo, hi] (<= 3)
197
+ * or the smallest positive width. Where the range of finite data overflows (#258), 2 (1e-7 (hi / 2 - lo / 2))
198
+ */
199
+ function fuzz(br, lo, hi) {
181
200
  const widths = br.slice(1).map((v, i) => v - br[i]);
182
201
  if (br.length > 5)
183
- return median(widths);
202
+ return 1e-7 * median(widths);
184
203
  if (br.length <= 3)
185
- return dataRange;
186
- return Math.min(...widths.filter((w) => w > 0));
204
+ return hi - lo === Infinity ? 2 * (1e-7 * (hi / 2 - lo / 2)) : 1e-7 * (hi - lo);
205
+ return 1e-7 * minOf(widths.filter((w) => w > 0));
187
206
  }
188
207
  /**
189
208
  * Histogram counts. Equivalent to R's `hist(x, plot = FALSE)`. Break points (by default pretty points over the range
@@ -204,7 +223,12 @@ export function hist(x, options = {}) {
204
223
  const spec = options.breaks ?? "Sturges";
205
224
  let br;
206
225
  if (typeof spec !== "string" && typeof spec !== "number" && spec.length > 1) {
226
+ // an infinite cell has density 0 and an infinite or NaN midpoint (R returns them; #229)
227
+ if (!spec.every(Number.isFinite))
228
+ throw new RangeError("'breaks' are not finite");
207
229
  br = [...spec].sort((a, b) => a - b);
230
+ if (br.some((v, i) => i > 0 && !(v > br[i - 1])))
231
+ throw new RangeError("'breaks' are not strictly increasing");
208
232
  }
209
233
  else {
210
234
  includeLowest = true;
@@ -222,7 +246,7 @@ export function hist(x, options = {}) {
222
246
  const nb = br.length;
223
247
  // Breaks moved by a small tolerance so that values on a break up to rounding fall on the intended side
224
248
  const [dlo, dhi] = n > 0 ? range(xs) : [0, 0];
225
- const tau = 1e-7 * fuzzScale(br, dhi - dlo);
249
+ const tau = fuzz(br, dlo, dhi);
226
250
  const f = br.map((v, i) => {
227
251
  if (right)
228
252
  return i === 0 && includeLowest ? v - tau : v + tau;
@@ -241,10 +265,26 @@ export function hist(x, options = {}) {
241
265
  }
242
266
  if (total < n)
243
267
  throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");
244
- const density = counts.map((c, i) => c / (n * (br[i + 1] - br[i])));
245
- const mids = counts.map((_, i) => 0.5 * (br[i + 1] + br[i]));
268
+ const density = counts.map((c, i) => cellDensity(c, n, br[i], br[i + 1]));
269
+ const mids = counts.map((_, i) => midpoint(br[i + 1], br[i]));
246
270
  return { breaks: br, counts, density, mids };
247
271
  }
272
+ /**
273
+ * count / (n (b - a)), R's density of the cell [a, b]. Where n (b - a) overflows for finite ends (the width itself,
274
+ * #228, or only its product with n, #259), from the width ws (b - a, or b / 2 - a / 2 = (b - a) 2^-s with s = 1 where
275
+ * the width overflows) divided by its power of 2, 2^e: count 2^-(e + s) / (n ws 2^-e). The products by powers of 2 are
276
+ * exact (count is an integer below 2^53), so the density is rounded once (also where it is subnormal). Elsewhere R's
277
+ * expression, unchanged
278
+ */
279
+ function cellDensity(count, n, a, b) {
280
+ const w = b - a;
281
+ if (!(n * w === Infinity && Number.isFinite(a) && Number.isFinite(b)))
282
+ return count / (n * w);
283
+ const s = w === Infinity ? 1 : 0;
284
+ const ws = s === 1 ? b / 2 - a / 2 : w;
285
+ const e = Math.floor(Math.log2(ws));
286
+ return ldexp(count, -(e + s)) / (n * ldexp(ws, -e));
287
+ }
248
288
  /** 0-based cell of `v` among the (shifted) breaks `f`, or -1 when it is in no cell */
249
289
  function cellOf(v, f, right, includeLowest) {
250
290
  const last = f.length - 1;
@@ -259,7 +299,7 @@ function cellOf(v, f, right, includeLowest) {
259
299
  let a = 1;
260
300
  let b = last;
261
301
  while (a < b) {
262
- const m = (a + b) >> 1;
302
+ const m = Math.floor((a + b) / 2); // not >> 1, which wraps beyond 2^31 breaks (issue #333)
263
303
  if (v <= f[m])
264
304
  b = m;
265
305
  else
@@ -275,7 +315,7 @@ function cellOf(v, f, right, includeLowest) {
275
315
  let a = 0;
276
316
  let b = last - 1;
277
317
  while (a < b) {
278
- const m = (a + b + 1) >> 1;
318
+ const m = Math.floor((a + b + 1) / 2);
279
319
  if (f[m] <= v)
280
320
  a = m;
281
321
  else
@@ -307,7 +347,7 @@ export function ecdf(x) {
307
347
  let lo = 0;
308
348
  let hi = n;
309
349
  while (lo < hi) {
310
- const mid = (lo + hi) >> 1;
350
+ const mid = Math.floor((lo + hi) / 2); // not >> 1, which wraps beyond 2^31 elements (issue #332)
311
351
  if (s[mid] <= q)
312
352
  lo = mid + 1;
313
353
  else
@@ -2,6 +2,7 @@
2
2
  //
3
3
  // Written for rStats.js (no ported code) from oracle/formulatests-behaviour.md. A value is missing when it is `null`,
4
4
  // or `NaN` (in a numeric column); a row is complete when no column of any argument is missing there.
5
+ import { addColumn } from "./dataFrames.js";
5
6
  const isMissing = (v) => v === null || (typeof v === "number" && Number.isNaN(v));
6
7
  const isVector = (x) => Array.isArray(x) || ArrayBuffer.isView(x);
7
8
  /** The columns of an argument (a vector is one column) and its number of rows */
@@ -46,7 +47,8 @@ export function naOmit(x) {
46
47
  const out = {};
47
48
  for (const [name, column] of Object.entries(x)) {
48
49
  const kept = Array.from(column).filter((_, i) => keep[i]);
49
- out[name] = column instanceof Float64Array ? Float64Array.from(kept) : kept;
50
+ // (addColumn: a column named "__proto__" stays an own column; issue #35)
51
+ addColumn(out, name, column instanceof Float64Array ? Float64Array.from(kept) : kept);
50
52
  }
51
53
  return out;
52
54
  }
@@ -7,16 +7,28 @@
7
7
  // (Joanes and Gill, The Statistician 47, 1998), type 3 (the default, as in MINITAB and BMDP) b1 = g1 ((n-1)/n)^1.5 and
8
8
  // b2 = (g2 + 3) ((n-1)/n)^2 - 3. The central moments are summed after subtracting the double-double mean.
9
9
  import { values } from "./basic.js";
10
- import { meanDD, mean as meanOf, variance } from "../internal/summary.js";
10
+ import { ldexp, meanDD, mean as meanOf, scaleToUnit, variance } from "../internal/summary.js";
11
11
  import { median } from "./basic.js";
12
- /** Central sums sum (x - mean)^2, ^3, ^4 of values without NaN */
13
- function centralSums(xs) {
12
+ import { maxOf } from "../internal/extremes.js";
13
+ /**
14
+ * Central sums sum (x - mean)^2, ^3, ^4 of values without NaN, of the data scaled by a power of 2 (exact) first, so
15
+ * that neither the deviations nor their powers overflow or underflow (R returns NaN there). The sums are those of the
16
+ * scaled deviations; only the scale-free ratios of skewness and kurtosis are taken from them. Deviations that are
17
+ * still tiny next to the values are scaled up as well.
18
+ */
19
+ function centralSums(values) {
20
+ const xs = scaleToUnit([values]).groups[0];
14
21
  const m = meanDD(xs);
22
+ const dev = xs.map((v) => v - m[0] - m[1]);
23
+ let mx = 0;
24
+ for (const d of dev)
25
+ mx = Math.max(mx, Math.abs(d));
26
+ const f = mx > 0 && (mx < 2 ** -120 || mx > 2 ** 120) ? 2 ** -Math.floor(Math.log2(mx)) : 1;
15
27
  let s2 = 0;
16
28
  let s3 = 0;
17
29
  let s4 = 0;
18
- for (const v of xs) {
19
- const d = v - m[0] - m[1];
30
+ for (const dv of dev) {
31
+ const d = dv * f;
20
32
  const d2 = d * d;
21
33
  s2 += d2;
22
34
  s3 += d2 * d;
@@ -142,10 +154,13 @@ export function modes(x) {
142
154
  * @category Descriptive statistics
143
155
  */
144
156
  export function meanAD(x, options = {}) {
145
- const xs = values(x, true);
146
157
  const c = options.center ?? "mean";
147
- const center = c === "mean" ? meanOf(xs) : c === "median" ? median(xs) : c;
148
- return meanOf(xs.map((v) => Math.abs(v - center)));
158
+ // the deviations of the values (and a given centre) scaled by a power of 2 (exact), so that they cannot overflow;
159
+ // the mean deviation is scaled back
160
+ const { groups, k } = scaleToUnit([values(x, true), typeof c === "number" ? [c] : []]);
161
+ const xs = groups[0];
162
+ const center = c === "mean" ? meanOf(xs) : c === "median" ? median(xs) : groups[1][0];
163
+ return ldexp(meanOf(xs.map((v) => Math.abs(v - center))), k);
149
164
  }
150
165
  /**
151
166
  * Coefficient of variation sd / mean (sample standard deviation). Equivalent to `DescTools::CoefVar()` in R.
@@ -162,11 +177,29 @@ export function cv(x, options = {}) {
162
177
  if (xs === undefined)
163
178
  return NaN;
164
179
  const n = xs.length;
165
- let res = Math.sqrt(variance(xs)) / meanOf(xs);
180
+ // sd and mean of the values scaled by a power of 2 (exact): their ratio has no units
181
+ const xu = scaleToUnit([xs]).groups[0];
182
+ let res = Math.sqrt(variance(xu)) / meanOf(xu);
166
183
  if (options.unbiased)
167
184
  res *= 1 - 1 / (4 * (n - 1)) + (res * res) / n + 1 / (2 * (n - 1) ** 2);
168
185
  return res;
169
186
  }
187
+ /** sqrt(sum v^2 / max(1, n - 1)), the scale of a centred column in R's scale() */
188
+ function rootMeanSquare(v) {
189
+ let ss = 0;
190
+ for (const t of v)
191
+ ss += t * t;
192
+ const mx = maxOf(v.map(Math.abs));
193
+ if ((ss === Infinity || ss < 2 ** -960) && mx > 0 && mx < Infinity) {
194
+ // The squares overflow or underflow (R's scale returns Inf or 0): sum the squares of the values divided by the
195
+ // largest
196
+ ss = 0;
197
+ for (const t of v)
198
+ ss += (t / mx) ** 2;
199
+ return Math.sqrt(ss / Math.max(1, v.length - 1)) * mx;
200
+ }
201
+ return Math.sqrt(ss / Math.max(1, v.length - 1));
202
+ }
170
203
  /**
171
204
  * Centre and scale the columns of a matrix (array of rows; a vector is one column). Equivalent to R's `scale()`.
172
205
  * `center` and `scale` report the values used (R's attributes), when any.
@@ -181,29 +214,33 @@ export function cv(x, options = {}) {
181
214
  export function scale(x, options = {}) {
182
215
  const rows = x.length > 0 && Array.isArray(x[0]) ? x.map((r) => [...r]) : Array.from(x, (v) => [v]);
183
216
  const nc = rows[0]?.length ?? 0;
217
+ if (rows.some((r) => r.length !== nc))
218
+ throw new TypeError("all rows of the matrix must have the same length");
184
219
  const col = (j) => rows.map((r) => r[j]);
185
220
  const result = { scaled: rows };
221
+ const given = rows.map((r) => r.slice());
222
+ // columns whose deviations overflow although the values and the centre are finite (the deviation of 1.5e308 from
223
+ // -5e307 is 2e308): redone below in the coordinates 2^-k
224
+ const overflowed = [];
186
225
  const c = options.center ?? true;
226
+ let center;
187
227
  if (c !== false) {
188
- const center = c === true ? Array.from({ length: nc }, (_, j) => meanOf(col(j).filter((v) => !Number.isNaN(v)))) : [...c];
228
+ center = c === true ? Array.from({ length: nc }, (_, j) => meanOf(col(j).filter((v) => !Number.isNaN(v)))) : [...c];
189
229
  if (center.length !== nc)
190
230
  throw new RangeError("length of 'center' must equal the number of columns of 'x'");
191
231
  for (const r of rows)
192
232
  for (let j = 0; j < nc; j++)
193
233
  r[j] = r[j] - center[j];
194
234
  result.center = center;
235
+ for (let j = 0; j < nc; j++) {
236
+ if (Number.isFinite(center[j]) && rows.some((r, i) => !Number.isFinite(r[j]) && Number.isFinite(given[i][j])))
237
+ overflowed.push(j);
238
+ }
195
239
  }
196
240
  const s = options.scale ?? true;
241
+ let sc;
197
242
  if (s !== false) {
198
- const sc = s === true
199
- ? Array.from({ length: nc }, (_, j) => {
200
- const v = col(j).filter((t) => !Number.isNaN(t));
201
- let ss = 0;
202
- for (const t of v)
203
- ss += t * t;
204
- return Math.sqrt(ss / Math.max(1, v.length - 1));
205
- })
206
- : [...s];
243
+ sc = s === true ? Array.from({ length: nc }, (_, j) => rootMeanSquare(col(j).filter((t) => !Number.isNaN(t)))) : [...s];
207
244
  if (sc.length !== nc)
208
245
  throw new RangeError("length of 'scale' must equal the number of columns of 'x'");
209
246
  for (const r of rows)
@@ -211,5 +248,21 @@ export function scale(x, options = {}) {
211
248
  r[j] = r[j] / sc[j];
212
249
  result.scale = sc;
213
250
  }
251
+ for (const j of overflowed) {
252
+ const k = Math.floor(Math.log2(maxOf(given.map((r) => Math.abs(r[j])).filter(Number.isFinite))));
253
+ const cs = ldexp(center[j], -k);
254
+ const d = given.map((r) => ldexp(r[j], -k) - cs);
255
+ let divisor = 1;
256
+ if (sc !== undefined) {
257
+ if (s === true) {
258
+ divisor = rootMeanSquare(d.filter((t) => !Number.isNaN(t)));
259
+ sc[j] = ldexp(divisor, k);
260
+ }
261
+ else
262
+ divisor = ldexp(sc[j], -k);
263
+ }
264
+ // without scaling the deviations go back by 2^k (one that is out of range is Infinity, as before)
265
+ rows.forEach((r, i) => (r[j] = sc === undefined ? ldexp(d[i], k) : d[i] / divisor));
266
+ }
214
267
  return result;
215
268
  }
@@ -54,7 +54,7 @@ export interface OmegaResult {
54
54
  * `option = "equal"`, `flip = TRUE`).
55
55
  *
56
56
  * @param x The data matrix (array of rows, NaN for missing values: correlations of pairwise complete observations),
57
- * or `null` with `options.covmat`.
57
+ * or `null` with `options.covmat`. At least 2 variables.
58
58
  * @param options See {@link OmegaOptions}.
59
59
  *
60
60
  * @example