@numero-uno-jpn/rstats 0.10.0 → 0.11.1

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 (280) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.ja.md +13 -9
  3. package/README.md +13 -8
  4. package/dist/chunks/{chunk-QJJWGNJP.js → chunk-2X7JYQBI.js} +2 -2
  5. package/dist/chunks/{chunk-O6PT7IVU.js → chunk-36GVER3O.js} +2 -2
  6. package/dist/chunks/{chunk-EWC6I75B.js → chunk-3WUXRSM6.js} +1 -1
  7. package/dist/chunks/{chunk-4NM37MGA.js → chunk-6I6QKTFK.js} +2 -2
  8. package/dist/chunks/{chunk-2XKG3DX4.js → chunk-ETOEZTGL.js} +1 -1
  9. package/dist/chunks/{chunk-IT354SHV.js → chunk-FVPDVRJQ.js} +2 -2
  10. package/dist/chunks/{chunk-QULPY6YM.js → chunk-GG4BJMJW.js} +1 -1
  11. package/dist/chunks/{chunk-7HPVUVZB.js → chunk-HITD7CX6.js} +1 -1
  12. package/dist/chunks/{chunk-LIMZKONM.js → chunk-KK4GE65D.js} +2 -2
  13. package/dist/chunks/chunk-LAUYSGV4.js +3 -0
  14. package/dist/chunks/chunk-M6GDXKKS.js +2 -0
  15. package/dist/chunks/{chunk-QFULZNHL.js → chunk-PHHUHR7T.js} +1 -1
  16. package/dist/chunks/{chunk-ENL43FNO.js → chunk-WQPFDDIY.js} +2 -2
  17. package/dist/chunks/chunk-X2AWQSVS.js +2 -0
  18. package/dist/chunks/{chunk-ZRIM4R4A.js → chunk-ZRJQD7VS.js} +2 -2
  19. package/dist/data/grouping.d.ts +100 -0
  20. package/dist/data/grouping.js +264 -0
  21. package/dist/descriptive/basic.d.ts +130 -17
  22. package/dist/descriptive/basic.js +115 -14
  23. package/dist/descriptive/cov.d.ts +22 -12
  24. package/dist/descriptive/dataFrames.d.ts +138 -0
  25. package/dist/descriptive/dataFrames.js +400 -0
  26. package/dist/descriptive/factanal.d.ts +26 -6
  27. package/dist/descriptive/factanal.js +7 -3
  28. package/dist/descriptive/hist.d.ts +27 -6
  29. package/dist/descriptive/hist.js +9 -3
  30. package/dist/descriptive/missing.d.ts +42 -0
  31. package/dist/descriptive/missing.js +52 -0
  32. package/dist/descriptive/moments.d.ts +91 -13
  33. package/dist/descriptive/moments.js +66 -9
  34. package/dist/descriptive/omega.d.ts +28 -6
  35. package/dist/descriptive/omega.js +16 -4
  36. package/dist/descriptive/pivot.d.ts +105 -0
  37. package/dist/descriptive/pivot.js +347 -0
  38. package/dist/descriptive/quantile.d.ts +33 -5
  39. package/dist/descriptive/quantile.js +20 -2
  40. package/dist/descriptive/rank.d.ts +12 -2
  41. package/dist/descriptive/rank.js +2 -0
  42. package/dist/descriptive/table.d.ts +55 -7
  43. package/dist/descriptive/table.js +38 -4
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.d.ts +40 -5
  46. package/dist/distributions/arcsine.js +35 -4
  47. package/dist/distributions/beta.d.ts +12 -0
  48. package/dist/distributions/beta.js +12 -0
  49. package/dist/distributions/binomial.d.ts +18 -0
  50. package/dist/distributions/binomial.js +18 -0
  51. package/dist/distributions/bvnorm.d.ts +4 -1
  52. package/dist/distributions/bvnorm.js +4 -1
  53. package/dist/distributions/cauchy.d.ts +24 -0
  54. package/dist/distributions/cauchy.js +24 -0
  55. package/dist/distributions/chisq.d.ts +18 -0
  56. package/dist/distributions/chisq.js +18 -0
  57. package/dist/distributions/exponential.d.ts +29 -1
  58. package/dist/distributions/exponential.js +24 -0
  59. package/dist/distributions/f.d.ts +18 -0
  60. package/dist/distributions/f.js +18 -0
  61. package/dist/distributions/gamma.d.ts +20 -0
  62. package/dist/distributions/gamma.js +18 -0
  63. package/dist/distributions/geometric.d.ts +24 -0
  64. package/dist/distributions/geometric.js +24 -0
  65. package/dist/distributions/hypergeometric.d.ts +24 -0
  66. package/dist/distributions/hypergeometric.js +24 -0
  67. package/dist/distributions/invgamma.d.ts +32 -4
  68. package/dist/distributions/invgamma.js +27 -3
  69. package/dist/distributions/kumaraswamy.d.ts +31 -3
  70. package/dist/distributions/kumaraswamy.js +31 -3
  71. package/dist/distributions/laplace.d.ts +36 -4
  72. package/dist/distributions/laplace.js +31 -3
  73. package/dist/distributions/logistic.d.ts +29 -1
  74. package/dist/distributions/logistic.js +24 -0
  75. package/dist/distributions/lognormal.d.ts +29 -1
  76. package/dist/distributions/lognormal.js +24 -0
  77. package/dist/distributions/multinomial.d.ts +7 -1
  78. package/dist/distributions/multinomial.js +2 -0
  79. package/dist/distributions/negbinomial.d.ts +29 -1
  80. package/dist/distributions/negbinomial.js +24 -0
  81. package/dist/distributions/normal.d.ts +11 -1
  82. package/dist/distributions/normal.js +6 -0
  83. package/dist/distributions/pareto.d.ts +36 -4
  84. package/dist/distributions/pareto.js +31 -3
  85. package/dist/distributions/poisson.d.ts +18 -0
  86. package/dist/distributions/poisson.js +18 -0
  87. package/dist/distributions/signrank.d.ts +24 -0
  88. package/dist/distributions/signrank.js +24 -0
  89. package/dist/distributions/summary.d.ts +20 -2
  90. package/dist/distributions/summary.js +4 -0
  91. package/dist/distributions/t.d.ts +18 -0
  92. package/dist/distributions/t.js +18 -0
  93. package/dist/distributions/triangular.d.ts +36 -4
  94. package/dist/distributions/triangular.js +31 -3
  95. package/dist/distributions/tukey.d.ts +15 -1
  96. package/dist/distributions/tukey.js +10 -0
  97. package/dist/distributions/uniform.d.ts +29 -1
  98. package/dist/distributions/uniform.js +24 -0
  99. package/dist/distributions/weibull.d.ts +29 -1
  100. package/dist/distributions/weibull.js +24 -0
  101. package/dist/distributions/wilcox.d.ts +24 -0
  102. package/dist/distributions/wilcox.js +24 -0
  103. package/dist/distributions.js +2 -2
  104. package/dist/entries/descriptive.d.ts +5 -1
  105. package/dist/entries/descriptive.js +4 -0
  106. package/dist/entries/numerics.d.ts +1 -1
  107. package/dist/entries/tests.js +1 -1
  108. package/dist/htest/agreement.d.ts +61 -23
  109. package/dist/htest/agreement.js +19 -9
  110. package/dist/htest/ansariTest.d.ts +19 -1
  111. package/dist/htest/ansariTest.js +5 -17
  112. package/dist/htest/aov.d.ts +43 -10
  113. package/dist/htest/aov.js +17 -3
  114. package/dist/htest/binomTest.d.ts +12 -2
  115. package/dist/htest/binomTest.js +2 -0
  116. package/dist/htest/brunnerMunzelTest.d.ts +9 -3
  117. package/dist/htest/brunnerMunzelTest.js +4 -2
  118. package/dist/htest/chisqTest.d.ts +19 -3
  119. package/dist/htest/cor.d.ts +31 -3
  120. package/dist/htest/cor.js +9 -27
  121. package/dist/htest/effectSize.d.ts +70 -12
  122. package/dist/htest/effectSize.js +40 -7
  123. package/dist/htest/fisherTest.d.ts +9 -1
  124. package/dist/htest/fisherTest.js +2 -0
  125. package/dist/htest/groups.d.ts +5 -1
  126. package/dist/htest/ksTest.d.ts +32 -2
  127. package/dist/htest/ksTest.js +5 -8
  128. package/dist/htest/leveneTest.d.ts +15 -4
  129. package/dist/htest/leveneTest.js +5 -2
  130. package/dist/htest/mantelhaenTest.d.ts +25 -3
  131. package/dist/htest/mantelhaenTest.js +15 -1
  132. package/dist/htest/mcnemarTest.d.ts +14 -4
  133. package/dist/htest/mcnemarTest.js +4 -2
  134. package/dist/htest/multipleComparisons.d.ts +173 -29
  135. package/dist/htest/multipleComparisons.js +123 -19
  136. package/dist/htest/normalityTests.d.ts +56 -9
  137. package/dist/htest/normalityTests.js +40 -6
  138. package/dist/htest/onewayTest.d.ts +45 -2
  139. package/dist/htest/onewayTest.js +15 -7
  140. package/dist/htest/pAdjust.d.ts +9 -1
  141. package/dist/htest/pAdjust.js +2 -0
  142. package/dist/htest/pairwise.d.ts +50 -5
  143. package/dist/htest/pairwise.js +25 -0
  144. package/dist/htest/poissonTest.d.ts +12 -2
  145. package/dist/htest/poissonTest.js +2 -0
  146. package/dist/htest/polycor.d.ts +29 -10
  147. package/dist/htest/power.d.ts +60 -6
  148. package/dist/htest/power.js +6 -0
  149. package/dist/htest/propTest.d.ts +13 -2
  150. package/dist/htest/propTest.js +2 -0
  151. package/dist/htest/pwr.d.ts +286 -36
  152. package/dist/htest/pwr.js +116 -15
  153. package/dist/htest/rankTests.d.ts +132 -7
  154. package/dist/htest/rankTests.js +30 -33
  155. package/dist/htest/tTest.d.ts +32 -2
  156. package/dist/htest/tTest.js +19 -24
  157. package/dist/htest/testFormula.d.ts +57 -0
  158. package/dist/htest/testFormula.js +171 -0
  159. package/dist/htest/trendTests.d.ts +29 -8
  160. package/dist/htest/trendTests.js +8 -4
  161. package/dist/htest/types.d.ts +14 -2
  162. package/dist/htest/varTest.d.ts +46 -6
  163. package/dist/htest/varTest.js +11 -21
  164. package/dist/htest/wilcoxTest.d.ts +23 -1
  165. package/dist/htest/wilcoxTest.js +9 -24
  166. package/dist/internal/dpq.d.ts +4 -0
  167. package/dist/internal/noncentral.d.ts +2 -0
  168. package/dist/internal/vectorize.d.ts +4 -0
  169. package/dist/linalg/basic.d.ts +39 -5
  170. package/dist/linalg/basic.js +15 -0
  171. package/dist/linalg/chol.d.ts +26 -5
  172. package/dist/linalg/chol.js +7 -0
  173. package/dist/linalg/eigen.d.ts +16 -7
  174. package/dist/linalg/eigen.js +6 -5
  175. package/dist/linalg/expm.d.ts +15 -5
  176. package/dist/linalg/expm.js +5 -3
  177. package/dist/linalg/kappa.d.ts +21 -1
  178. package/dist/linalg/kappa.js +16 -0
  179. package/dist/linalg/lu.d.ts +30 -6
  180. package/dist/linalg/lu.js +15 -3
  181. package/dist/linalg/matrix.d.ts +4 -0
  182. package/dist/linalg/norm.d.ts +16 -1
  183. package/dist/linalg/norm.js +9 -0
  184. package/dist/linalg/ops.d.ts +168 -36
  185. package/dist/linalg/ops.js +116 -20
  186. package/dist/linalg/qr.d.ts +87 -12
  187. package/dist/linalg/qr.js +31 -0
  188. package/dist/linalg/schur.d.ts +8 -2
  189. package/dist/linalg/schur.js +3 -1
  190. package/dist/linalg/solve.d.ts +42 -6
  191. package/dist/linalg/solve.js +22 -0
  192. package/dist/linalg/svd.d.ts +12 -2
  193. package/dist/linalg/svd.js +2 -0
  194. package/dist/linalg.js +2 -2
  195. package/dist/models/anovaSequential.d.ts +26 -4
  196. package/dist/models/anovaSequential.js +3 -1
  197. package/dist/models/aovEz.d.ts +29 -6
  198. package/dist/models/aovEz.js +5 -2
  199. package/dist/models/aovStrata.d.ts +12 -2
  200. package/dist/models/carAnova.d.ts +9 -3
  201. package/dist/models/carAnova.js +4 -2
  202. package/dist/models/coxph.d.ts +33 -7
  203. package/dist/models/coxph.js +8 -3
  204. package/dist/models/glm.d.ts +128 -21
  205. package/dist/models/glm.js +71 -14
  206. package/dist/models/glmAnova.d.ts +30 -5
  207. package/dist/models/glmAnova.js +15 -2
  208. package/dist/models/glmConfint.d.ts +16 -2
  209. package/dist/models/glmConfint.js +9 -1
  210. package/dist/models/glmFamily.d.ts +27 -5
  211. package/dist/models/lm.d.ts +75 -17
  212. package/dist/models/lm.js +22 -4
  213. package/dist/models/mauchly.d.ts +20 -5
  214. package/dist/models/mauchly.js +7 -3
  215. package/dist/models/modelFrame.d.ts +5 -1
  216. package/dist/models/modelMatrix.d.ts +18 -4
  217. package/dist/models/modelMatrix.js +3 -1
  218. package/dist/models/survival.d.ts +41 -9
  219. package/dist/models/survival.js +10 -4
  220. package/dist/numerics/deriv.d.ts +21 -6
  221. package/dist/numerics/deriv.js +16 -5
  222. package/dist/numerics/integrate.d.ts +37 -7
  223. package/dist/numerics/integrate.js +8 -2
  224. package/dist/numerics/interp.d.ts +63 -12
  225. package/dist/numerics/interp.js +30 -6
  226. package/dist/numerics/ode.d.ts +15 -5
  227. package/dist/numerics/ode.js +5 -3
  228. package/dist/numerics.js +2 -2
  229. package/dist/optim/optim.d.ts +32 -8
  230. package/dist/optim/optim.js +8 -4
  231. package/dist/random/beta.d.ts +8 -0
  232. package/dist/random/beta.js +8 -0
  233. package/dist/random/binomial.d.ts +16 -0
  234. package/dist/random/binomial.js +16 -0
  235. package/dist/random/continuous.d.ts +51 -0
  236. package/dist/random/continuous.js +51 -0
  237. package/dist/random/extra.d.ts +66 -6
  238. package/dist/random/extra.js +66 -6
  239. package/dist/random/gamma.d.ts +33 -0
  240. package/dist/random/gamma.js +33 -0
  241. package/dist/random/hyper.d.ts +8 -0
  242. package/dist/random/hyper.js +8 -0
  243. package/dist/random/poisson.d.ts +25 -0
  244. package/dist/random/poisson.js +25 -0
  245. package/dist/random/r2dtable.d.ts +2 -0
  246. package/dist/random/r2dtable.js +2 -0
  247. package/dist/random/rank.d.ts +16 -0
  248. package/dist/random/rank.js +16 -0
  249. package/dist/random/rng.d.ts +49 -6
  250. package/dist/random/rng.js +29 -2
  251. package/dist/random/sample.d.ts +10 -2
  252. package/dist/random/sample.js +5 -1
  253. package/dist/random/streams.d.ts +13 -0
  254. package/dist/random/streams.js +13 -0
  255. package/dist/rstats.js +14 -14
  256. package/dist/special/besselIK.d.ts +11 -3
  257. package/dist/special/besselIK.js +6 -2
  258. package/dist/special/besselJY.d.ts +6 -2
  259. package/dist/special/besselJY.js +6 -2
  260. package/dist/special/beta.d.ts +16 -2
  261. package/dist/special/beta.js +16 -2
  262. package/dist/special/choose.d.ts +13 -5
  263. package/dist/special/choose.js +13 -5
  264. package/dist/special/erf.d.ts +8 -3
  265. package/dist/special/erf.js +8 -3
  266. package/dist/special/extra.d.ts +30 -10
  267. package/dist/special/extra.js +25 -9
  268. package/dist/special/gamma.d.ts +18 -2
  269. package/dist/special/gamma.js +18 -2
  270. package/dist/special/log1p.d.ts +16 -7
  271. package/dist/special/log1p.js +16 -7
  272. package/dist/special/psigamma.d.ts +9 -3
  273. package/dist/special/psigamma.js +9 -3
  274. package/dist/special/rCompatible.d.ts +5 -1
  275. package/dist/special.js +2 -2
  276. package/dist/tests.js +12 -13
  277. package/llms.txt +14 -0
  278. package/package.json +1 -1
  279. package/dist/chunks/chunk-AECGWZHD.js +0 -2
  280. package/dist/chunks/chunk-XWTZ4RTR.js +0 -2
@@ -0,0 +1,400 @@
1
+ // Data frame operations: R's merge (merge.data.frame), subset (subset.data.frame), and rbind and cbind of data frames;
2
+ // and fromRows / toRows, the conversion to and from arrays of row objects (not R functions).
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/dataframes-behaviour.md. A data frame is an object of columns
5
+ // (the library's DataFrame); `null`, and `NaN` in a numeric column, is a missing value. A Float64Array column stays a
6
+ // Float64Array (missing values filled in as NaN); any other column becomes an array (missing values filled in as
7
+ // null). merge reproduces R's row order exactly, including the order that R's (unstable) Shell sort of the row
8
+ // indices gives to rows that share a key.
9
+ import { compareCodePoints } from "../models/modelFrame.js";
10
+ /** The number of rows of a data frame (0 without columns); all columns must have the same length */
11
+ export function rowCount(frame) {
12
+ const cols = Object.values(frame);
13
+ const n = cols[0]?.length ?? 0;
14
+ if (cols.some((c) => c.length !== n))
15
+ throw new RangeError("the columns of a data frame must have the same length");
16
+ return n;
17
+ }
18
+ export const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
19
+ const valueAt = (col, i) => col[i];
20
+ /**
21
+ * A new column of the values of the source columns at the given rows: `rows[k]` is [column, row] or `null` for a
22
+ * missing value. A Float64Array if all sources are Float64Arrays, else an array.
23
+ */
24
+ function gather(sources, rows) {
25
+ if (sources.length > 0 && sources.every((c) => c instanceof Float64Array)) {
26
+ const out = new Float64Array(rows.length);
27
+ rows.forEach((r, k) => (out[k] = r === null ? NaN : r[0][r[1]]));
28
+ return out;
29
+ }
30
+ return rows.map((r) => (r === null ? null : valueAt(r[0], r[1])));
31
+ }
32
+ /** A copy of a column restricted to the given rows */
33
+ export function pick(col, rows) {
34
+ return col instanceof Float64Array ? Float64Array.from(rows, (i) => col[i]) : rows.map((i) => valueAt(col, i));
35
+ }
36
+ /** Adds a column to a result under construction; names must be unique */
37
+ export function addColumn(out, name, col) {
38
+ if (Object.hasOwn(out, name))
39
+ throw new Error(`duplicate column name '${name}'`);
40
+ out[name] = col;
41
+ }
42
+ /**
43
+ * A number as R's as.character writes it: up to 15 significant digits, in fixed notation unless the scientific one
44
+ * is narrower ("1e+05", "123456", "0.001", "1e-04").
45
+ */
46
+ function numberText(x) {
47
+ if (Number.isNaN(x))
48
+ return "NA";
49
+ if (!Number.isFinite(x))
50
+ return x > 0 ? "Inf" : "-Inf";
51
+ if (x === 0)
52
+ return "0";
53
+ const [mant, expPart] = Number(x.toPrecision(15)).toExponential().split("e");
54
+ const negative = mant.startsWith("-");
55
+ const digits = mant.replace("-", "").replace(".", "");
56
+ const exp = Number(expPart);
57
+ const nd = digits.length;
58
+ const expDigits = String(Math.abs(exp)).padStart(2, "0");
59
+ const sciWidth = nd + (nd > 1 ? 1 : 0) + 2 + expDigits.length;
60
+ const fixedWidth = exp >= 0 ? Math.max(exp + 1, nd) + (nd > exp + 1 ? 1 : 0) : 2 - exp - 1 + nd;
61
+ const sign = negative ? "-" : "";
62
+ if (fixedWidth > sciWidth) {
63
+ return `${sign}${digits[0]}${nd > 1 ? `.${digits.slice(1)}` : ""}e${exp < 0 ? "-" : "+"}${expDigits}`;
64
+ }
65
+ if (exp < 0)
66
+ return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
67
+ if (nd <= exp + 1)
68
+ return `${sign}${digits}${"0".repeat(exp + 1 - nd)}`;
69
+ return `${sign}${digits.slice(0, exp + 1)}.${digits.slice(exp + 1)}`;
70
+ }
71
+ /** A value as text, as in R's paste of key columns ("NA" for a missing value) */
72
+ function valueText(v) {
73
+ if (isMissing(v))
74
+ return "NA";
75
+ if (typeof v === "number")
76
+ return numberText(v);
77
+ if (typeof v === "boolean")
78
+ return v ? "TRUE" : "FALSE";
79
+ return v;
80
+ }
81
+ const MISSING_KEY = Symbol("NA");
82
+ /** The order of values of one type: numbers, then strings, then booleans (a column holds one type) */
83
+ const typeRank = (v) => (typeof v === "number" ? 0 : typeof v === "string" ? 1 : 2);
84
+ /** Comparison of two values for sorting: numbers as numbers, text by code point, FALSE before TRUE, missing last */
85
+ export function compareValues(a, b) {
86
+ const ma = isMissing(a);
87
+ const mb = isMissing(b);
88
+ if (ma || mb)
89
+ return ma === mb ? 0 : ma ? 1 : -1;
90
+ const x = a;
91
+ const y = b;
92
+ if (typeof x !== typeof y)
93
+ return typeRank(x) - typeRank(y);
94
+ if (typeof x === "string")
95
+ return compareCodePoints(x, y);
96
+ return Number(x) - Number(y);
97
+ }
98
+ /**
99
+ * The permutation that sorts `values` by R's Shell sort of row indices (Knuth's increments; not stable): 0-based
100
+ * row numbers in sorted order.
101
+ */
102
+ function shellOrder(values) {
103
+ const n = values.length;
104
+ const v = [...values];
105
+ const rows = values.map((_, i) => i);
106
+ let h = 1;
107
+ while (h <= Math.trunc(n / 9))
108
+ h = 3 * h + 1;
109
+ for (; h > 0; h = Math.trunc(h / 3)) {
110
+ for (let i = h; i < n; i++) {
111
+ const value = v[i];
112
+ const row = rows[i];
113
+ let j = i;
114
+ while (j >= h && v[j - h] > value) {
115
+ v[j] = v[j - h];
116
+ rows[j] = rows[j - h];
117
+ j -= h;
118
+ }
119
+ v[j] = value;
120
+ rows[j] = row;
121
+ }
122
+ }
123
+ return rows;
124
+ }
125
+ /** The sorted rows split into the unmatched ones (value 0) and the groups of rows with the same positive value */
126
+ function groupSorted(values) {
127
+ const alone = [];
128
+ const groups = new Map();
129
+ for (const r of shellOrder(values)) {
130
+ const v = values[r];
131
+ if (v === 0)
132
+ alone.push(r);
133
+ else {
134
+ const g = groups.get(v);
135
+ if (g === undefined)
136
+ groups.set(v, [r]);
137
+ else
138
+ g.push(r);
139
+ }
140
+ }
141
+ return { alone, groups };
142
+ }
143
+ const nameList = (v) => (typeof v === "string" ? [v] : [...v]);
144
+ /** The key columns named, each a column of the frame */
145
+ function keyColumns(frame, names) {
146
+ return names.map((n) => {
147
+ if (!Object.hasOwn(frame, n))
148
+ throw new Error("'by' must specify a uniquely valid column");
149
+ return frame[n];
150
+ });
151
+ }
152
+ /**
153
+ * 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
156
+ * ordered by the key unless `sort` is false (several keys: as text joined with "\r" unless `allX` or `allY`, as R
157
+ * does); without key columns, the cross join (x varying fastest).
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * const x = { id: [3, 1, 2], v: [10, 20, 30] };
162
+ * const y = { id: [1, 2, 2, 4], w: [0.5, 1.5, 2.5, 3.5] };
163
+ * merge(x, y); // { id: [1, 2, 2], v: [20, 30, 30], w: [0.5, 1.5, 2.5] }
164
+ * merge(x, y, { all: true }); // also id 3 (w missing) and id 4 (v missing)
165
+ * ```
166
+ *
167
+ * @category Data frames
168
+ */
169
+ export function merge(x, y, options = {}) {
170
+ const xNames = Object.keys(x);
171
+ const yNames = Object.keys(y);
172
+ const nx = rowCount(x);
173
+ const ny = rowCount(y);
174
+ const byDefault = options.by === undefined ? xNames.filter((n) => yNames.includes(n)) : nameList(options.by);
175
+ const byX = options.byX === undefined ? byDefault : nameList(options.byX);
176
+ const byY = options.byY === undefined ? byDefault : nameList(options.byY);
177
+ const keysX = keyColumns(x, byX);
178
+ const keysY = keyColumns(y, byY);
179
+ if (byX.length !== byY.length)
180
+ throw new Error("'by.x' and 'by.y' specify different numbers of columns");
181
+ const allX = options.allX ?? options.all ?? false;
182
+ const allY = options.allY ?? options.all ?? false;
183
+ const sort = options.sort ?? true;
184
+ const [suffixX, suffixY] = options.suffixes ?? [".x", ".y"];
185
+ const restX = xNames.filter((n) => !byX.includes(n));
186
+ const restY = yNames.filter((n) => !byY.includes(n));
187
+ const nameX = (n) => (restY.includes(n) ? n + suffixX : n);
188
+ const nameY = (n) => (restX.includes(n) || byX.includes(n) ? n + suffixY : n);
189
+ // Pairs of rows of the result: [x row, y row], -1 for a missing side
190
+ const pairs = [];
191
+ if (byX.length === 0) {
192
+ for (let j = 0; j < ny; j++)
193
+ for (let i = 0; i < nx; i++)
194
+ pairs.push([i, j]);
195
+ }
196
+ else {
197
+ 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");
203
+ const kx = Array.from({ length: nx }, (_, i) => keyOf(keysX, i));
204
+ const ky = Array.from({ length: ny }, (_, j) => keyOf(keysY, j));
205
+ const inY = new Set(ky);
206
+ // position (1-based) of each key's first occurrence among the x keys that occur in y (duplicates kept)
207
+ const position = new Map();
208
+ let p = 0;
209
+ for (const k of kx) {
210
+ if (!inY.has(k))
211
+ continue;
212
+ p++;
213
+ if (!position.has(k))
214
+ position.set(k, p);
215
+ }
216
+ const sx = groupSorted(kx.map((k) => position.get(k) ?? 0));
217
+ const sy = groupSorted(ky.map((k) => position.get(k) ?? 0));
218
+ for (const [value, rowsX] of sx.groups) {
219
+ const rowsY = sy.groups.get(value) ?? [];
220
+ for (const i of rowsX)
221
+ for (const j of rowsY)
222
+ pairs.push([i, j]);
223
+ }
224
+ if (allX)
225
+ for (const i of sx.alone)
226
+ pairs.push([i, -1]);
227
+ if (allY)
228
+ for (const j of sy.alone)
229
+ pairs.push([-1, j]);
230
+ }
231
+ // Rows sorted stably by the key
232
+ let order = pairs.map((_, r) => r);
233
+ 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
+ };
238
+ if (byX.length > 1 && !allX && !allY) {
239
+ const text = pairs.map((_, r) => byX.map((_, k) => valueText(keyValue(r, k))).join("\r"));
240
+ order.sort((a, b) => compareCodePoints(text[a], text[b]));
241
+ }
242
+ else {
243
+ order.sort((a, b) => {
244
+ for (let k = 0; k < byX.length; k++) {
245
+ const d = compareValues(keyValue(a, k), keyValue(b, k));
246
+ if (d !== 0)
247
+ return d;
248
+ }
249
+ return 0;
250
+ });
251
+ }
252
+ }
253
+ const sorted = order.map((r) => pairs[r]);
254
+ 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
+ });
260
+ for (const n of restX) {
261
+ const c = x[n];
262
+ addColumn(out, nameX(n), gather([c], sorted.map(([i]) => (i >= 0 ? [c, i] : null))));
263
+ }
264
+ for (const n of restY) {
265
+ const c = y[n];
266
+ addColumn(out, nameY(n), gather([c], sorted.map(([, j]) => (j >= 0 ? [c, j] : null))));
267
+ }
268
+ return out;
269
+ }
270
+ /**
271
+ * The rows of a data frame that meet a condition, and optionally some of its columns. Equivalent to R's `subset()`.
272
+ * For a data frame: `keep` is a boolean per row or a function of the row; a missing (`null`) or non-boolean result
273
+ * counts as false, as R drops the rows whose condition is NA.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * const d = { y: [5, NaN, 7, 2], g: ["a", "b", "a", "b"] };
278
+ * subset(d, (row) => (row.y as number) > 4); // { y: [5, 7], g: ["a", "a"] }
279
+ * subset(d, [true, true, false, false], { select: ["g"] }); // { g: ["a", "b"] }
280
+ * ```
281
+ *
282
+ * @category Data frames
283
+ */
284
+ export function subset(data, keep, options = {}) {
285
+ const names = Object.keys(data);
286
+ const n = rowCount(data);
287
+ if (typeof keep !== "function" && keep.length !== n) {
288
+ throw new RangeError(`'keep' has ${keep.length} values for ${n} rows`);
289
+ }
290
+ const rowAt = (i) => Object.fromEntries(names.map((c) => [c, valueAt(data[c], i)]));
291
+ const rows = [];
292
+ for (let i = 0; i < n; i++)
293
+ if ((typeof keep === "function" ? keep(rowAt(i)) : keep[i]) === true)
294
+ rows.push(i);
295
+ const select = options.select ?? names;
296
+ const out = {};
297
+ for (const c of select) {
298
+ if (!Object.hasOwn(data, c))
299
+ throw new Error("undefined columns selected");
300
+ addColumn(out, c, pick(data[c], rows));
301
+ }
302
+ return out;
303
+ }
304
+ /**
305
+ * Stacks data frames with the same column names (matched by name, in the first frame's order). The data frame form
306
+ * of R's `rbind()`; see {@link rbind}.
307
+ */
308
+ export function rbindFrames(frames) {
309
+ if (frames.length === 0)
310
+ return {};
311
+ const names = Object.keys(frames[0]);
312
+ for (const f of frames) {
313
+ rowCount(f);
314
+ const other = Object.keys(f);
315
+ if (other.length !== names.length || !names.every((n) => Object.hasOwn(f, n))) {
316
+ throw new Error("names do not match previous names");
317
+ }
318
+ }
319
+ const out = {};
320
+ for (const n of names) {
321
+ const cols = frames.map((f) => f[n]);
322
+ const rows = cols.flatMap((c) => Array.from({ length: c.length }, (_, i) => [c, i]));
323
+ out[n] = gather(cols, rows);
324
+ }
325
+ return out;
326
+ }
327
+ /**
328
+ * Puts data frames with the same number of rows side by side. The data frame form of R's `cbind()`; see
329
+ * {@link cbind}. A column name that occurs twice is an error (an object cannot hold two columns of the same name).
330
+ */
331
+ export function cbindFrames(frames) {
332
+ const out = {};
333
+ const counts = frames.map(rowCount);
334
+ const differing = counts.find((c) => c !== counts[0]);
335
+ if (differing !== undefined)
336
+ throw new RangeError(`arguments imply differing number of rows: ${counts[0]}, ${differing}`);
337
+ for (const f of frames) {
338
+ for (const [n, c] of Object.entries(f))
339
+ addColumn(out, n, c instanceof Float64Array ? Float64Array.from(c) : [...c]);
340
+ }
341
+ return out;
342
+ }
343
+ /**
344
+ * A data frame (an object of columns) from an array of row objects, the usual shape of JSON and of parsed CSV:
345
+ * `[{ age: 30, score: 5 }, { age: 41, score: 7 }]` becomes `{ age: [30, 41], score: [5, 7] }`. A key that a row
346
+ * lacks, and `undefined`, become `null` (a missing value). Values must be numbers, strings, booleans or `null`, and
347
+ * one column may not mix numbers, strings and booleans. Not an R function. R reads data as data frames directly.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * fromRows([{ id: "a", score: 5 }, { id: "b" }]); // { id: ["a", "b"], score: [5, null] }
352
+ * ```
353
+ *
354
+ * @category Data frames
355
+ */
356
+ export function fromRows(rows, options = {}) {
357
+ let names = options.columns;
358
+ if (names === undefined) {
359
+ const seen = new Set();
360
+ for (const row of rows)
361
+ for (const k of Object.keys(row))
362
+ seen.add(k);
363
+ names = [...seen];
364
+ }
365
+ const out = {};
366
+ for (const name of names) {
367
+ const kinds = new Set();
368
+ const col = rows.map((row, i) => {
369
+ const v = Object.hasOwn(row, name) ? row[name] : undefined;
370
+ if (v === undefined || v === null)
371
+ return null;
372
+ if (typeof v !== "number" && typeof v !== "string" && typeof v !== "boolean") {
373
+ throw new TypeError(`row ${i}, column '${name}': values must be numbers, strings, booleans or null`);
374
+ }
375
+ kinds.add(typeof v);
376
+ return v;
377
+ });
378
+ if (kinds.size > 1)
379
+ throw new TypeError(`column '${name}' mixes ${[...kinds].join(" and ")} values`);
380
+ addColumn(out, name, col);
381
+ }
382
+ return out;
383
+ }
384
+ /**
385
+ * The rows of a data frame as an array of objects, the inverse of {@link fromRows}: `{ age: [30, 41], score: [5, 7]
386
+ * }` becomes `[{ age: 30, score: 5 }, { age: 41, score: 7 }]`. Missing values stay as they are (`null`, or `NaN` in a
387
+ * numeric column). Not an R function. R keeps data in data frames and has no need for row objects.
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * toRows({ id: ["a", "b"], score: [5, null] }); // [{ id: "a", score: 5 }, { id: "b", score: null }]
392
+ * ```
393
+ *
394
+ * @category Data frames
395
+ */
396
+ export function toRows(data) {
397
+ const names = Object.keys(data);
398
+ const n = rowCount(data);
399
+ return Array.from({ length: n }, (_, i) => Object.fromEntries(names.map((c) => [c, valueAt(data[c], i)])));
400
+ }
@@ -1,6 +1,14 @@
1
- /** Rotations of {@link factanal} */
1
+ /**
2
+ * Rotations of {@link factanal}
3
+ *
4
+ * @category Agreement, reliability and factor analysis
5
+ */
2
6
  export type FactanalRotation = "varimax" | "promax" | "none";
3
- /** Options of {@link factanal} */
7
+ /**
8
+ * Options of {@link factanal}
9
+ *
10
+ * @category Agreement, reliability and factor analysis
11
+ */
4
12
  export interface FactanalOptions {
5
13
  /** A covariance (or correlation) matrix to analyse instead of the data `x` (pass `null` as `x`). */
6
14
  covmat?: readonly (readonly number[])[];
@@ -8,6 +16,7 @@ export interface FactanalOptions {
8
16
  nObs?: number;
9
17
  /** Default `"varimax"`. */
10
18
  rotation?: FactanalRotation;
19
+ /** Settings of the optimisation (part of R's `control` list). */
11
20
  control?: {
12
21
  /** Lower bound of the uniquenesses. Default 0.005. */
13
22
  lower?: number;
@@ -15,8 +24,13 @@ export interface FactanalOptions {
15
24
  start?: readonly number[];
16
25
  };
17
26
  }
18
- /** Result of {@link factanal} */
27
+ /**
28
+ * Result of {@link factanal}
29
+ *
30
+ * @category Agreement, reliability and factor analysis
31
+ */
19
32
  export interface FactanalResult {
33
+ /** The uniquenesses, one per variable: the variance not explained by the factors. */
20
34
  uniquenesses: number[];
21
35
  /** The (rotated) loadings, p rows by `factors` columns, columns sorted by decreasing sum of squares, each column's sum positive */
22
36
  loadings: number[][];
@@ -24,9 +38,11 @@ export interface FactanalResult {
24
38
  rotmat?: number[][];
25
39
  /** The likelihood-ratio statistic (NaN without n.obs or with no degrees of freedom) */
26
40
  STATISTIC: number;
41
+ /** Degrees of freedom of the statistic, ((p - factors)^2 - (p + factors)) / 2. */
27
42
  dof: number;
28
43
  /** Its upper chi-squared tail probability (NaN as STATISTIC) */
29
44
  PVAL: number;
45
+ /** Whether the optimisation converged. */
30
46
  converged: boolean;
31
47
  /** The minimised criterion */
32
48
  objective: number;
@@ -42,15 +58,19 @@ export declare function varimax(L: readonly (readonly number[])[]): {
42
58
  };
43
59
  /**
44
60
  * Maximum-likelihood factor analysis of a data matrix (rows are observations) or, with `options.covmat`, of a
45
- * covariance matrix. Equivalent to R's `factanal()` with `rotation` `"varimax"`, `"promax"` or `"none"`.
61
+ * covariance matrix. Equivalent to R's `factanal()`. With `rotation` `"varimax"`, `"promax"` or `"none"`.
46
62
  *
47
63
  * @param x The data matrix (array of rows), or `null` with `options.covmat`.
48
64
  * @param factors The number of factors.
49
65
  *
50
66
  * @example
51
67
  * ```ts
52
- * const fa = factanal(x, 2); // x: an n x 6 data matrix
53
- * fa.uniquenesses; fa.loadings; fa.PVAL;
68
+ * const R = [[1, 0.72, 0.63], [0.72, 1, 0.56], [0.63, 0.56, 1]];
69
+ * const fa = factanal(null, 1, { covmat: R });
70
+ * fa.uniquenesses; // [0.19, 0.36, 0.51]
71
+ * fa.loadings; // [[0.9], [0.8], [0.7]]
54
72
  * ```
73
+ *
74
+ * @category Agreement, reliability and factor analysis
55
75
  */
56
76
  export declare function factanal(x: readonly (readonly number[])[] | null, factors: number, options?: FactanalOptions): FactanalResult;
@@ -92,16 +92,20 @@ function promax(L) {
92
92
  }
93
93
  /**
94
94
  * Maximum-likelihood factor analysis of a data matrix (rows are observations) or, with `options.covmat`, of a
95
- * covariance matrix. Equivalent to R's `factanal()` with `rotation` `"varimax"`, `"promax"` or `"none"`.
95
+ * covariance matrix. Equivalent to R's `factanal()`. With `rotation` `"varimax"`, `"promax"` or `"none"`.
96
96
  *
97
97
  * @param x The data matrix (array of rows), or `null` with `options.covmat`.
98
98
  * @param factors The number of factors.
99
99
  *
100
100
  * @example
101
101
  * ```ts
102
- * const fa = factanal(x, 2); // x: an n x 6 data matrix
103
- * fa.uniquenesses; fa.loadings; fa.PVAL;
102
+ * const R = [[1, 0.72, 0.63], [0.72, 1, 0.56], [0.63, 0.56, 1]];
103
+ * const fa = factanal(null, 1, { covmat: R });
104
+ * fa.uniquenesses; // [0.19, 0.36, 0.51]
105
+ * fa.loadings; // [[0.9], [0.8], [0.7]]
104
106
  * ```
107
+ *
108
+ * @category Agreement, reliability and factor analysis
105
109
  */
106
110
  export function factanal(x, factors, options = {}) {
107
111
  let cv;
@@ -1,5 +1,9 @@
1
1
  import type { Sample } from "../htest/types.js";
2
- /** Options for {@link pretty}. */
2
+ /**
3
+ * Options for {@link pretty}.
4
+ *
5
+ * @category Descriptive statistics
6
+ */
3
7
  export interface PrettyOptions {
4
8
  /** Desired number of intervals. Default `5`. */
5
9
  n?: number;
@@ -20,9 +24,15 @@ export interface PrettyOptions {
20
24
  * ```ts
21
25
  * pretty([0.3, 9.6]); // [0, 2, 4, 6, 8, 10]
22
26
  * ```
27
+ *
28
+ * @category Descriptive statistics
23
29
  */
24
30
  export declare function pretty(x: Sample, options?: PrettyOptions): number[];
25
- /** Options for {@link hist}. */
31
+ /**
32
+ * Options for {@link hist}.
33
+ *
34
+ * @category Descriptive statistics
35
+ */
26
36
  export interface HistOptions {
27
37
  /**
28
38
  * Break points, a number of cells (a suggestion for pretty), or a rule: `"Sturges"` (default), `"Scott"` or
@@ -34,22 +44,31 @@ export interface HistOptions {
34
44
  /** Close the first cell on the left (the last on the right when `right` is false). Default `true`. */
35
45
  includeLowest?: boolean;
36
46
  }
37
- /** Result of {@link hist}. */
47
+ /**
48
+ * Result of {@link hist}.
49
+ *
50
+ * @category Descriptive statistics
51
+ */
38
52
  export interface HistResult {
53
+ /** The cell boundaries, one more than the cells. */
39
54
  breaks: number[];
55
+ /** Number of values in each cell. */
40
56
  counts: number[];
41
57
  /** counts / (n * cell width) */
42
58
  density: number[];
59
+ /** Cell midpoints. */
43
60
  mids: number[];
44
61
  }
45
62
  /**
46
- * Histogram counts. Equivalent to R's `hist(x, plot = FALSE)`: break points (by default pretty points over the range
63
+ * Histogram counts. Equivalent to R's `hist(x, plot = FALSE)`. Break points (by default pretty points over the range
47
64
  * with about Sturges' number of cells), counts, densities and cell midpoints. Non-finite values are dropped.
48
65
  *
49
66
  * @example
50
67
  * ```ts
51
- * hist([1, 2, 2, 3, 3, 3, 4]).counts; // [3, 3, 1] for breaks [1, 2, 3, 4]
68
+ * hist([1, 2, 2, 3, 3, 3, 4]).counts; // [3, 3, 1] (for breaks [1, 2, 3, 4])
52
69
  * ```
70
+ *
71
+ * @category Descriptive statistics
53
72
  */
54
73
  export declare function hist(x: Sample, options?: HistOptions): HistResult;
55
74
  /**
@@ -58,7 +77,9 @@ export declare function hist(x: Sample, options?: HistOptions): HistResult;
58
77
  *
59
78
  * @example
60
79
  * ```ts
61
- * ecdf([3, 1, 2])(2); // 2/3
80
+ * ecdf([3, 1, 2])(2); // 0.6666666666666666
62
81
  * ```
82
+ *
83
+ * @category Descriptive statistics
63
84
  */
64
85
  export declare function ecdf(x: Sample): (q: number) => number;
@@ -19,6 +19,8 @@ import { seqLength } from "../internal/seq.js";
19
19
  * ```ts
20
20
  * pretty([0.3, 9.6]); // [0, 2, 4, 6, 8, 10]
21
21
  * ```
22
+ *
23
+ * @category Descriptive statistics
22
24
  */
23
25
  export function pretty(x, options = {}) {
24
26
  const finite = Array.from(x).filter(Number.isFinite);
@@ -176,13 +178,15 @@ function fuzzScale(br, dataRange) {
176
178
  return Math.min(...widths.filter((w) => w > 0));
177
179
  }
178
180
  /**
179
- * Histogram counts. Equivalent to R's `hist(x, plot = FALSE)`: break points (by default pretty points over the range
181
+ * Histogram counts. Equivalent to R's `hist(x, plot = FALSE)`. Break points (by default pretty points over the range
180
182
  * with about Sturges' number of cells), counts, densities and cell midpoints. Non-finite values are dropped.
181
183
  *
182
184
  * @example
183
185
  * ```ts
184
- * hist([1, 2, 2, 3, 3, 3, 4]).counts; // [3, 3, 1] for breaks [1, 2, 3, 4]
186
+ * hist([1, 2, 2, 3, 3, 3, 4]).counts; // [3, 3, 1] (for breaks [1, 2, 3, 4])
185
187
  * ```
188
+ *
189
+ * @category Descriptive statistics
186
190
  */
187
191
  export function hist(x, options = {}) {
188
192
  const xs = Array.from(x).filter(Number.isFinite);
@@ -277,8 +281,10 @@ function cellOf(v, f, right, includeLowest) {
277
281
  *
278
282
  * @example
279
283
  * ```ts
280
- * ecdf([3, 1, 2])(2); // 2/3
284
+ * ecdf([3, 1, 2])(2); // 0.6666666666666666
281
285
  * ```
286
+ *
287
+ * @category Descriptive statistics
282
288
  */
283
289
  export function ecdf(x) {
284
290
  const s = Array.from(x)
@@ -0,0 +1,42 @@
1
+ import type { DataFrame } from "../models/modelFrame.js";
2
+ /**
3
+ * A vector: numbers (`NaN` missing), or strings, booleans or numbers with `null` for a missing value.
4
+ *
5
+ * @category Data frames
6
+ */
7
+ export type MissingVector = readonly (number | string | boolean | null)[] | Float64Array;
8
+ /**
9
+ * Which rows have no missing value. Equivalent to R's `complete.cases()`. One boolean per row, true when no column
10
+ * of any argument is missing (`null`, or `NaN` in a numeric column) in that row.
11
+ *
12
+ * @param args Data frames (objects of equal-length columns) or arrays, all with the same number of rows.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * completeCases({ a: [1, NaN, 3], s: ["u", "v", null] }); // [true, false, false]
17
+ * ```
18
+ *
19
+ * @category Data frames
20
+ */
21
+ export declare function completeCases(...args: (MissingVector | DataFrame)[]): boolean[];
22
+ /**
23
+ * The values that are not missing. Equivalent to R's `na.omit()`. For a vector.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * naOmit([1, NaN, 3]); // [1, 3]
28
+ * ```
29
+ *
30
+ * @category Data frames
31
+ */
32
+ export declare function naOmit(x: readonly number[] | Float64Array): number[];
33
+ export declare function naOmit<T extends string | boolean | number>(x: readonly (T | null)[]): T[];
34
+ /**
35
+ * The complete rows of a data frame, as R's `na.omit()` for a data frame: the same columns, in order, restricted to the rows where none is missing (`null`, or `NaN` in a numeric column); see {@link completeCases}.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * naOmit({ a: [1, NaN, 3], s: ["u", "v", null] }); // { a: [1], s: ["u"] }
40
+ * ```
41
+ */
42
+ export declare function naOmit<D extends DataFrame>(x: D): D;