@numero-uno-jpn/rstats 0.9.0 → 0.11.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 (142) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.ja.md +64 -12
  3. package/README.md +63 -11
  4. package/THIRD_PARTY_NOTICES.md +7 -2
  5. package/dist/chunks/chunk-5WDJPHYY.js +2 -0
  6. package/dist/chunks/chunk-7GQMKH3Z.js +2 -0
  7. package/dist/chunks/chunk-AHHS6AC4.js +3 -0
  8. package/dist/chunks/chunk-ALM3VHFP.js +2 -0
  9. package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-C5XTWMGB.js} +1 -1
  10. package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
  11. package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-EZAFN5CD.js} +1 -1
  12. package/dist/chunks/{chunk-H2AP6TCR.js → chunk-EZWBRCJL.js} +1 -1
  13. package/dist/chunks/chunk-F5EDJFEO.js +2 -0
  14. package/dist/chunks/{chunk-FC2TLHZC.js → chunk-JWBO5WVN.js} +2 -2
  15. package/dist/chunks/{chunk-LE7TBHNI.js → chunk-TOGXTCZO.js} +2 -2
  16. package/dist/chunks/chunk-VJ4BDBMU.js +3 -0
  17. package/dist/chunks/chunk-Y5CNQ266.js +2 -0
  18. package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-Y5PYRAYP.js} +2 -2
  19. package/dist/chunks/{chunk-5K4PS7IV.js → chunk-YSWGDOWK.js} +2 -2
  20. package/dist/data/grouping.d.ts +79 -0
  21. package/dist/data/grouping.js +262 -0
  22. package/dist/descriptive/dataFrames.d.ts +110 -0
  23. package/dist/descriptive/dataFrames.js +392 -0
  24. package/dist/descriptive/factanal.d.ts +56 -0
  25. package/dist/descriptive/factanal.js +186 -0
  26. package/dist/descriptive/missing.d.ts +35 -0
  27. package/dist/descriptive/missing.js +50 -0
  28. package/dist/descriptive/omega.d.ts +56 -0
  29. package/dist/descriptive/omega.js +323 -0
  30. package/dist/descriptive/pivot.d.ts +89 -0
  31. package/dist/descriptive/pivot.js +343 -0
  32. package/dist/descriptive.js +2 -2
  33. package/dist/distributions/bvnorm.d.ts +15 -0
  34. package/dist/distributions/bvnorm.js +131 -0
  35. package/dist/distributions/nbeta.js +34 -1
  36. package/dist/distributions/nchisq.d.ts +10 -0
  37. package/dist/distributions/nchisq.js +46 -0
  38. package/dist/distributions.js +2 -2
  39. package/dist/entries/descriptive.d.ts +4 -0
  40. package/dist/entries/descriptive.js +4 -0
  41. package/dist/entries/distributions.d.ts +1 -0
  42. package/dist/entries/distributions.js +1 -0
  43. package/dist/entries/linalg.d.ts +2 -0
  44. package/dist/entries/linalg.js +2 -0
  45. package/dist/entries/numerics.d.ts +2 -0
  46. package/dist/entries/numerics.js +1 -0
  47. package/dist/entries/tests.d.ts +22 -1
  48. package/dist/entries/tests.js +19 -1
  49. package/dist/htest/agreement.d.ts +141 -0
  50. package/dist/htest/agreement.js +274 -0
  51. package/dist/htest/ansariTest.d.ts +12 -0
  52. package/dist/htest/ansariTest.js +5 -17
  53. package/dist/htest/aov.d.ts +19 -0
  54. package/dist/htest/aov.js +22 -15
  55. package/dist/htest/cor.d.ts +12 -0
  56. package/dist/htest/cor.js +9 -27
  57. package/dist/htest/core/simulate.d.ts +2 -0
  58. package/dist/htest/core/simulate.js +1 -1
  59. package/dist/htest/dunnett.d.ts +5 -0
  60. package/dist/htest/dunnett.js +89 -0
  61. package/dist/htest/effectSize.d.ts +112 -0
  62. package/dist/htest/effectSize.js +385 -0
  63. package/dist/htest/ksTest.d.ts +13 -0
  64. package/dist/htest/ksTest.js +5 -8
  65. package/dist/htest/leveneTest.d.ts +30 -0
  66. package/dist/htest/leveneTest.js +41 -0
  67. package/dist/htest/multipleComparisons.d.ts +147 -0
  68. package/dist/htest/multipleComparisons.js +369 -0
  69. package/dist/htest/normalityTests.d.ts +44 -0
  70. package/dist/htest/normalityTests.js +164 -0
  71. package/dist/htest/onewayTest.d.ts +14 -0
  72. package/dist/htest/onewayTest.js +5 -7
  73. package/dist/htest/polycor.d.ts +117 -0
  74. package/dist/htest/polycor.js +468 -0
  75. package/dist/htest/power.d.ts +132 -0
  76. package/dist/htest/power.js +227 -0
  77. package/dist/htest/pwr.d.ts +263 -0
  78. package/dist/htest/pwr.js +440 -0
  79. package/dist/htest/rankTests.d.ts +64 -0
  80. package/dist/htest/rankTests.js +27 -29
  81. package/dist/htest/tTest.d.ts +20 -0
  82. package/dist/htest/tTest.js +19 -24
  83. package/dist/htest/testFormula.d.ts +57 -0
  84. package/dist/htest/testFormula.js +171 -0
  85. package/dist/htest/trendTests.d.ts +57 -0
  86. package/dist/htest/trendTests.js +167 -0
  87. package/dist/htest/varTest.d.ts +23 -0
  88. package/dist/htest/varTest.js +11 -21
  89. package/dist/htest/wilcoxTest.d.ts +14 -0
  90. package/dist/htest/wilcoxTest.js +9 -24
  91. package/dist/linalg/eigen.d.ts +8 -0
  92. package/dist/linalg/eigen.js +5 -4
  93. package/dist/linalg/expm.d.ts +48 -0
  94. package/dist/linalg/expm.js +472 -0
  95. package/dist/linalg/ops.d.ts +13 -2
  96. package/dist/linalg/ops.js +20 -5
  97. package/dist/linalg/schur.d.ts +48 -0
  98. package/dist/linalg/schur.js +225 -0
  99. package/dist/linalg.js +2 -2
  100. package/dist/models/anovaSequential.d.ts +58 -0
  101. package/dist/models/anovaSequential.js +138 -0
  102. package/dist/models/aovEz.d.ts +64 -0
  103. package/dist/models/aovEz.js +332 -0
  104. package/dist/models/aovStrata.d.ts +32 -0
  105. package/dist/models/aovStrata.js +104 -0
  106. package/dist/models/carAnova.d.ts +30 -0
  107. package/dist/models/carAnova.js +121 -0
  108. package/dist/models/coxph.d.ts +101 -0
  109. package/dist/models/coxph.js +502 -0
  110. package/dist/models/ddLeastSquares.d.ts +30 -0
  111. package/dist/models/ddLeastSquares.js +90 -0
  112. package/dist/models/ddMatrix.d.ts +10 -0
  113. package/dist/models/ddMatrix.js +91 -0
  114. package/dist/models/formula.d.ts +83 -0
  115. package/dist/models/formula.js +333 -0
  116. package/dist/models/lm.d.ts +84 -3
  117. package/dist/models/lm.js +141 -44
  118. package/dist/models/mauchly.d.ts +48 -0
  119. package/dist/models/mauchly.js +123 -0
  120. package/dist/models/modelFrame.d.ts +40 -0
  121. package/dist/models/modelFrame.js +131 -0
  122. package/dist/models/modelMatrix.d.ts +88 -0
  123. package/dist/models/modelMatrix.js +170 -0
  124. package/dist/models/survival.d.ts +87 -0
  125. package/dist/models/survival.js +238 -0
  126. package/dist/numerics.js +2 -2
  127. package/dist/optim/lbfgsb.d.ts +20 -0
  128. package/dist/optim/lbfgsb.js +1240 -0
  129. package/dist/optim/optim.d.ts +85 -0
  130. package/dist/optim/optim.js +610 -0
  131. package/dist/rstats.js +19 -4
  132. package/dist/special.js +2 -2
  133. package/dist/tests.js +17 -4
  134. package/llms.txt +114 -0
  135. package/package.json +3 -2
  136. package/dist/chunks/chunk-24U4DKRY.js +0 -2
  137. package/dist/chunks/chunk-IVOBWYLV.js +0 -2
  138. package/dist/chunks/chunk-JLSTEMSN.js +0 -2
  139. package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
  140. package/dist/chunks/chunk-MSAUU6PY.js +0 -2
  141. package/dist/chunks/chunk-YC4JWUKG.js +0 -2
  142. package/dist/chunks/chunk-ZRO446BP.js +0 -2
@@ -0,0 +1,392 @@
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()` of data frames: every pair of rows of x and y with
154
+ * 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
+ export function merge(x, y, options = {}) {
168
+ const xNames = Object.keys(x);
169
+ const yNames = Object.keys(y);
170
+ const nx = rowCount(x);
171
+ const ny = rowCount(y);
172
+ const byDefault = options.by === undefined ? xNames.filter((n) => yNames.includes(n)) : nameList(options.by);
173
+ const byX = options.byX === undefined ? byDefault : nameList(options.byX);
174
+ const byY = options.byY === undefined ? byDefault : nameList(options.byY);
175
+ const keysX = keyColumns(x, byX);
176
+ const keysY = keyColumns(y, byY);
177
+ if (byX.length !== byY.length)
178
+ throw new Error("'by.x' and 'by.y' specify different numbers of columns");
179
+ const allX = options.allX ?? options.all ?? false;
180
+ const allY = options.allY ?? options.all ?? false;
181
+ const sort = options.sort ?? true;
182
+ const [suffixX, suffixY] = options.suffixes ?? [".x", ".y"];
183
+ const restX = xNames.filter((n) => !byX.includes(n));
184
+ const restY = yNames.filter((n) => !byY.includes(n));
185
+ const nameX = (n) => (restY.includes(n) ? n + suffixX : n);
186
+ const nameY = (n) => (restX.includes(n) || byX.includes(n) ? n + suffixY : n);
187
+ // Pairs of rows of the result: [x row, y row], -1 for a missing side
188
+ const pairs = [];
189
+ if (byX.length === 0) {
190
+ for (let j = 0; j < ny; j++)
191
+ for (let i = 0; i < nx; i++)
192
+ pairs.push([i, j]);
193
+ }
194
+ else {
195
+ const keyOf = byX.length === 1
196
+ ? (cols, i) => {
197
+ const v = valueAt(cols[0], i);
198
+ return isMissing(v) ? MISSING_KEY : v;
199
+ }
200
+ : (cols, i) => cols.map((c) => valueText(valueAt(c, i))).join("\r");
201
+ const kx = Array.from({ length: nx }, (_, i) => keyOf(keysX, i));
202
+ const ky = Array.from({ length: ny }, (_, j) => keyOf(keysY, j));
203
+ const inY = new Set(ky);
204
+ // position (1-based) of each key's first occurrence among the x keys that occur in y (duplicates kept)
205
+ const position = new Map();
206
+ let p = 0;
207
+ for (const k of kx) {
208
+ if (!inY.has(k))
209
+ continue;
210
+ p++;
211
+ if (!position.has(k))
212
+ position.set(k, p);
213
+ }
214
+ const sx = groupSorted(kx.map((k) => position.get(k) ?? 0));
215
+ const sy = groupSorted(ky.map((k) => position.get(k) ?? 0));
216
+ for (const [value, rowsX] of sx.groups) {
217
+ const rowsY = sy.groups.get(value) ?? [];
218
+ for (const i of rowsX)
219
+ for (const j of rowsY)
220
+ pairs.push([i, j]);
221
+ }
222
+ if (allX)
223
+ for (const i of sx.alone)
224
+ pairs.push([i, -1]);
225
+ if (allY)
226
+ for (const j of sy.alone)
227
+ pairs.push([-1, j]);
228
+ }
229
+ // Rows sorted stably by the key
230
+ let order = pairs.map((_, r) => r);
231
+ if (sort && byX.length > 0) {
232
+ const keyValue = (r, k) => {
233
+ const [i, j] = pairs[r];
234
+ return i >= 0 ? valueAt(keysX[k], i) : valueAt(keysY[k], j);
235
+ };
236
+ if (byX.length > 1 && !allX && !allY) {
237
+ const text = pairs.map((_, r) => byX.map((_, k) => valueText(keyValue(r, k))).join("\r"));
238
+ order.sort((a, b) => compareCodePoints(text[a], text[b]));
239
+ }
240
+ else {
241
+ order.sort((a, b) => {
242
+ for (let k = 0; k < byX.length; k++) {
243
+ const d = compareValues(keyValue(a, k), keyValue(b, k));
244
+ if (d !== 0)
245
+ return d;
246
+ }
247
+ return 0;
248
+ });
249
+ }
250
+ }
251
+ const sorted = order.map((r) => pairs[r]);
252
+ const out = {};
253
+ byX.forEach((n, k) => {
254
+ const cx = keysX[k];
255
+ const cy = keysY[k];
256
+ addColumn(out, n, gather([cx, cy], sorted.map(([i, j]) => (i >= 0 ? [cx, i] : [cy, j]))));
257
+ });
258
+ for (const n of restX) {
259
+ const c = x[n];
260
+ addColumn(out, nameX(n), gather([c], sorted.map(([i]) => (i >= 0 ? [c, i] : null))));
261
+ }
262
+ for (const n of restY) {
263
+ const c = y[n];
264
+ addColumn(out, nameY(n), gather([c], sorted.map(([, j]) => (j >= 0 ? [c, j] : null))));
265
+ }
266
+ return out;
267
+ }
268
+ /**
269
+ * The rows of a data frame that meet a condition, and optionally some of its columns. Equivalent to R's `subset()`
270
+ * of a data frame: `keep` is a boolean per row or a function of the row; a missing (`null`) or non-boolean result
271
+ * counts as false, as R drops the rows whose condition is NA.
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * const d = { y: [5, NaN, 7, 2], g: ["a", "b", "a", "b"] };
276
+ * subset(d, (row) => (row.y as number) > 4); // { y: [5, 7], g: ["a", "a"] }
277
+ * subset(d, [true, true, false, false], { select: ["g"] }); // { g: ["a", "b"] }
278
+ * ```
279
+ */
280
+ export function subset(data, keep, options = {}) {
281
+ const names = Object.keys(data);
282
+ const n = rowCount(data);
283
+ if (typeof keep !== "function" && keep.length !== n) {
284
+ throw new RangeError(`'keep' has ${keep.length} values for ${n} rows`);
285
+ }
286
+ const rowAt = (i) => Object.fromEntries(names.map((c) => [c, valueAt(data[c], i)]));
287
+ const rows = [];
288
+ for (let i = 0; i < n; i++)
289
+ if ((typeof keep === "function" ? keep(rowAt(i)) : keep[i]) === true)
290
+ rows.push(i);
291
+ const select = options.select ?? names;
292
+ const out = {};
293
+ for (const c of select) {
294
+ if (!Object.hasOwn(data, c))
295
+ throw new Error("undefined columns selected");
296
+ addColumn(out, c, pick(data[c], rows));
297
+ }
298
+ return out;
299
+ }
300
+ /**
301
+ * Stacks data frames with the same column names (matched by name, in the first frame's order). The data frame form
302
+ * of R's `rbind()`; see {@link rbind}.
303
+ */
304
+ export function rbindFrames(frames) {
305
+ if (frames.length === 0)
306
+ return {};
307
+ const names = Object.keys(frames[0]);
308
+ for (const f of frames) {
309
+ rowCount(f);
310
+ const other = Object.keys(f);
311
+ if (other.length !== names.length || !names.every((n) => Object.hasOwn(f, n))) {
312
+ throw new Error("names do not match previous names");
313
+ }
314
+ }
315
+ const out = {};
316
+ for (const n of names) {
317
+ const cols = frames.map((f) => f[n]);
318
+ const rows = cols.flatMap((c) => Array.from({ length: c.length }, (_, i) => [c, i]));
319
+ out[n] = gather(cols, rows);
320
+ }
321
+ return out;
322
+ }
323
+ /**
324
+ * Puts data frames with the same number of rows side by side. The data frame form of R's `cbind()`; see
325
+ * {@link cbind}. A column name that occurs twice is an error (an object cannot hold two columns of the same name).
326
+ */
327
+ export function cbindFrames(frames) {
328
+ const out = {};
329
+ const counts = frames.map(rowCount);
330
+ const differing = counts.find((c) => c !== counts[0]);
331
+ if (differing !== undefined)
332
+ throw new RangeError(`arguments imply differing number of rows: ${counts[0]}, ${differing}`);
333
+ for (const f of frames) {
334
+ for (const [n, c] of Object.entries(f))
335
+ addColumn(out, n, c instanceof Float64Array ? Float64Array.from(c) : [...c]);
336
+ }
337
+ return out;
338
+ }
339
+ /**
340
+ * A data frame (an object of columns) from an array of row objects, the usual shape of JSON and of parsed CSV:
341
+ * `[{ age: 30, score: 5 }, { age: 41, score: 7 }]` becomes `{ age: [30, 41], score: [5, 7] }`. A key that a row
342
+ * lacks, and `undefined`, become `null` (a missing value). Values must be numbers, strings, booleans or `null`, and
343
+ * one column may not mix numbers, strings and booleans. Not an R function: R reads data as data frames directly.
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * fromRows([{ id: "a", score: 5 }, { id: "b" }]); // { id: ["a", "b"], score: [5, null] }
348
+ * ```
349
+ */
350
+ export function fromRows(rows, options = {}) {
351
+ let names = options.columns;
352
+ if (names === undefined) {
353
+ const seen = new Set();
354
+ for (const row of rows)
355
+ for (const k of Object.keys(row))
356
+ seen.add(k);
357
+ names = [...seen];
358
+ }
359
+ const out = {};
360
+ for (const name of names) {
361
+ const kinds = new Set();
362
+ const col = rows.map((row, i) => {
363
+ const v = Object.hasOwn(row, name) ? row[name] : undefined;
364
+ if (v === undefined || v === null)
365
+ return null;
366
+ if (typeof v !== "number" && typeof v !== "string" && typeof v !== "boolean") {
367
+ throw new TypeError(`row ${i}, column '${name}': values must be numbers, strings, booleans or null`);
368
+ }
369
+ kinds.add(typeof v);
370
+ return v;
371
+ });
372
+ if (kinds.size > 1)
373
+ throw new TypeError(`column '${name}' mixes ${[...kinds].join(" and ")} values`);
374
+ addColumn(out, name, col);
375
+ }
376
+ return out;
377
+ }
378
+ /**
379
+ * The rows of a data frame as an array of objects, the inverse of {@link fromRows}: `{ age: [30, 41], score: [5, 7]
380
+ * }` becomes `[{ age: 30, score: 5 }, { age: 41, score: 7 }]`. Missing values stay as they are (`null`, or `NaN` in a
381
+ * numeric column).
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * toRows({ id: ["a", "b"], score: [5, null] }); // [{ id: "a", score: 5 }, { id: "b", score: null }]
386
+ * ```
387
+ */
388
+ export function toRows(data) {
389
+ const names = Object.keys(data);
390
+ const n = rowCount(data);
391
+ return Array.from({ length: n }, (_, i) => Object.fromEntries(names.map((c) => [c, valueAt(data[c], i)])));
392
+ }
@@ -0,0 +1,56 @@
1
+ /** Rotations of {@link factanal} */
2
+ export type FactanalRotation = "varimax" | "promax" | "none";
3
+ /** Options of {@link factanal} */
4
+ export interface FactanalOptions {
5
+ /** A covariance (or correlation) matrix to analyse instead of the data `x` (pass `null` as `x`). */
6
+ covmat?: readonly (readonly number[])[];
7
+ /** The number of observations behind `covmat` (for the test statistic). Default: unknown. */
8
+ nObs?: number;
9
+ /** Default `"varimax"`. */
10
+ rotation?: FactanalRotation;
11
+ control?: {
12
+ /** Lower bound of the uniquenesses. Default 0.005. */
13
+ lower?: number;
14
+ /** Starting uniquenesses. Default `(1 - factors / (2p)) / diag(solve(S))`. */
15
+ start?: readonly number[];
16
+ };
17
+ }
18
+ /** Result of {@link factanal} */
19
+ export interface FactanalResult {
20
+ uniquenesses: number[];
21
+ /** The (rotated) loadings, p rows by `factors` columns, columns sorted by decreasing sum of squares, each column's sum positive */
22
+ loadings: number[][];
23
+ /** The rotation matrix (absent for `rotation: "none"` and for one factor) */
24
+ rotmat?: number[][];
25
+ /** The likelihood-ratio statistic (NaN without n.obs or with no degrees of freedom) */
26
+ STATISTIC: number;
27
+ dof: number;
28
+ /** Its upper chi-squared tail probability (NaN as STATISTIC) */
29
+ PVAL: number;
30
+ converged: boolean;
31
+ /** The minimised criterion */
32
+ objective: number;
33
+ /** optim's counts of function and gradient evaluations */
34
+ counts: [number, number];
35
+ }
36
+ /** Sum rounded once (R's long double accumulation, here double-double); also used by omega */
37
+ export declare function sumOnce(xs: readonly number[]): number;
38
+ /** Varimax rotation (normalised, eps 1e-5, at most 1000 iterations); also used by omega */
39
+ export declare function varimax(L: readonly (readonly number[])[]): {
40
+ loadings: number[][];
41
+ rotmat: number[][];
42
+ };
43
+ /**
44
+ * 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"`.
46
+ *
47
+ * @param x The data matrix (array of rows), or `null` with `options.covmat`.
48
+ * @param factors The number of factors.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const fa = factanal(x, 2); // x: an n x 6 data matrix
53
+ * fa.uniquenesses; fa.loadings; fa.PVAL;
54
+ * ```
55
+ */
56
+ export declare function factanal(x: readonly (readonly number[])[] | null, factors: number, options?: FactanalOptions): FactanalResult;
@@ -0,0 +1,186 @@
1
+ // Maximum-likelihood factor analysis, R's factanal(), with the varimax and promax rotations. Written for rStats.js
2
+ // from the specification oracle/factanal-behaviour.md (no R code was read or used): the uniquenesses minimise the
3
+ // likelihood criterion by L-BFGS-B (this library's optim), the loadings come from the eigendecomposition of the
4
+ // scaled correlation matrix, and the rotations are Kaiser's varimax (normalised) and Hendrickson and White's promax.
5
+ import { pchisq } from "../distributions/chisq.js";
6
+ import { eigen } from "../linalg/eigen.js";
7
+ import { qr, qrCoef } from "../linalg/qr.js";
8
+ import { solve } from "../linalg/solve.js";
9
+ import { svd } from "../linalg/svd.js";
10
+ import { optim } from "../optim/optim.js";
11
+ import { twoSum } from "../special/dd.js";
12
+ import { cov } from "./cov.js";
13
+ /** Sum rounded once (R's long double accumulation, here double-double); also used by omega */
14
+ export function sumOnce(xs) {
15
+ let hi = 0;
16
+ let lo = 0;
17
+ for (const x of xs) {
18
+ const [s, e] = twoSum(hi, x);
19
+ hi = s;
20
+ lo += e;
21
+ }
22
+ return hi + lo;
23
+ }
24
+ const colSumsOf = (m, f) => m[0].map((_, j) => sumOnce(m.map((r) => f(r[j]))));
25
+ /** The scaled matrix D S D with D = diag(1/sqrt(psi)) */
26
+ function scaled(S, psi) {
27
+ const d = psi.map((v) => 1 / Math.sqrt(v));
28
+ return S.map((row, i) => row.map((v, j) => d[i] * v * d[j]));
29
+ }
30
+ /** Loadings at psi: diag(sqrt(psi)) V diag(sqrt(max(e - 1, 0))) from the first q eigenvectors of D S D */
31
+ function loadingsAt(S, psi, q) {
32
+ const E = eigen(scaled(S, psi), { symmetric: true });
33
+ const w = E.values.slice(0, q).map((e) => Math.sqrt(Math.max(e - 1, 0)));
34
+ return E.vectors.map((row, i) => row.slice(0, q).map((v, k) => Math.sqrt(psi[i]) * (v * w[k])));
35
+ }
36
+ /** Columns sorted by decreasing sum of squares, each made to have a positive sum; `rot` (if any) permuted and signed alike */
37
+ function orderAndSignColumns(L, rot) {
38
+ const ssq = colSumsOf(L, (v) => v * v);
39
+ const order = ssq.map((_, j) => j).sort((a, b) => ssq[b] - ssq[a] || a - b);
40
+ let out = L.map((r) => order.map((j) => r[j]));
41
+ let R = rot?.map((r) => order.map((j) => r[j]));
42
+ const sign = colSumsOf(out, (v) => v).map((s) => (s < 0 ? -1 : 1));
43
+ out = out.map((r) => r.map((v, j) => (sign[j] < 0 ? -v : v)));
44
+ R = R?.map((r) => r.map((v, j) => (sign[j] < 0 ? -v : v)));
45
+ return R === undefined ? { L: out } : { L: out, rot: R };
46
+ }
47
+ const matMul = (A, B) => A.map((row) => B[0].map((_, j) => {
48
+ let s = 0;
49
+ for (let k = 0; k < row.length; k++)
50
+ s += row[k] * B[k][j];
51
+ return s;
52
+ }));
53
+ const transpose = (A) => A[0].map((_, j) => A.map((r) => r[j]));
54
+ /** Varimax rotation (normalised, eps 1e-5, at most 1000 iterations); also used by omega */
55
+ export function varimax(L) {
56
+ const k = L[0].length;
57
+ const p = L.length;
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);
61
+ let T = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (_, j) => (i === j ? 1 : 0)));
62
+ let total = 0;
63
+ for (let it = 0; it < 1000; it++) {
64
+ const Z = matMul(X, T);
65
+ const css = Z[0].map((_, j) => {
66
+ let s = 0;
67
+ for (let i = 0; i < p; i++)
68
+ s += Z[i][j] * Z[i][j];
69
+ return s;
70
+ });
71
+ const W = Z.map((r) => r.map((z, j) => z ** 3 - (z * css[j]) / p));
72
+ const B = matMul(Xt, W);
73
+ const sv = svd(B);
74
+ T = matMul(sv.u, transpose(sv.v));
75
+ const previous = total;
76
+ total = sumOnce(sv.d);
77
+ if (total < previous * (1 + 1e-5))
78
+ break;
79
+ }
80
+ const Z = matMul(X, T);
81
+ return { loadings: Z.map((r, i) => r.map((v) => v * len[i])), rotmat: T };
82
+ }
83
+ /** Promax rotation (m = 4) */
84
+ function promax(L) {
85
+ const v = varimax(L);
86
+ const X = v.loadings;
87
+ const Q = X.map((r) => r.map((x) => x * Math.abs(x) ** 3));
88
+ const U0 = qrCoef(qr(X), Q);
89
+ const d = solve(matMul(transpose(U0), U0)).map((r, i) => r[i]);
90
+ const U = U0.map((r) => r.map((u, j) => u * Math.sqrt(d[j])));
91
+ return { loadings: matMul(X, U), rotmat: matMul(v.rotmat, U) };
92
+ }
93
+ /**
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"`.
96
+ *
97
+ * @param x The data matrix (array of rows), or `null` with `options.covmat`.
98
+ * @param factors The number of factors.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const fa = factanal(x, 2); // x: an n x 6 data matrix
103
+ * fa.uniquenesses; fa.loadings; fa.PVAL;
104
+ * ```
105
+ */
106
+ export function factanal(x, factors, options = {}) {
107
+ let cv;
108
+ let nObs;
109
+ if (options.covmat !== undefined) {
110
+ cv = options.covmat.map((r) => r.slice());
111
+ nObs = options.nObs ?? NaN;
112
+ }
113
+ else {
114
+ if (x === null)
115
+ throw new TypeError("neither 'x' nor 'covmat' supplied");
116
+ cv = cov(x);
117
+ nObs = x.length;
118
+ }
119
+ const p = cv.length;
120
+ if (p < 3)
121
+ throw new RangeError("factor analysis requires at least three variables");
122
+ const q = factors;
123
+ if (!Number.isInteger(q) || q < 1)
124
+ throw new RangeError("'factors' must be a positive integer");
125
+ const dof = ((p - q) ** 2 - p - q) / 2;
126
+ if (dof < 0)
127
+ throw new RangeError(`${q} ${q === 1 ? "factor is" : "factors are"} too many for ${p} variables`);
128
+ const sds = cv.map((r, i) => Math.sqrt(r[i]));
129
+ const S = cv.map((r, i) => r.map((v, j) => v / (sds[i] * sds[j])));
130
+ const lower = options.control?.lower ?? 0.005;
131
+ const start = options.control?.start?.slice() ?? solve(S).map((r, i) => (1 - q / (2 * p)) / r[i]);
132
+ const objective = (psi) => {
133
+ const e = eigen(scaled(S, psi), { symmetric: true, onlyValues: true }).values.slice(q);
134
+ return -(sumOnce(e.map((v) => Math.log(v) - v)) - q + p);
135
+ };
136
+ const gradient = (psi) => {
137
+ const L = loadingsAt(S, psi, q);
138
+ return psi.map((v, i) => {
139
+ let s = 0;
140
+ for (let k = 0; k < q; k++)
141
+ s += L[i][k] * L[i][k];
142
+ return (s + v - S[i][i]) / (v * v);
143
+ });
144
+ };
145
+ const fit = optim(start, objective, {
146
+ gr: gradient,
147
+ method: "L-BFGS-B",
148
+ lower,
149
+ upper: 1,
150
+ control: { fnscale: 1, parscale: new Array(p).fill(0.01) },
151
+ });
152
+ if (fit.convergence !== 0)
153
+ throw new Error("unable to optimize from this starting value");
154
+ const psi = fit.par;
155
+ let L = orderAndSignColumns(loadingsAt(S, psi, q)).L;
156
+ let rotmat;
157
+ const rotation = options.rotation ?? "varimax";
158
+ if (rotation !== "none" && q >= 2) {
159
+ const r = rotation === "varimax" ? varimax(L) : promax(L);
160
+ const sorted = orderAndSignColumns(r.loadings, r.rotmat);
161
+ L = sorted.L;
162
+ rotmat = sorted.rot;
163
+ }
164
+ else if (rotation !== "varimax" && rotation !== "promax" && rotation !== "none") {
165
+ throw new RangeError(`unknown rotation '${String(rotation)}'`);
166
+ }
167
+ let STATISTIC = NaN;
168
+ let PVAL = NaN;
169
+ if (!Number.isNaN(nObs) && dof > 0) {
170
+ STATISTIC = (nObs - 1 - (2 * p + 5) / 6 - (2 * q) / 3) * fit.value;
171
+ PVAL = pchisq(STATISTIC, dof, { lowerTail: false });
172
+ }
173
+ const out = {
174
+ uniquenesses: psi,
175
+ loadings: L,
176
+ STATISTIC,
177
+ dof,
178
+ PVAL,
179
+ converged: true,
180
+ objective: fit.value,
181
+ counts: fit.counts,
182
+ };
183
+ if (rotmat !== undefined)
184
+ out.rotmat = rotmat;
185
+ return out;
186
+ }
@@ -0,0 +1,35 @@
1
+ import type { DataFrame } from "../models/modelFrame.js";
2
+ /** A vector: numbers (`NaN` missing), or strings, booleans or numbers with `null` for a missing value. */
3
+ export type MissingVector = readonly (number | string | boolean | null)[] | Float64Array;
4
+ /**
5
+ * Which rows have no missing value. Equivalent to R's `complete.cases()`: one boolean per row, true when no column of
6
+ * any argument is missing (`null`, or `NaN` in a numeric column) in that row.
7
+ *
8
+ * @param args Data frames (objects of equal-length columns) or arrays, all with the same number of rows.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * completeCases({ a: [1, NaN, 3], s: ["u", "v", null] }); // [true, false, false]
13
+ * ```
14
+ */
15
+ export declare function completeCases(...args: (MissingVector | DataFrame)[]): boolean[];
16
+ /**
17
+ * The values that are not missing. Equivalent to R's `na.omit()` for a vector.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * naOmit([1, NaN, 3]); // [1, 3]
22
+ * ```
23
+ */
24
+ export declare function naOmit(x: readonly number[] | Float64Array): number[];
25
+ export declare function naOmit<T extends string | boolean | number>(x: readonly (T | null)[]): T[];
26
+ /**
27
+ * The complete rows of a data frame. Equivalent to R's `na.omit()` for a data frame: the same columns, in order,
28
+ * restricted to the rows where none is missing (`null`, or `NaN` in a numeric column); see {@link completeCases}.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * naOmit({ a: [1, NaN, 3], s: ["u", "v", null] }); // { a: [1], s: ["u"] }
33
+ * ```
34
+ */
35
+ export declare function naOmit<D extends DataFrame>(x: D): D;