@numero-uno-jpn/rstats 0.9.0 → 0.10.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 +63 -0
- package/README.ja.md +60 -11
- package/README.md +59 -10
- package/THIRD_PARTY_NOTICES.md +7 -2
- package/dist/chunks/{chunk-H2AP6TCR.js → chunk-2XKG3DX4.js} +1 -1
- package/dist/chunks/{chunk-FC2TLHZC.js → chunk-4NM37MGA.js} +2 -2
- package/dist/chunks/chunk-7HPVUVZB.js +2 -0
- package/dist/chunks/{chunk-YC4JWUKG.js → chunk-AECGWZHD.js} +2 -2
- package/dist/chunks/{chunk-LE7TBHNI.js → chunk-ENL43FNO.js} +2 -2
- package/dist/chunks/chunk-EWC6I75B.js +2 -0
- package/dist/chunks/chunk-IT354SHV.js +3 -0
- package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-LIMZKONM.js} +2 -2
- package/dist/chunks/chunk-O6PT7IVU.js +2 -0
- package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-QFULZNHL.js} +1 -1
- package/dist/chunks/{chunk-5K4PS7IV.js → chunk-QJJWGNJP.js} +2 -2
- package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-QULPY6YM.js} +1 -1
- package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
- package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
- package/dist/descriptive/factanal.d.ts +56 -0
- package/dist/descriptive/factanal.js +186 -0
- package/dist/descriptive/omega.d.ts +56 -0
- package/dist/descriptive/omega.js +323 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/bvnorm.d.ts +15 -0
- package/dist/distributions/bvnorm.js +131 -0
- package/dist/distributions/nbeta.js +34 -1
- package/dist/distributions/nchisq.d.ts +10 -0
- package/dist/distributions/nchisq.js +46 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +1 -0
- package/dist/entries/linalg.d.ts +2 -0
- package/dist/entries/linalg.js +2 -0
- package/dist/entries/numerics.d.ts +2 -0
- package/dist/entries/numerics.js +1 -0
- package/dist/entries/tests.d.ts +22 -1
- package/dist/entries/tests.js +19 -1
- package/dist/htest/agreement.d.ts +141 -0
- package/dist/htest/agreement.js +274 -0
- package/dist/htest/aov.d.ts +19 -0
- package/dist/htest/aov.js +22 -15
- package/dist/htest/core/simulate.d.ts +2 -0
- package/dist/htest/core/simulate.js +1 -1
- package/dist/htest/dunnett.d.ts +5 -0
- package/dist/htest/dunnett.js +89 -0
- package/dist/htest/effectSize.d.ts +112 -0
- package/dist/htest/effectSize.js +385 -0
- package/dist/htest/leveneTest.d.ts +30 -0
- package/dist/htest/leveneTest.js +41 -0
- package/dist/htest/multipleComparisons.d.ts +147 -0
- package/dist/htest/multipleComparisons.js +369 -0
- package/dist/htest/normalityTests.d.ts +44 -0
- package/dist/htest/normalityTests.js +164 -0
- package/dist/htest/polycor.d.ts +117 -0
- package/dist/htest/polycor.js +468 -0
- package/dist/htest/power.d.ts +132 -0
- package/dist/htest/power.js +227 -0
- package/dist/htest/pwr.d.ts +263 -0
- package/dist/htest/pwr.js +440 -0
- package/dist/htest/rankTests.d.ts +7 -0
- package/dist/htest/rankTests.js +11 -1
- package/dist/htest/trendTests.d.ts +57 -0
- package/dist/htest/trendTests.js +167 -0
- package/dist/linalg/eigen.d.ts +8 -0
- package/dist/linalg/eigen.js +5 -4
- package/dist/linalg/expm.d.ts +48 -0
- package/dist/linalg/expm.js +472 -0
- package/dist/linalg/schur.d.ts +48 -0
- package/dist/linalg/schur.js +225 -0
- package/dist/linalg.js +2 -2
- package/dist/models/anovaSequential.d.ts +58 -0
- package/dist/models/anovaSequential.js +138 -0
- package/dist/models/aovEz.d.ts +64 -0
- package/dist/models/aovEz.js +332 -0
- package/dist/models/aovStrata.d.ts +32 -0
- package/dist/models/aovStrata.js +104 -0
- package/dist/models/carAnova.d.ts +30 -0
- package/dist/models/carAnova.js +121 -0
- package/dist/models/coxph.d.ts +101 -0
- package/dist/models/coxph.js +502 -0
- package/dist/models/ddLeastSquares.d.ts +30 -0
- package/dist/models/ddLeastSquares.js +90 -0
- package/dist/models/ddMatrix.d.ts +10 -0
- package/dist/models/ddMatrix.js +91 -0
- package/dist/models/formula.d.ts +83 -0
- package/dist/models/formula.js +333 -0
- package/dist/models/lm.d.ts +84 -3
- package/dist/models/lm.js +141 -44
- package/dist/models/mauchly.d.ts +48 -0
- package/dist/models/mauchly.js +123 -0
- package/dist/models/modelFrame.d.ts +40 -0
- package/dist/models/modelFrame.js +131 -0
- package/dist/models/modelMatrix.d.ts +88 -0
- package/dist/models/modelMatrix.js +170 -0
- package/dist/models/survival.d.ts +87 -0
- package/dist/models/survival.js +238 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/lbfgsb.d.ts +20 -0
- package/dist/optim/lbfgsb.js +1240 -0
- package/dist/optim/optim.d.ts +85 -0
- package/dist/optim/optim.js +610 -0
- package/dist/rstats.js +19 -4
- package/dist/special.js +2 -2
- package/dist/tests.js +18 -4
- package/llms.txt +102 -0
- package/package.json +3 -2
- package/dist/chunks/chunk-24U4DKRY.js +0 -2
- package/dist/chunks/chunk-IVOBWYLV.js +0 -2
- package/dist/chunks/chunk-JLSTEMSN.js +0 -2
- package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
- package/dist/chunks/chunk-MSAUU6PY.js +0 -2
- package/dist/chunks/chunk-ZRO446BP.js +0 -2
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Model frames: the variables of a formula taken from a data frame, with the rows that have a missing value dropped
|
|
2
|
+
// and string and boolean columns turned into factors (R's model.frame with na.omit).
|
|
3
|
+
//
|
|
4
|
+
// Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Data and missing values"). Levels of a
|
|
5
|
+
// string column are its distinct values sorted by code point unless `levels` gives them; a boolean column has the
|
|
6
|
+
// levels FALSE and TRUE; numeric columns stay numeric. `dropUnusedLevels` removes the levels without a row left
|
|
7
|
+
// (R's drop.unused.levels = TRUE, used by lm and aov).
|
|
8
|
+
/** Comparison of strings by code point (not by UTF-16 code unit) */
|
|
9
|
+
export function compareCodePoints(a, b) {
|
|
10
|
+
const ia = a[Symbol.iterator]();
|
|
11
|
+
const ib = b[Symbol.iterator]();
|
|
12
|
+
for (;;) {
|
|
13
|
+
const x = ia.next();
|
|
14
|
+
const y = ib.next();
|
|
15
|
+
if (x.done)
|
|
16
|
+
return y.done ? 0 : -1;
|
|
17
|
+
if (y.done)
|
|
18
|
+
return 1;
|
|
19
|
+
const d = x.value.codePointAt(0) - y.value.codePointAt(0);
|
|
20
|
+
if (d !== 0)
|
|
21
|
+
return d;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** A column as a variable over all rows, with a missing flag per row */
|
|
25
|
+
function convert(name, col, levels) {
|
|
26
|
+
if (col instanceof Float64Array && levels === undefined) {
|
|
27
|
+
const values = Array.from(col);
|
|
28
|
+
return { v: { kind: "numeric", values }, missing: values.map((x) => Number.isNaN(x)) };
|
|
29
|
+
}
|
|
30
|
+
const vals = Array.from(col);
|
|
31
|
+
const kinds = new Set(vals.filter((x) => x !== null).map((x) => typeof x));
|
|
32
|
+
if (kinds.size > 1)
|
|
33
|
+
throw new TypeError(`column '${name}' mixes ${[...kinds].join(" and ")} values`);
|
|
34
|
+
const kind = [...kinds][0] ?? "number";
|
|
35
|
+
if (kind !== "number" && kind !== "string" && kind !== "boolean")
|
|
36
|
+
throw new TypeError(`column '${name}' has values of an unsupported type`);
|
|
37
|
+
if (kind === "number" && levels === undefined) {
|
|
38
|
+
const values = vals.map((x) => (x === null ? NaN : x));
|
|
39
|
+
return { v: { kind: "numeric", values }, missing: values.map((x) => Number.isNaN(x)) };
|
|
40
|
+
}
|
|
41
|
+
const str = (x) => x === null || (typeof x === "number" && Number.isNaN(x)) ? null : typeof x === "boolean" ? (x ? "TRUE" : "FALSE") : String(x);
|
|
42
|
+
const labels = vals.map(str);
|
|
43
|
+
let lev;
|
|
44
|
+
if (levels !== undefined)
|
|
45
|
+
lev = Array.from(levels, String);
|
|
46
|
+
else if (kind === "boolean")
|
|
47
|
+
lev = ["FALSE", "TRUE"];
|
|
48
|
+
else
|
|
49
|
+
lev = [...new Set(labels.filter((x) => x !== null))].sort(compareCodePoints);
|
|
50
|
+
const pos = new Map(lev.map((l, i) => [l, i]));
|
|
51
|
+
const codes = labels.map((l) => (l === null ? -1 : (pos.get(l) ?? -1)));
|
|
52
|
+
return { v: { kind: "factor", levels: lev, codes }, missing: codes.map((c) => c < 0) };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The model frame of the given variables: each variable taken from the data, the rows with a missing value in any
|
|
56
|
+
* of them (or in the weights) dropped.
|
|
57
|
+
*
|
|
58
|
+
* Errors as R: `object 'Q' not found` for a variable that is not a column, `variable lengths differ (found for 'x')`
|
|
59
|
+
* for columns of different lengths.
|
|
60
|
+
*/
|
|
61
|
+
export function modelFrame(data, names, options = {}) {
|
|
62
|
+
if (typeof data !== "object" || data === null)
|
|
63
|
+
throw new TypeError("data must be an object of columns");
|
|
64
|
+
const cols = names.map((v) => {
|
|
65
|
+
const c = Object.prototype.hasOwnProperty.call(data, v) ? data[v] : undefined;
|
|
66
|
+
if (c === undefined)
|
|
67
|
+
throw new Error(`object '${v}' not found`);
|
|
68
|
+
if (!Array.isArray(c) && !(c instanceof Float64Array))
|
|
69
|
+
throw new TypeError(`column '${v}' must be an array`);
|
|
70
|
+
return c;
|
|
71
|
+
});
|
|
72
|
+
let w;
|
|
73
|
+
if (typeof options.weights === "string") {
|
|
74
|
+
const c = Object.prototype.hasOwnProperty.call(data, options.weights) ? data[options.weights] : undefined;
|
|
75
|
+
if (c === undefined)
|
|
76
|
+
throw new Error(`object '${options.weights}' not found`);
|
|
77
|
+
w = c;
|
|
78
|
+
}
|
|
79
|
+
else if (options.weights !== undefined)
|
|
80
|
+
w = Array.from(options.weights);
|
|
81
|
+
const n = cols.length > 0 ? cols[0].length : (w?.length ?? Object.values(data)[0]?.length ?? 0);
|
|
82
|
+
names.forEach((v, i) => {
|
|
83
|
+
if (cols[i].length !== n)
|
|
84
|
+
throw new RangeError(`variable lengths differ (found for '${v}')`);
|
|
85
|
+
});
|
|
86
|
+
if (w !== undefined && w.length !== n)
|
|
87
|
+
throw new RangeError("variable lengths differ (found for '(weights)')");
|
|
88
|
+
const conv = names.map((v, i) => convert(v, cols[i], options.levels?.[v]));
|
|
89
|
+
let weights;
|
|
90
|
+
if (w !== undefined) {
|
|
91
|
+
weights = Array.from(w, (x) => {
|
|
92
|
+
if (x === null)
|
|
93
|
+
return NaN;
|
|
94
|
+
if (typeof x !== "number")
|
|
95
|
+
throw new TypeError("the weights must be numeric");
|
|
96
|
+
return x;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const rows = [];
|
|
100
|
+
for (let i = 0; i < n; i++) {
|
|
101
|
+
if (conv.some((c) => c.missing[i]) || (weights !== undefined && Number.isNaN(weights[i])))
|
|
102
|
+
continue;
|
|
103
|
+
rows.push(i);
|
|
104
|
+
}
|
|
105
|
+
const variables = conv.map(({ v }) => {
|
|
106
|
+
if (v.kind === "numeric")
|
|
107
|
+
return { kind: "numeric", values: rows.map((i) => v.values[i]) };
|
|
108
|
+
let codes = rows.map((i) => v.codes[i]);
|
|
109
|
+
let levels = v.levels;
|
|
110
|
+
if (options.dropUnusedLevels) {
|
|
111
|
+
const used = levels.map(() => false);
|
|
112
|
+
for (const c of codes)
|
|
113
|
+
used[c] = true;
|
|
114
|
+
const map = new Map();
|
|
115
|
+
levels = levels.filter((_, k) => {
|
|
116
|
+
if (used[k])
|
|
117
|
+
map.set(k, map.size);
|
|
118
|
+
return used[k];
|
|
119
|
+
});
|
|
120
|
+
codes = codes.map((c) => map.get(c));
|
|
121
|
+
}
|
|
122
|
+
return { kind: "factor", levels, codes };
|
|
123
|
+
});
|
|
124
|
+
const out = { rows, variables };
|
|
125
|
+
if (weights !== undefined) {
|
|
126
|
+
out.weights = rows.map((i) => weights[i]);
|
|
127
|
+
if (out.weights.some((x) => x < 0))
|
|
128
|
+
throw new RangeError("missing or negative weights not allowed");
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { type FormulaNode, type ParsedFormula, type Terms } from "./formula.js";
|
|
2
|
+
import { type DataFrame, type ModelFrame } from "./modelFrame.js";
|
|
3
|
+
import type { Sample } from "../htest/types.js";
|
|
4
|
+
/** A contrast of a factor: R's `contr.treatment`, `contr.sum` or `contr.helmert`. */
|
|
5
|
+
export type ContrastName = "contr.treatment" | "contr.sum" | "contr.helmert";
|
|
6
|
+
/** Options for {@link modelMatrix}. */
|
|
7
|
+
export interface ModelMatrixOptions {
|
|
8
|
+
/** A contrast per factor (default `"contr.treatment"`). */
|
|
9
|
+
contrasts?: Record<string, ContrastName>;
|
|
10
|
+
/** The order of the levels of a factor (`{ A: ["c", "a", "b"] }`), as `factor(x, levels = ...)` in R. */
|
|
11
|
+
levels?: Record<string, readonly string[]>;
|
|
12
|
+
}
|
|
13
|
+
/** Result of {@link modelMatrix}. */
|
|
14
|
+
export interface ModelMatrixResult {
|
|
15
|
+
/** Column names, such as `"(Intercept)"`, `"Ab"`, `"Ab:Bq"`, `"x"`. */
|
|
16
|
+
colNames: string[];
|
|
17
|
+
/** The term of each column (0 for the intercept, 1 for the first term). */
|
|
18
|
+
assign: number[];
|
|
19
|
+
/** The model matrix (array of rows). */
|
|
20
|
+
x: number[][];
|
|
21
|
+
/** 0-based indices of the rows of the data used (rows with a missing value are dropped). */
|
|
22
|
+
rows: number[];
|
|
23
|
+
/** Labels of the terms (variables joined by `:`). */
|
|
24
|
+
termLabels: string[];
|
|
25
|
+
/** Degree of each term. */
|
|
26
|
+
order: number[];
|
|
27
|
+
/** Whether the model has an intercept. */
|
|
28
|
+
intercept: boolean;
|
|
29
|
+
/** The variables of the formula, the response first. */
|
|
30
|
+
variables: string[];
|
|
31
|
+
/** R's factors attribute: one array per variable, one code per term (0 not in it, 1 contrasts, 2 indicators). */
|
|
32
|
+
factors: number[][];
|
|
33
|
+
/** R's warnings. */
|
|
34
|
+
warnings: string[];
|
|
35
|
+
}
|
|
36
|
+
/** A contrast matrix (one row per level) and its column names */
|
|
37
|
+
export declare function contrastMatrix(levels: readonly string[], contrast: ContrastName | "indicators"): {
|
|
38
|
+
m: number[][];
|
|
39
|
+
names: string[];
|
|
40
|
+
};
|
|
41
|
+
/** A model matrix with what the fits need. */
|
|
42
|
+
export interface Design {
|
|
43
|
+
terms: Terms;
|
|
44
|
+
frame: ModelFrame;
|
|
45
|
+
/** The model matrix (array of rows) */
|
|
46
|
+
x: number[][];
|
|
47
|
+
colNames: string[];
|
|
48
|
+
assign: number[];
|
|
49
|
+
/** The response's values (rows kept), if the formula has one */
|
|
50
|
+
y?: number[];
|
|
51
|
+
warnings: string[];
|
|
52
|
+
}
|
|
53
|
+
/** Options of {@link design} */
|
|
54
|
+
export interface DesignOptions extends ModelMatrixOptions {
|
|
55
|
+
weights?: Sample | string;
|
|
56
|
+
dropUnusedLevels?: boolean;
|
|
57
|
+
/** Contrast used for every factor instead of `contrasts` (the error model of aov) */
|
|
58
|
+
allContrasts?: ContrastName;
|
|
59
|
+
/** The intercept flag to use instead of the formula's (the error model of aov) */
|
|
60
|
+
intercept?: boolean;
|
|
61
|
+
/** More variables whose missing values drop rows (the rest of the formula, for the error model of aov) */
|
|
62
|
+
extraVariables?: readonly string[];
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The model matrix of a parsed formula on the data.
|
|
66
|
+
*
|
|
67
|
+
* @param rhs The right-hand side to use (default: the formula's; aov passes it without the Error() term).
|
|
68
|
+
*/
|
|
69
|
+
export declare function design(parsed: ParsedFormula, data: DataFrame, options?: DesignOptions, rhs?: FormulaNode | undefined): Design;
|
|
70
|
+
/**
|
|
71
|
+
* The model matrix of a formula on a data frame, with the attributes of R's `terms()`. Equivalent to R's
|
|
72
|
+
* `model.matrix(formula, data)` (with `contrasts.arg`), together with `attr(terms(formula), ...)`.
|
|
73
|
+
*
|
|
74
|
+
* Strings are factors (levels sorted by code point unless `levels` gives them), booleans factors with levels FALSE
|
|
75
|
+
* and TRUE, numbers numeric. Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the
|
|
76
|
+
* formula are dropped; levels without rows are kept (their columns are 0).
|
|
77
|
+
*
|
|
78
|
+
* @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
|
|
79
|
+
* @param data The data frame: an object of columns.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```ts
|
|
83
|
+
* const m = modelMatrix("y ~ A", { y: [1, 2, 3, 4], A: ["a", "b", "a", "b"] });
|
|
84
|
+
* m.colNames; // ["(Intercept)", "Ab"]
|
|
85
|
+
* m.x; // [[1, 0], [1, 1], [1, 0], [1, 1]]
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
export declare function modelMatrix(formula: string, data: DataFrame, options?: ModelMatrixOptions): ModelMatrixResult;
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// Model matrices from formulas: R's model.matrix(formula, data) with the attributes of terms().
|
|
2
|
+
//
|
|
3
|
+
// Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Coding"). Each term contributes the
|
|
4
|
+
// products of one column of each of its variables, the first variable varying fastest: a numeric variable's values,
|
|
5
|
+
// or a factor's contrast columns (contr.treatment, contr.sum or contr.helmert) or indicator columns, as chosen by the
|
|
6
|
+
// codes of src/models/formula.ts. Without an intercept the first factor found is coded by indicators.
|
|
7
|
+
import { parseFormula, termsOf } from "./formula.js";
|
|
8
|
+
import { modelFrame } from "./modelFrame.js";
|
|
9
|
+
/** A contrast matrix (one row per level) and its column names */
|
|
10
|
+
export function contrastMatrix(levels, contrast) {
|
|
11
|
+
const k = levels.length;
|
|
12
|
+
const m = levels.map(() => []);
|
|
13
|
+
let names;
|
|
14
|
+
switch (contrast) {
|
|
15
|
+
case "indicators":
|
|
16
|
+
levels.forEach((_, i) => levels.forEach((__, j) => m[i].push(i === j ? 1 : 0)));
|
|
17
|
+
names = [...levels];
|
|
18
|
+
break;
|
|
19
|
+
case "contr.treatment":
|
|
20
|
+
levels.forEach((_, i) => {
|
|
21
|
+
for (let j = 1; j < k; j++)
|
|
22
|
+
m[i].push(i === j ? 1 : 0);
|
|
23
|
+
});
|
|
24
|
+
names = levels.slice(1);
|
|
25
|
+
break;
|
|
26
|
+
case "contr.sum":
|
|
27
|
+
levels.forEach((_, i) => {
|
|
28
|
+
for (let j = 0; j < k - 1; j++)
|
|
29
|
+
m[i].push(i === j ? 1 : i === k - 1 ? -1 : 0);
|
|
30
|
+
});
|
|
31
|
+
names = Array.from({ length: k - 1 }, (_, j) => String(j + 1));
|
|
32
|
+
break;
|
|
33
|
+
case "contr.helmert":
|
|
34
|
+
levels.forEach((_, i) => {
|
|
35
|
+
for (let j = 1; j < k; j++)
|
|
36
|
+
m[i].push(i < j ? -1 : i === j ? j : 0);
|
|
37
|
+
});
|
|
38
|
+
names = Array.from({ length: k - 1 }, (_, j) => String(j + 1));
|
|
39
|
+
break;
|
|
40
|
+
default:
|
|
41
|
+
throw new RangeError(`unknown contrast '${String(contrast)}'`);
|
|
42
|
+
}
|
|
43
|
+
return { m, names };
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The model matrix of a parsed formula on the data.
|
|
47
|
+
*
|
|
48
|
+
* @param rhs The right-hand side to use (default: the formula's; aov passes it without the Error() term).
|
|
49
|
+
*/
|
|
50
|
+
export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
51
|
+
if (typeof data !== "object" || data === null)
|
|
52
|
+
throw new TypeError("data must be an object of columns");
|
|
53
|
+
const terms = termsOf(parsed, Object.keys(data), rhs);
|
|
54
|
+
if (options.intercept !== undefined)
|
|
55
|
+
terms.intercept = options.intercept;
|
|
56
|
+
const frameNames = [...terms.variables, ...(options.extraVariables ?? []).filter((v) => !terms.variables.includes(v))];
|
|
57
|
+
const frameOptions = {};
|
|
58
|
+
if (options.levels !== undefined)
|
|
59
|
+
frameOptions.levels = options.levels;
|
|
60
|
+
if (options.weights !== undefined)
|
|
61
|
+
frameOptions.weights = options.weights;
|
|
62
|
+
if (options.dropUnusedLevels !== undefined)
|
|
63
|
+
frameOptions.dropUnusedLevels = options.dropUnusedLevels;
|
|
64
|
+
const frame = modelFrame(data, frameNames, frameOptions);
|
|
65
|
+
const vars = frame.variables;
|
|
66
|
+
const nr = frame.rows.length;
|
|
67
|
+
// the terms that get columns, and the code of each variable in them
|
|
68
|
+
const used = terms.terms.map((_, j) => j !== terms.responseTerm);
|
|
69
|
+
const codes = terms.terms.map((t, j) => t.map((v) => terms.factors[v][j]));
|
|
70
|
+
for (let j = 0; j < terms.terms.length; j++) {
|
|
71
|
+
if (!used[j])
|
|
72
|
+
continue;
|
|
73
|
+
for (const v of terms.terms[j]) {
|
|
74
|
+
const fv = vars[v];
|
|
75
|
+
if (fv.kind === "factor" && fv.levels.length < 2)
|
|
76
|
+
throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (!terms.intercept) {
|
|
80
|
+
search: for (let j = 0; j < terms.terms.length; j++) {
|
|
81
|
+
if (!used[j])
|
|
82
|
+
continue;
|
|
83
|
+
const t = terms.terms[j];
|
|
84
|
+
for (let k = 0; k < t.length; k++) {
|
|
85
|
+
if (vars[t[k]].kind === "factor") {
|
|
86
|
+
codes[j][k] = 2;
|
|
87
|
+
break search;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const columns = [];
|
|
93
|
+
const colNames = [];
|
|
94
|
+
const assign = [];
|
|
95
|
+
if (terms.intercept) {
|
|
96
|
+
columns.push(new Array(nr).fill(1));
|
|
97
|
+
colNames.push("(Intercept)");
|
|
98
|
+
assign.push(0);
|
|
99
|
+
}
|
|
100
|
+
const partsOf = (v, code) => {
|
|
101
|
+
const fv = vars[v];
|
|
102
|
+
const name = terms.variables[v];
|
|
103
|
+
if (fv.kind === "numeric")
|
|
104
|
+
return [{ name, values: fv.values }];
|
|
105
|
+
const contrast = code === 2 ? "indicators" : (options.allContrasts ?? options.contrasts?.[name] ?? "contr.treatment");
|
|
106
|
+
const { m, names } = contrastMatrix(fv.levels, contrast);
|
|
107
|
+
return names.map((cn, j) => ({ name: name + cn, values: fv.codes.map((c) => m[c][j]) }));
|
|
108
|
+
};
|
|
109
|
+
terms.terms.forEach((t, j) => {
|
|
110
|
+
if (!used[j])
|
|
111
|
+
return;
|
|
112
|
+
let cur = partsOf(t[0], codes[j][0]);
|
|
113
|
+
for (let k = 1; k < t.length; k++) {
|
|
114
|
+
const next = [];
|
|
115
|
+
for (const p of partsOf(t[k], codes[j][k])) {
|
|
116
|
+
for (const c of cur)
|
|
117
|
+
next.push({ name: `${c.name}:${p.name}`, values: c.values.map((v, i) => v * p.values[i]) });
|
|
118
|
+
}
|
|
119
|
+
cur = next;
|
|
120
|
+
}
|
|
121
|
+
for (const c of cur) {
|
|
122
|
+
columns.push(c.values);
|
|
123
|
+
colNames.push(c.name);
|
|
124
|
+
assign.push(j + 1);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
const x = Array.from({ length: nr }, (_, i) => columns.map((c) => c[i]));
|
|
128
|
+
const out = { terms, frame, x, colNames, assign, warnings: [...terms.warnings] };
|
|
129
|
+
if (terms.response >= 0) {
|
|
130
|
+
const r = vars[terms.response];
|
|
131
|
+
if (r.kind !== "numeric")
|
|
132
|
+
throw new TypeError("the response must be numeric");
|
|
133
|
+
out.y = r.values;
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The model matrix of a formula on a data frame, with the attributes of R's `terms()`. Equivalent to R's
|
|
139
|
+
* `model.matrix(formula, data)` (with `contrasts.arg`), together with `attr(terms(formula), ...)`.
|
|
140
|
+
*
|
|
141
|
+
* Strings are factors (levels sorted by code point unless `levels` gives them), booleans factors with levels FALSE
|
|
142
|
+
* and TRUE, numbers numeric. Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the
|
|
143
|
+
* formula are dropped; levels without rows are kept (their columns are 0).
|
|
144
|
+
*
|
|
145
|
+
* @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
|
|
146
|
+
* @param data The data frame: an object of columns.
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* ```ts
|
|
150
|
+
* const m = modelMatrix("y ~ A", { y: [1, 2, 3, 4], A: ["a", "b", "a", "b"] });
|
|
151
|
+
* m.colNames; // ["(Intercept)", "Ab"]
|
|
152
|
+
* m.x; // [[1, 0], [1, 1], [1, 0], [1, 1]]
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
export function modelMatrix(formula, data, options = {}) {
|
|
156
|
+
const d = design(parseFormula(formula), data, options);
|
|
157
|
+
return {
|
|
158
|
+
colNames: d.colNames,
|
|
159
|
+
assign: d.assign,
|
|
160
|
+
x: d.x,
|
|
161
|
+
rows: d.frame.rows,
|
|
162
|
+
termLabels: d.terms.termLabels,
|
|
163
|
+
order: d.terms.order,
|
|
164
|
+
intercept: d.terms.intercept,
|
|
165
|
+
variables: d.terms.variables,
|
|
166
|
+
// R's factors attribute is empty for a model without terms
|
|
167
|
+
factors: d.terms.terms.length > 0 ? d.terms.factors : [],
|
|
168
|
+
warnings: d.warnings,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { GroupLabel } from "../htest/groups.js";
|
|
2
|
+
/** Options for {@link survdiff}. */
|
|
3
|
+
export interface SurvdiffOptions {
|
|
4
|
+
/** Exponent of the weights S(t-)^rho (pooled Kaplan-Meier estimate just before each event time). Default 0. */
|
|
5
|
+
rho?: number;
|
|
6
|
+
}
|
|
7
|
+
/** Result of {@link survdiff}. */
|
|
8
|
+
export interface SurvdiffResult {
|
|
9
|
+
/** Number of observations per group */
|
|
10
|
+
n: number[];
|
|
11
|
+
/** R's names of the groups, `"group=<label>"`, in the order of the sorted labels */
|
|
12
|
+
groups: string[];
|
|
13
|
+
/** Weighted observed number of events per group */
|
|
14
|
+
obs: number[];
|
|
15
|
+
/** Weighted expected number of events per group */
|
|
16
|
+
exp: number[];
|
|
17
|
+
/** Variance matrix of obs - exp (array of rows) */
|
|
18
|
+
var: number[][];
|
|
19
|
+
/** Chi-squared statistic */
|
|
20
|
+
chisq: number;
|
|
21
|
+
/** Upper chi-squared tail on (number of groups with a positive expected count) - 1 degrees of freedom */
|
|
22
|
+
pvalue: number;
|
|
23
|
+
}
|
|
24
|
+
/** Confidence interval type of {@link survfit}. */
|
|
25
|
+
export type SurvfitConfType = "log" | "plain" | "log-log";
|
|
26
|
+
/** Options for {@link survfit}. */
|
|
27
|
+
export interface SurvfitOptions {
|
|
28
|
+
/** Group labels, one per observation: one curve per group. Omitted: a single curve. */
|
|
29
|
+
group?: readonly GroupLabel[];
|
|
30
|
+
/** Transformation of the pointwise confidence intervals. Default `"log"`. */
|
|
31
|
+
confType?: SurvfitConfType;
|
|
32
|
+
/** Confidence level. Default 0.95. */
|
|
33
|
+
confInt?: number;
|
|
34
|
+
}
|
|
35
|
+
/** Result of {@link survfit}: the rows of R's `summary(fit, censored = TRUE)` and the medians. */
|
|
36
|
+
export interface SurvfitResult {
|
|
37
|
+
/** Stratum of each row (`"group=<label>"`, or `"all"` for a single curve) */
|
|
38
|
+
strata: string[];
|
|
39
|
+
time: number[];
|
|
40
|
+
nRisk: number[];
|
|
41
|
+
nEvent: number[];
|
|
42
|
+
nCensor: number[];
|
|
43
|
+
/** Kaplan-Meier estimate S(t) */
|
|
44
|
+
surv: number[];
|
|
45
|
+
/** Standard error of S(t) (S times the standard error of log S) */
|
|
46
|
+
stdErr: number[];
|
|
47
|
+
lower: number[];
|
|
48
|
+
upper: number[];
|
|
49
|
+
/** Per stratum, [median, lower limit, upper limit] (NaN for R's NA) */
|
|
50
|
+
median: number[][];
|
|
51
|
+
/** The strata of `median` */
|
|
52
|
+
medianRows: string[];
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Test of the difference between survival curves: the G-rho family of Harrington and Fleming, the log-rank test for
|
|
56
|
+
* `rho = 0`. Equivalent to R's `survdiff(Surv(time, status) ~ group, rho = rho)` (package survival).
|
|
57
|
+
*
|
|
58
|
+
* Rows with a missing time, status or group are dropped.
|
|
59
|
+
*
|
|
60
|
+
* @param time Follow-up times.
|
|
61
|
+
* @param status 1 for an event, 0 for a censored time.
|
|
62
|
+
* @param group Group labels, one per observation.
|
|
63
|
+
* @param options See {@link SurvdiffOptions}.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* survdiff([1, 2, 3, 4, 5, 6], [1, 1, 0, 1, 1, 1], ["a", "b", "a", "b", "a", "b"]).chisq;
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare function survdiff(time: readonly number[], status: readonly number[], group: readonly (GroupLabel | null)[], options?: SurvdiffOptions): SurvdiffResult;
|
|
71
|
+
/**
|
|
72
|
+
* Kaplan-Meier estimate of the survival function with Greenwood's standard error and pointwise confidence intervals.
|
|
73
|
+
* Equivalent to R's `summary(survfit(Surv(time, status) ~ group, conf.type, conf.int), censored = TRUE)` (package
|
|
74
|
+
* survival), with the medians and their confidence limits of `summary(fit)$table`.
|
|
75
|
+
*
|
|
76
|
+
* Rows with a missing time, status or group are dropped.
|
|
77
|
+
*
|
|
78
|
+
* @param time Follow-up times.
|
|
79
|
+
* @param status 1 for an event, 0 for a censored time.
|
|
80
|
+
* @param options See {@link SurvfitOptions}.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* survfit([1, 2, 2, 3, 4], [1, 1, 0, 1, 0]).surv; // [0.8, 0.6, 0.3, 0.3]
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
export declare function survfit(time: readonly number[], status: readonly number[], options?: SurvfitOptions): SurvfitResult;
|