@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.
Files changed (59) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.ja.md +11 -8
  3. package/README.md +10 -7
  4. package/dist/chunks/{chunk-7HPVUVZB.js → chunk-5WDJPHYY.js} +1 -1
  5. package/dist/chunks/{chunk-EWC6I75B.js → chunk-7GQMKH3Z.js} +1 -1
  6. package/dist/chunks/chunk-AHHS6AC4.js +3 -0
  7. package/dist/chunks/chunk-ALM3VHFP.js +2 -0
  8. package/dist/chunks/{chunk-QFULZNHL.js → chunk-C5XTWMGB.js} +1 -1
  9. package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
  10. package/dist/chunks/{chunk-QULPY6YM.js → chunk-EZAFN5CD.js} +1 -1
  11. package/dist/chunks/{chunk-2XKG3DX4.js → chunk-EZWBRCJL.js} +1 -1
  12. package/dist/chunks/{chunk-O6PT7IVU.js → chunk-F5EDJFEO.js} +2 -2
  13. package/dist/chunks/{chunk-4NM37MGA.js → chunk-JWBO5WVN.js} +2 -2
  14. package/dist/chunks/{chunk-ENL43FNO.js → chunk-TOGXTCZO.js} +2 -2
  15. package/dist/chunks/{chunk-IT354SHV.js → chunk-VJ4BDBMU.js} +2 -2
  16. package/dist/chunks/{chunk-ZRIM4R4A.js → chunk-Y5CNQ266.js} +2 -2
  17. package/dist/chunks/{chunk-LIMZKONM.js → chunk-Y5PYRAYP.js} +2 -2
  18. package/dist/chunks/{chunk-QJJWGNJP.js → chunk-YSWGDOWK.js} +2 -2
  19. package/dist/data/grouping.d.ts +79 -0
  20. package/dist/data/grouping.js +262 -0
  21. package/dist/descriptive/dataFrames.d.ts +110 -0
  22. package/dist/descriptive/dataFrames.js +392 -0
  23. package/dist/descriptive/missing.d.ts +35 -0
  24. package/dist/descriptive/missing.js +50 -0
  25. package/dist/descriptive/pivot.d.ts +89 -0
  26. package/dist/descriptive/pivot.js +343 -0
  27. package/dist/descriptive.js +2 -2
  28. package/dist/distributions.js +2 -2
  29. package/dist/entries/descriptive.d.ts +4 -0
  30. package/dist/entries/descriptive.js +4 -0
  31. package/dist/htest/ansariTest.d.ts +12 -0
  32. package/dist/htest/ansariTest.js +5 -17
  33. package/dist/htest/cor.d.ts +12 -0
  34. package/dist/htest/cor.js +9 -27
  35. package/dist/htest/ksTest.d.ts +13 -0
  36. package/dist/htest/ksTest.js +5 -8
  37. package/dist/htest/onewayTest.d.ts +14 -0
  38. package/dist/htest/onewayTest.js +5 -7
  39. package/dist/htest/rankTests.d.ts +57 -0
  40. package/dist/htest/rankTests.js +19 -31
  41. package/dist/htest/tTest.d.ts +20 -0
  42. package/dist/htest/tTest.js +19 -24
  43. package/dist/htest/testFormula.d.ts +57 -0
  44. package/dist/htest/testFormula.js +171 -0
  45. package/dist/htest/varTest.d.ts +23 -0
  46. package/dist/htest/varTest.js +11 -21
  47. package/dist/htest/wilcoxTest.d.ts +14 -0
  48. package/dist/htest/wilcoxTest.js +9 -24
  49. package/dist/linalg/ops.d.ts +13 -2
  50. package/dist/linalg/ops.js +20 -5
  51. package/dist/linalg.js +2 -2
  52. package/dist/numerics.js +2 -2
  53. package/dist/rstats.js +14 -14
  54. package/dist/special.js +2 -2
  55. package/dist/tests.js +12 -13
  56. package/llms.txt +12 -0
  57. package/package.json +1 -1
  58. package/dist/chunks/chunk-AECGWZHD.js +0 -2
  59. package/dist/chunks/chunk-XWTZ4RTR.js +0 -2
@@ -0,0 +1,262 @@
1
+ // Grouped summaries: R's tapply, split and aggregate.
2
+ //
3
+ // Written for rStats.js (no ported code) from oracle/grouping-behaviour.md. Group labels are turned into factors with
4
+ // the library's level rules: the sorted distinct non-missing values (numbers by value, strings by code point, FALSE
5
+ // before TRUE). With several factors the groups are the cells of their cross classification in column-major order
6
+ // (the first factor varies fastest). A row whose label is missing (null, or NaN in a numeric column) belongs to no
7
+ // group. tapply keeps the empty cells (NaN or null), split keeps them unless `drop`, aggregate leaves them out.
8
+ import { formatR } from "../htest/core/simulate.js";
9
+ import { parseFormula } from "../models/formula.js";
10
+ import { compareCodePoints } from "../models/modelFrame.js";
11
+ const isMissing = (v) => v === null || (typeof v === "number" && Number.isNaN(v));
12
+ const levelOrder = (a, b) => typeof a === "number" ? a - b : typeof a === "string" ? compareCodePoints(a, b) : Number(a) - Number(b);
13
+ /** A level as R names it: numbers as as.character (15 significant digits), booleans as TRUE and FALSE */
14
+ const levelName = (v) => typeof v === "boolean" ? (v ? "TRUE" : "FALSE") : typeof v === "string" ? v : Number.isFinite(v) ? formatR(v) : v > 0 ? "Inf" : "-Inf";
15
+ function factorOf(name, labels) {
16
+ const vals = Array.from(labels, (v) => (v === 0 ? 0 : v)); // -0 is the label 0
17
+ const kinds = new Set(vals.filter((v) => !isMissing(v)).map((v) => typeof v));
18
+ if (kinds.size > 1)
19
+ throw new TypeError(`${name} mixes ${[...kinds].join(" and ")} labels`);
20
+ const kind = [...kinds][0];
21
+ if (kind !== undefined && kind !== "number" && kind !== "string" && kind !== "boolean") {
22
+ throw new TypeError(`${name} has labels of an unsupported type`);
23
+ }
24
+ const levels = [...new Set(vals.filter((v) => !isMissing(v)))].sort(levelOrder);
25
+ const pos = new Map(levels.map((l, i) => [l, i]));
26
+ return { levels, codes: vals.map((v) => (isMissing(v) ? -1 : pos.get(v))) };
27
+ }
28
+ const isLabelArray = (v) => Array.isArray(v) || v instanceof Float64Array;
29
+ /** One array of labels, or an array of such arrays (one per factor), as a list of factors' labels */
30
+ function labelLists(index) {
31
+ if (index instanceof Float64Array)
32
+ return [index];
33
+ if (!Array.isArray(index))
34
+ throw new TypeError("the group labels must be an array or an array of arrays");
35
+ if (index.length > 0 && index.every(isLabelArray))
36
+ return [...index];
37
+ if (index.some(isLabelArray))
38
+ throw new TypeError("the group labels must be an array or an array of arrays");
39
+ return [index];
40
+ }
41
+ function groupingOf(lists, names, n) {
42
+ lists.forEach((l, j) => {
43
+ if (l.length !== n)
44
+ throw new RangeError(`${names[j]} must have one label per row (${n}), not ${l.length}`);
45
+ });
46
+ const factors = lists.map((l, j) => factorOf(names[j], l));
47
+ const size = factors.reduce((s, f) => s * f.levels.length, 1);
48
+ const cells = new Array(n);
49
+ for (let i = 0; i < n; i++) {
50
+ let cell = 0;
51
+ let stride = 1;
52
+ for (const f of factors) {
53
+ const c = f.codes[i];
54
+ if (c < 0) {
55
+ cell = -1;
56
+ break;
57
+ }
58
+ cell += c * stride;
59
+ stride *= f.levels.length;
60
+ }
61
+ cells[i] = cell;
62
+ }
63
+ return { factors, size, cells };
64
+ }
65
+ /** The rows (0-based) of each cell, in row order; an empty array for an empty cell */
66
+ function rowsByCell(g) {
67
+ const rows = Array.from({ length: g.size }, () => []);
68
+ g.cells.forEach((c, i) => {
69
+ if (c >= 0)
70
+ rows[c].push(i);
71
+ });
72
+ return rows;
73
+ }
74
+ /** The level of each factor in a cell */
75
+ function cellLevels(g, cell) {
76
+ return g.factors.map((f) => {
77
+ const k = f.levels.length;
78
+ const level = f.levels[cell % k];
79
+ cell = Math.floor(cell / k);
80
+ return level;
81
+ });
82
+ }
83
+ const factorNames = (count, what) => Array.from({ length: count }, (_, j) => (count === 1 ? what : `${what}[${j}]`));
84
+ /**
85
+ * The function applied to the values of each group. Equivalent to R's `tapply(x, index, fun)`.
86
+ *
87
+ * `index` is one array of group labels (one per value of `x`) or an array of such arrays, one per factor. The
88
+ * function is called only for the non-empty cells; a value of `x` whose label is missing is left out.
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * tapply([1, 2, 3, 4], ["b", "a", "b", "a"], (v) => v.length); // { dim: [2], dimnames: [["a", "b"]], values: [2, 2] }
93
+ * ```
94
+ */
95
+ export function tapply(x, index, fun) {
96
+ const xs = Array.from(x);
97
+ const lists = labelLists(index);
98
+ const g = groupingOf(lists, factorNames(lists.length, "index"), xs.length);
99
+ const results = rowsByCell(g).map((rows) => (rows.length === 0 ? null : { value: fun(rows.map((i) => xs[i])) }));
100
+ const scalar = results.every((r) => r === null || typeof r.value === "number");
101
+ const values = scalar ? results.map((r) => (r === null ? NaN : r.value)) : results.map((r) => (r === null ? null : r.value));
102
+ return {
103
+ dim: g.factors.map((f) => f.levels.length),
104
+ dimnames: g.factors.map((f) => [...f.levels]),
105
+ values: values,
106
+ };
107
+ }
108
+ /** The rows of a data frame, each column keeping its kind (array or Float64Array) */
109
+ function rowsOf(data, rows) {
110
+ const out = {};
111
+ for (const [name, col] of Object.entries(data)) {
112
+ out[name] = col instanceof Float64Array ? Float64Array.from(rows, (i) => col[i]) : rows.map((i) => col[i]);
113
+ }
114
+ return out;
115
+ }
116
+ function rowCount(data) {
117
+ const cols = Object.values(data);
118
+ const n = cols[0]?.length ?? 0;
119
+ for (const [name, col] of Object.entries(data)) {
120
+ if (!isLabelArray(col))
121
+ throw new TypeError(`column '${name}' must be an array`);
122
+ if (col.length !== n)
123
+ throw new RangeError(`the columns of the data frame have different lengths (found for '${name}')`);
124
+ }
125
+ return n;
126
+ }
127
+ export function split(x, f, options = {}) {
128
+ const sep = options.sep ?? ".";
129
+ const lists = labelLists(f);
130
+ const frame = !isLabelArray(x);
131
+ if (frame && (typeof x !== "object" || x === null))
132
+ throw new TypeError("x must be an array or a data frame");
133
+ const n = frame ? rowCount(x) : x.length;
134
+ const g = groupingOf(lists, factorNames(lists.length, "f"), n);
135
+ const xs = frame ? [] : Array.from(x);
136
+ const out = new Map();
137
+ rowsByCell(g).forEach((rows, cell) => {
138
+ if (rows.length === 0 && (options.drop || g.factors.length === 1))
139
+ return;
140
+ const name = cellLevels(g, cell).map(levelName).join(sep);
141
+ out.set(name, frame ? rowsOf(x, rows) : rows.map((i) => xs[i]));
142
+ });
143
+ return out;
144
+ }
145
+ /** A summarised column as numbers (null is NaN) */
146
+ function numericColumn(name, col) {
147
+ if (col === undefined)
148
+ throw new Error(`object '${name}' not found`);
149
+ if (!isLabelArray(col))
150
+ throw new TypeError(`column '${name}' must be an array`);
151
+ return Array.from(col, (v) => {
152
+ if (v === null)
153
+ return NaN;
154
+ if (typeof v !== "number")
155
+ throw new TypeError(`column '${name}' to summarise must be numeric`);
156
+ return v;
157
+ });
158
+ }
159
+ function labelColumn(data, name) {
160
+ const col = Object.prototype.hasOwnProperty.call(data, name) ? data[name] : undefined;
161
+ if (col === undefined)
162
+ throw new Error(`object '${name}' not found`);
163
+ if (!isLabelArray(col))
164
+ throw new TypeError(`column '${name}' must be an array`);
165
+ return col;
166
+ }
167
+ /** The variables of a right-hand side that is a sum of variables (`g`, `g + h`, ...) */
168
+ function summands(node, out) {
169
+ if (node.type === "var")
170
+ out.push(node.name);
171
+ else if (node.type === "binary" && node.op === "+") {
172
+ summands(node.left, out);
173
+ summands(node.right, out);
174
+ }
175
+ else if (node.type === "paren")
176
+ summands(node.arg, out);
177
+ else
178
+ throw new SyntaxError("invalid formula: the right-hand side must be grouping variables joined by '+'");
179
+ return out;
180
+ }
181
+ /** The summarised and the grouping columns of `y ~ g`, `y ~ g + h`, `cbind(y, z) ~ g` or `. ~ g` */
182
+ function aggregateFormula(formula, columns) {
183
+ if (typeof formula !== "string")
184
+ throw new TypeError("the formula must be a string");
185
+ const tilde = formula.indexOf("~");
186
+ if (tilde < 0)
187
+ throw new SyntaxError("invalid formula: missing '~'");
188
+ const lhs = formula.slice(0, tilde).trim();
189
+ const groups = summands(parseFormula(`~ ${formula.slice(tilde + 1)}`).rhs, []);
190
+ const name = /^[A-Za-z.][A-Za-z0-9._]*$/;
191
+ let values;
192
+ if (lhs === ".")
193
+ values = columns.filter((c) => !groups.includes(c));
194
+ else {
195
+ const m = /^cbind\s*\((.*)\)$/s.exec(lhs);
196
+ values = m === null ? [lhs] : m[1].split(",").map((s) => s.trim());
197
+ if (values.some((v) => !name.test(v) || v === ".")) {
198
+ throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'");
199
+ }
200
+ }
201
+ return { values, groups };
202
+ }
203
+ function aggregateRows(valueNames, valueCols, groupNames, groupCols, keep, fun) {
204
+ const n = groupCols[0]?.length ?? 0;
205
+ valueNames.forEach((v, j) => {
206
+ if (valueCols[j].length !== n)
207
+ throw new RangeError(`variable lengths differ (found for '${v}')`);
208
+ });
209
+ const g = groupingOf(groupCols, groupNames, n);
210
+ const cells = rowsByCell(g).map((rows, cell) => ({ cell, rows: rows.filter(keep) })).filter((c) => c.rows.length > 0);
211
+ const out = {};
212
+ const levels = cells.map((c) => cellLevels(g, c.cell));
213
+ groupNames.forEach((name, j) => {
214
+ out[name] = levels.map((l) => l[j]);
215
+ });
216
+ valueNames.forEach((name, j) => {
217
+ const col = valueCols[j];
218
+ const results = cells.map((c) => fun(c.rows.map((i) => col[i])));
219
+ const flat = results.map((r) => {
220
+ if (typeof r === "number")
221
+ return { names: undefined, values: [r] };
222
+ if (Array.isArray(r))
223
+ return { names: undefined, values: [...r] };
224
+ const rec = r;
225
+ return { names: Object.keys(rec), values: Object.values(rec) };
226
+ });
227
+ const k = flat[0]?.values.length ?? 1;
228
+ if (flat.some((r) => r.values.length !== k))
229
+ throw new RangeError("fun must return values of the same length for every group");
230
+ if (k === 1 && flat[0]?.names === undefined) {
231
+ out[name] = flat.map((r) => r.values[0]);
232
+ return;
233
+ }
234
+ for (let m = 0; m < k; m++) {
235
+ const suffix = flat[0].names?.[m] ?? String(m + 1);
236
+ out[`${name}.${suffix}`] = flat.map((r) => r.values[m]);
237
+ }
238
+ });
239
+ return out;
240
+ }
241
+ export function aggregate(first, second, fun) {
242
+ if (typeof second !== "object" || second === null)
243
+ throw new TypeError("the data must be an object of columns");
244
+ if (typeof first === "string") {
245
+ const data = second;
246
+ const { values, groups } = aggregateFormula(first, Object.keys(data));
247
+ const has = (v) => Object.prototype.hasOwnProperty.call(data, v);
248
+ const valueCols = values.map((v) => numericColumn(v, has(v) ? data[v] : undefined));
249
+ const groupCols = groups.map((v) => labelColumn(data, v));
250
+ const keep = (i) => valueCols.every((c) => !Number.isNaN(c[i])) && groupCols.every((c) => !isMissing(c[i]));
251
+ return aggregateRows(values, valueCols, groups, groupCols, keep, fun);
252
+ }
253
+ if (typeof first !== "object" || first === null)
254
+ throw new TypeError("x must be a data frame");
255
+ const values = Object.keys(first);
256
+ const valueCols = values.map((v) => numericColumn(v, first[v]));
257
+ const groups = Object.keys(second);
258
+ if (groups.length === 0)
259
+ throw new RangeError("'by' must name at least one grouping column");
260
+ const groupCols = groups.map((v) => labelColumn(second, v));
261
+ return aggregateRows(values, valueCols, groups, groupCols, () => true, fun);
262
+ }
@@ -0,0 +1,110 @@
1
+ import { type DataFrame } from "../models/modelFrame.js";
2
+ /** One value of a data frame column (`null`: missing). */
3
+ export type DataValue = number | string | boolean | null;
4
+ /** A row of a data frame, as passed to the condition of {@link subset}: column name to value. */
5
+ export type DataRow = Record<string, DataValue>;
6
+ /** One column of a data frame. */
7
+ export type Column = DataFrame[string];
8
+ /** The number of rows of a data frame (0 without columns); all columns must have the same length */
9
+ export declare function rowCount(frame: DataFrame): number;
10
+ export declare const isMissing: (v: DataValue | undefined) => boolean;
11
+ /** A copy of a column restricted to the given rows */
12
+ export declare function pick(col: Column, rows: readonly number[]): Column;
13
+ /** Adds a column to a result under construction; names must be unique */
14
+ export declare function addColumn(out: DataFrame, name: string, col: Column): void;
15
+ /** Comparison of two values for sorting: numbers as numbers, text by code point, FALSE before TRUE, missing last */
16
+ export declare function compareValues(a: DataValue, b: DataValue): number;
17
+ /** Options for {@link merge}. */
18
+ export interface MergeOptions {
19
+ /** The key columns, in both frames. Default: the column names common to both, in x's order. */
20
+ by?: string | readonly string[];
21
+ /** The key columns of x. Default `by`. */
22
+ byX?: string | readonly string[];
23
+ /** The key columns of y (as many as `byX`, matched in order). Default `by`. */
24
+ byY?: string | readonly string[];
25
+ /** Keep the rows of both frames that have no match. Default `false`. */
26
+ all?: boolean;
27
+ /** Keep the rows of x that have no match in y (y's columns missing). Default `all`. */
28
+ allX?: boolean;
29
+ /** Keep the rows of y that have no match in x (x's columns missing). Default `all`. */
30
+ allY?: boolean;
31
+ /** Order the rows by the key. Default `true`. */
32
+ sort?: boolean;
33
+ /** Appended to the names of the non-key columns that occur in both frames. Default `[".x", ".y"]`. */
34
+ suffixes?: readonly [string, string];
35
+ }
36
+ /**
37
+ * Join two data frames on key columns. Equivalent to R's `merge()` of data frames: every pair of rows of x and y with
38
+ * equal keys (missing keys match each other), and with `allX` / `allY` the rows without a match. Columns: the keys
39
+ * (named as in x), x's other columns, y's other columns; a non-key name present in both gets the suffixes. Rows are
40
+ * ordered by the key unless `sort` is false (several keys: as text joined with "\r" unless `allX` or `allY`, as R
41
+ * does); without key columns, the cross join (x varying fastest).
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * const x = { id: [3, 1, 2], v: [10, 20, 30] };
46
+ * const y = { id: [1, 2, 2, 4], w: [0.5, 1.5, 2.5, 3.5] };
47
+ * merge(x, y); // { id: [1, 2, 2], v: [20, 30, 30], w: [0.5, 1.5, 2.5] }
48
+ * merge(x, y, { all: true }); // also id 3 (w missing) and id 4 (v missing)
49
+ * ```
50
+ */
51
+ export declare function merge(x: DataFrame, y: DataFrame, options?: MergeOptions): DataFrame;
52
+ /** Options for {@link subset}. */
53
+ export interface SubsetOptions {
54
+ /** The columns to keep, in this order. Default: all, in their order. */
55
+ select?: readonly string[];
56
+ }
57
+ /**
58
+ * The rows of a data frame that meet a condition, and optionally some of its columns. Equivalent to R's `subset()`
59
+ * of a data frame: `keep` is a boolean per row or a function of the row; a missing (`null`) or non-boolean result
60
+ * counts as false, as R drops the rows whose condition is NA.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const d = { y: [5, NaN, 7, 2], g: ["a", "b", "a", "b"] };
65
+ * subset(d, (row) => (row.y as number) > 4); // { y: [5, 7], g: ["a", "a"] }
66
+ * subset(d, [true, true, false, false], { select: ["g"] }); // { g: ["a", "b"] }
67
+ * ```
68
+ */
69
+ export declare function subset(data: DataFrame, keep: readonly (boolean | null)[] | ((row: DataRow) => boolean | null | undefined), options?: SubsetOptions): DataFrame;
70
+ /**
71
+ * Stacks data frames with the same column names (matched by name, in the first frame's order). The data frame form
72
+ * of R's `rbind()`; see {@link rbind}.
73
+ */
74
+ export declare function rbindFrames(frames: readonly DataFrame[]): DataFrame;
75
+ /**
76
+ * Puts data frames with the same number of rows side by side. The data frame form of R's `cbind()`; see
77
+ * {@link cbind}. A column name that occurs twice is an error (an object cannot hold two columns of the same name).
78
+ */
79
+ export declare function cbindFrames(frames: readonly DataFrame[]): DataFrame;
80
+ /** Options of {@link fromRows}. */
81
+ export interface FromRowsOptions {
82
+ /**
83
+ * The columns to take, in this order. Default: every key that occurs in some row, in the order of first
84
+ * appearance.
85
+ */
86
+ columns?: readonly string[];
87
+ }
88
+ /**
89
+ * A data frame (an object of columns) from an array of row objects, the usual shape of JSON and of parsed CSV:
90
+ * `[{ age: 30, score: 5 }, { age: 41, score: 7 }]` becomes `{ age: [30, 41], score: [5, 7] }`. A key that a row
91
+ * lacks, and `undefined`, become `null` (a missing value). Values must be numbers, strings, booleans or `null`, and
92
+ * one column may not mix numbers, strings and booleans. Not an R function: R reads data as data frames directly.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * fromRows([{ id: "a", score: 5 }, { id: "b" }]); // { id: ["a", "b"], score: [5, null] }
97
+ * ```
98
+ */
99
+ export declare function fromRows(rows: readonly Readonly<Record<string, unknown>>[], options?: FromRowsOptions): DataFrame;
100
+ /**
101
+ * The rows of a data frame as an array of objects, the inverse of {@link fromRows}: `{ age: [30, 41], score: [5, 7]
102
+ * }` becomes `[{ age: 30, score: 5 }, { age: 41, score: 7 }]`. Missing values stay as they are (`null`, or `NaN` in a
103
+ * numeric column).
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * toRows({ id: ["a", "b"], score: [5, null] }); // [{ id: "a", score: 5 }, { id: "b", score: null }]
108
+ * ```
109
+ */
110
+ export declare function toRows(data: DataFrame): DataRow[];