@numero-uno-jpn/rstats 0.10.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.
- package/CHANGELOG.md +24 -0
- package/README.ja.md +11 -8
- package/README.md +10 -7
- package/dist/chunks/{chunk-7HPVUVZB.js → chunk-5WDJPHYY.js} +1 -1
- package/dist/chunks/{chunk-EWC6I75B.js → chunk-7GQMKH3Z.js} +1 -1
- package/dist/chunks/chunk-AHHS6AC4.js +3 -0
- package/dist/chunks/chunk-ALM3VHFP.js +2 -0
- package/dist/chunks/{chunk-QFULZNHL.js → chunk-C5XTWMGB.js} +1 -1
- package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
- package/dist/chunks/{chunk-QULPY6YM.js → chunk-EZAFN5CD.js} +1 -1
- package/dist/chunks/{chunk-2XKG3DX4.js → chunk-EZWBRCJL.js} +1 -1
- package/dist/chunks/{chunk-O6PT7IVU.js → chunk-F5EDJFEO.js} +2 -2
- package/dist/chunks/{chunk-4NM37MGA.js → chunk-JWBO5WVN.js} +2 -2
- package/dist/chunks/{chunk-ENL43FNO.js → chunk-TOGXTCZO.js} +2 -2
- package/dist/chunks/{chunk-IT354SHV.js → chunk-VJ4BDBMU.js} +2 -2
- package/dist/chunks/{chunk-ZRIM4R4A.js → chunk-Y5CNQ266.js} +2 -2
- package/dist/chunks/{chunk-LIMZKONM.js → chunk-Y5PYRAYP.js} +2 -2
- package/dist/chunks/{chunk-QJJWGNJP.js → chunk-YSWGDOWK.js} +2 -2
- package/dist/data/grouping.d.ts +79 -0
- package/dist/data/grouping.js +262 -0
- package/dist/descriptive/dataFrames.d.ts +110 -0
- package/dist/descriptive/dataFrames.js +392 -0
- package/dist/descriptive/missing.d.ts +35 -0
- package/dist/descriptive/missing.js +50 -0
- package/dist/descriptive/pivot.d.ts +89 -0
- package/dist/descriptive/pivot.js +343 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +4 -0
- package/dist/entries/descriptive.js +4 -0
- package/dist/htest/ansariTest.d.ts +12 -0
- package/dist/htest/ansariTest.js +5 -17
- package/dist/htest/cor.d.ts +12 -0
- package/dist/htest/cor.js +9 -27
- package/dist/htest/ksTest.d.ts +13 -0
- package/dist/htest/ksTest.js +5 -8
- package/dist/htest/onewayTest.d.ts +14 -0
- package/dist/htest/onewayTest.js +5 -7
- package/dist/htest/rankTests.d.ts +57 -0
- package/dist/htest/rankTests.js +19 -31
- package/dist/htest/tTest.d.ts +20 -0
- package/dist/htest/tTest.js +19 -24
- package/dist/htest/testFormula.d.ts +57 -0
- package/dist/htest/testFormula.js +171 -0
- package/dist/htest/varTest.d.ts +23 -0
- package/dist/htest/varTest.js +11 -21
- package/dist/htest/wilcoxTest.d.ts +14 -0
- package/dist/htest/wilcoxTest.js +9 -24
- package/dist/linalg/ops.d.ts +13 -2
- package/dist/linalg/ops.js +20 -5
- package/dist/linalg.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +14 -14
- package/dist/special.js +2 -2
- package/dist/tests.js +12 -13
- package/llms.txt +12 -0
- package/package.json +1 -1
- package/dist/chunks/chunk-AECGWZHD.js +0 -2
- package/dist/chunks/chunk-XWTZ4RTR.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,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;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Missing values: R's complete.cases and na.omit for arrays and data frames.
|
|
2
|
+
//
|
|
3
|
+
// Written for rStats.js (no ported code) from oracle/formulatests-behaviour.md. A value is missing when it is `null`,
|
|
4
|
+
// or `NaN` (in a numeric column); a row is complete when no column of any argument is missing there.
|
|
5
|
+
const isMissing = (v) => v === null || (typeof v === "number" && Number.isNaN(v));
|
|
6
|
+
const isVector = (x) => Array.isArray(x) || ArrayBuffer.isView(x);
|
|
7
|
+
/** The columns of an argument (a vector is one column) and its number of rows */
|
|
8
|
+
function columnsOf(x) {
|
|
9
|
+
if (isVector(x))
|
|
10
|
+
return { columns: [x], rows: x.length };
|
|
11
|
+
if (typeof x !== "object" || x === null)
|
|
12
|
+
throw new TypeError("the arguments must be arrays or data frames");
|
|
13
|
+
const columns = Object.values(x);
|
|
14
|
+
const rows = columns[0]?.length ?? 0;
|
|
15
|
+
if (columns.some((c) => c.length !== rows))
|
|
16
|
+
throw new RangeError("not all arguments have the same length");
|
|
17
|
+
return { columns, rows };
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Which rows have no missing value. Equivalent to R's `complete.cases()`: one boolean per row, true when no column of
|
|
21
|
+
* any argument is missing (`null`, or `NaN` in a numeric column) in that row.
|
|
22
|
+
*
|
|
23
|
+
* @param args Data frames (objects of equal-length columns) or arrays, all with the same number of rows.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* completeCases({ a: [1, NaN, 3], s: ["u", "v", null] }); // [true, false, false]
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export function completeCases(...args) {
|
|
31
|
+
if (args.length === 0)
|
|
32
|
+
throw new RangeError("no input has determined the number of cases");
|
|
33
|
+
const all = args.map(columnsOf);
|
|
34
|
+
const rows = all[0].rows;
|
|
35
|
+
if (all.some((a) => a.rows !== rows))
|
|
36
|
+
throw new RangeError("not all arguments have the same length");
|
|
37
|
+
const columns = all.flatMap((a) => a.columns);
|
|
38
|
+
return Array.from({ length: rows }, (_, i) => columns.every((c) => !isMissing(c[i])));
|
|
39
|
+
}
|
|
40
|
+
export function naOmit(x) {
|
|
41
|
+
if (isVector(x))
|
|
42
|
+
return Array.from(x).filter((v) => !isMissing(v));
|
|
43
|
+
const keep = completeCases(x);
|
|
44
|
+
const out = {};
|
|
45
|
+
for (const [name, column] of Object.entries(x)) {
|
|
46
|
+
const kept = Array.from(column).filter((_, i) => keep[i]);
|
|
47
|
+
out[name] = column instanceof Float64Array ? Float64Array.from(kept) : kept;
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { DataFrame } from "../models/modelFrame.js";
|
|
2
|
+
import { type DataValue } from "./dataFrames.js";
|
|
3
|
+
/** Options for {@link pivotLonger} (tidyr's arguments in camelCase). */
|
|
4
|
+
export interface PivotLongerOptions {
|
|
5
|
+
/** The columns to pivot: their names, in this order, or a test of the name (selecting in the data's order). */
|
|
6
|
+
cols: readonly string[] | ((name: string) => boolean);
|
|
7
|
+
/**
|
|
8
|
+
* The columns to make from the names, one per part of the names. `".value"` marks the part that names the value
|
|
9
|
+
* columns. Default `"name"`.
|
|
10
|
+
*/
|
|
11
|
+
namesTo?: string | readonly string[];
|
|
12
|
+
/** A regular expression whose match at the start of the names is removed. */
|
|
13
|
+
namesPrefix?: string;
|
|
14
|
+
/** A regular expression at whose matches the names are split into the parts. */
|
|
15
|
+
namesSep?: string;
|
|
16
|
+
/** A regular expression whose capture groups are the parts of the names. */
|
|
17
|
+
namesPattern?: string;
|
|
18
|
+
/** Functions applied to the parts, by `namesTo` column (the part as a string; missing parts stay missing). */
|
|
19
|
+
namesTransform?: Readonly<Record<string, (part: string) => DataValue>>;
|
|
20
|
+
/** The name of the value column (without `".value"` in `namesTo`). Default `"value"`. */
|
|
21
|
+
valuesTo?: string;
|
|
22
|
+
/** Drop the rows where every value column is missing. Default `false`. */
|
|
23
|
+
valuesDropNa?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* `"fastest"` (default): the pivoted columns vary within each input row; `"slowest"`: all rows for each column in
|
|
26
|
+
* turn.
|
|
27
|
+
*/
|
|
28
|
+
colsVary?: "fastest" | "slowest";
|
|
29
|
+
/** Called with each of tidyr's warnings, once per distinct warning, in order. Default: the warnings are dropped. */
|
|
30
|
+
onWarning?: (message: string) => void;
|
|
31
|
+
}
|
|
32
|
+
/** A summary of the values of one cell (in data order), for `valuesFn` of {@link pivotWider}. */
|
|
33
|
+
export type PivotSummary = (values: DataValue[]) => DataValue;
|
|
34
|
+
/** Options for {@link pivotWider} (tidyr's arguments in camelCase). */
|
|
35
|
+
export interface PivotWiderOptions {
|
|
36
|
+
/** The column (or columns) whose values name the new columns. Default `"name"`. */
|
|
37
|
+
namesFrom?: string | readonly string[];
|
|
38
|
+
/** The column (or columns) whose values fill the new columns. Default `"value"`. */
|
|
39
|
+
valuesFrom?: string | readonly string[];
|
|
40
|
+
/**
|
|
41
|
+
* The columns that identify a row of the result. Default: every column not in `namesFrom` or `valuesFrom`, in the
|
|
42
|
+
* data's order; when given, the other columns are dropped.
|
|
43
|
+
*/
|
|
44
|
+
idCols?: string | readonly string[];
|
|
45
|
+
/** Put before each new name. Default `""`. */
|
|
46
|
+
namesPrefix?: string;
|
|
47
|
+
/** Joins the values of several `namesFrom` columns, and a value column's name to the name. Default `"_"`. */
|
|
48
|
+
namesSep?: string;
|
|
49
|
+
/** Sort the names (by the first `namesFrom` column, then the next) instead of taking them in order of appearance. */
|
|
50
|
+
namesSort?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* With several `valuesFrom`: `"fastest"` (default) all names for each value column; `"slowest"` each value column
|
|
53
|
+
* for each name.
|
|
54
|
+
*/
|
|
55
|
+
namesVary?: "fastest" | "slowest";
|
|
56
|
+
/** The value of a cell that no row fills, or such values by value column. Default: missing. */
|
|
57
|
+
valuesFill?: DataValue | Readonly<Record<string, DataValue>>;
|
|
58
|
+
/** Summarises the values of each filled cell, or such functions by value column. */
|
|
59
|
+
valuesFn?: PivotSummary | Readonly<Record<string, PivotSummary>>;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Reshapes a data frame from wide to long: the selected columns become rows. Equivalent to tidyr's `pivot_longer()`:
|
|
63
|
+
* the result has the columns not selected, a column per part of the selected names (`namesTo`), and the value
|
|
64
|
+
* column (`valuesTo`), or with `".value"` in `namesTo` one value column per value of that part. The values of the
|
|
65
|
+
* selected columns are combined into one type: numbers with booleans give numbers; strings with either are an error.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* const wide = { id: ["s1", "s2"], t1: [5.1, 4.8], t2: [6.3, 7.2] };
|
|
70
|
+
* pivotLonger(wide, { cols: ["t1", "t2"], namesTo: "time", valuesTo: "score" });
|
|
71
|
+
* // { id: ["s1", "s1", "s2", "s2"], time: ["t1", "t2", "t1", "t2"], score: [5.1, 6.3, 4.8, 7.2] }
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare function pivotLonger(data: DataFrame, options: PivotLongerOptions): DataFrame;
|
|
75
|
+
/**
|
|
76
|
+
* Reshapes a data frame from long to wide: the values of `namesFrom` become columns, filled from `valuesFrom`.
|
|
77
|
+
* Equivalent to tidyr's `pivot_wider()`: one row per combination of the id columns (in order of first appearance),
|
|
78
|
+
* the new columns in order of first appearance of their names (unless `namesSort`). A cell that no row fills is
|
|
79
|
+
* `valuesFill` (default missing). A cell that several rows fill is an error unless `valuesFn` summarises the values
|
|
80
|
+
* (tidyr makes a list column there, which a data frame here cannot hold).
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* const long = { id: ["s1", "s1", "s2"], time: ["t1", "t2", "t1"], score: [5.1, 6.3, 4.8] };
|
|
85
|
+
* pivotWider(long, { namesFrom: "time", valuesFrom: "score" });
|
|
86
|
+
* // { id: ["s1", "s2"], t1: [5.1, 4.8], t2: [6.3, null] }
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export declare function pivotWider(data: DataFrame, options?: PivotWiderOptions): DataFrame;
|