@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.
- package/CHANGELOG.md +87 -0
- package/README.ja.md +64 -12
- package/README.md +63 -11
- package/THIRD_PARTY_NOTICES.md +7 -2
- package/dist/chunks/chunk-5WDJPHYY.js +2 -0
- package/dist/chunks/chunk-7GQMKH3Z.js +2 -0
- package/dist/chunks/chunk-AHHS6AC4.js +3 -0
- package/dist/chunks/chunk-ALM3VHFP.js +2 -0
- package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-C5XTWMGB.js} +1 -1
- package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
- package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-EZAFN5CD.js} +1 -1
- package/dist/chunks/{chunk-H2AP6TCR.js → chunk-EZWBRCJL.js} +1 -1
- package/dist/chunks/chunk-F5EDJFEO.js +2 -0
- package/dist/chunks/{chunk-FC2TLHZC.js → chunk-JWBO5WVN.js} +2 -2
- package/dist/chunks/{chunk-LE7TBHNI.js → chunk-TOGXTCZO.js} +2 -2
- package/dist/chunks/chunk-VJ4BDBMU.js +3 -0
- package/dist/chunks/chunk-Y5CNQ266.js +2 -0
- package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-Y5PYRAYP.js} +2 -2
- package/dist/chunks/{chunk-5K4PS7IV.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/factanal.d.ts +56 -0
- package/dist/descriptive/factanal.js +186 -0
- package/dist/descriptive/missing.d.ts +35 -0
- package/dist/descriptive/missing.js +50 -0
- package/dist/descriptive/omega.d.ts +56 -0
- package/dist/descriptive/omega.js +323 -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/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/descriptive.d.ts +4 -0
- package/dist/entries/descriptive.js +4 -0
- 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/ansariTest.d.ts +12 -0
- package/dist/htest/ansariTest.js +5 -17
- package/dist/htest/aov.d.ts +19 -0
- package/dist/htest/aov.js +22 -15
- package/dist/htest/cor.d.ts +12 -0
- package/dist/htest/cor.js +9 -27
- 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/ksTest.d.ts +13 -0
- package/dist/htest/ksTest.js +5 -8
- 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/onewayTest.d.ts +14 -0
- package/dist/htest/onewayTest.js +5 -7
- 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 +64 -0
- package/dist/htest/rankTests.js +27 -29
- 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/trendTests.d.ts +57 -0
- package/dist/htest/trendTests.js +167 -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/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/ops.d.ts +13 -2
- package/dist/linalg/ops.js +20 -5
- 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 +17 -4
- package/llms.txt +114 -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-YC4JWUKG.js +0 -2
- package/dist/chunks/chunk-ZRO446BP.js +0 -2
|
@@ -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,56 @@
|
|
|
1
|
+
/** Options of {@link omega} */
|
|
2
|
+
export interface OmegaOptions {
|
|
3
|
+
/** The number of first-order (group) factors. Default 3. */
|
|
4
|
+
nfactors?: number;
|
|
5
|
+
/** A correlation (or covariance) matrix to analyse instead of the data `x` (pass `null` as `x`). */
|
|
6
|
+
covmat?: readonly (readonly number[])[];
|
|
7
|
+
}
|
|
8
|
+
/** Result of {@link omega} */
|
|
9
|
+
export interface OmegaResult {
|
|
10
|
+
/** Omega hierarchical: the share of the total variance due to the general factor */
|
|
11
|
+
omegaH: number;
|
|
12
|
+
/** Omega asymptotic: the general factor's share of the common variance */
|
|
13
|
+
omegaLim: number;
|
|
14
|
+
/** Cronbach's alpha (standardised: of the correlations) */
|
|
15
|
+
alpha: number;
|
|
16
|
+
/** Omega total */
|
|
17
|
+
omegaTot: number;
|
|
18
|
+
/** Guttman's lambda 6 */
|
|
19
|
+
G6: number;
|
|
20
|
+
/** Explained common variance of the general factor */
|
|
21
|
+
ECV: number;
|
|
22
|
+
/** The Schmid-Leiman matrix, p rows; columns as `slNames` */
|
|
23
|
+
sl: number[][];
|
|
24
|
+
/** `["g", "F1*", ..., "h2", "u2", "p2", "com"]` */
|
|
25
|
+
slNames: string[];
|
|
26
|
+
/** The varimax loadings of the first-order minres solution */
|
|
27
|
+
orthog: number[][];
|
|
28
|
+
/** The oblimin pattern (the varimax loadings for one factor) */
|
|
29
|
+
oblique: number[][];
|
|
30
|
+
/** The factor correlations (absent for one factor) */
|
|
31
|
+
phi?: number[][];
|
|
32
|
+
/** The loadings of the first-order factors on the general factor */
|
|
33
|
+
gloading: number[];
|
|
34
|
+
/** The item signs (-1 for a flipped item) */
|
|
35
|
+
key: number[];
|
|
36
|
+
/** Rows g, F1*, ...; columns total, general, group (NaN for a group with no items) */
|
|
37
|
+
omegaGroup: number[][];
|
|
38
|
+
warnings: string[];
|
|
39
|
+
messages: string[];
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* McDonald's omega (hierarchical, asymptotic and total) from a Schmid-Leiman transformation of an oblique minres
|
|
43
|
+
* factor solution. Equivalent to R's `psych::omega(x, nfactors)` with its defaults (`fm = "minres"`, `rotate =
|
|
44
|
+
* "oblimin"`, `option = "equal"`, `flip = TRUE`).
|
|
45
|
+
*
|
|
46
|
+
* @param x The data matrix (array of rows, NaN for missing values: correlations of pairwise complete observations),
|
|
47
|
+
* or `null` with `options.covmat`.
|
|
48
|
+
* @param options See {@link OmegaOptions}.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* const om = omega(x); // x: an n x 12 data matrix
|
|
53
|
+
* om.omegaH; om.omegaTot; om.sl;
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export declare function omega(x: readonly (readonly number[])[] | null, options?: OmegaOptions): OmegaResult;
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// McDonald's omega, psych's omega() with its defaults (minres factoring, varimax then oblimin, a Schmid-Leiman
|
|
2
|
+
// transformation, items with a negative general loading flipped). Written for rStats.js from the specification
|
|
3
|
+
// oracle/omega-behaviour.md (no R, psych or GPArotation code was read or used): the minres uniquenesses minimise
|
|
4
|
+
// the off-diagonal residuals by L-BFGS-B (this library's optim), the oblique rotation is GPArotation's quartimin
|
|
5
|
+
// with its Barzilai-Borwein step and non-monotone line search, and the general factor comes from a one-factor
|
|
6
|
+
// minres analysis of the factor correlations.
|
|
7
|
+
import { eigen } from "../linalg/eigen.js";
|
|
8
|
+
import { solve } from "../linalg/solve.js";
|
|
9
|
+
import { svd } from "../linalg/svd.js";
|
|
10
|
+
import { optim } from "../optim/optim.js";
|
|
11
|
+
import { cor } from "./cov.js";
|
|
12
|
+
import { sumOnce, varimax } from "./factanal.js";
|
|
13
|
+
const EPS = 2 ** -52;
|
|
14
|
+
const TWO_FACTOR_MESSAGE = "\nThree factors are required for identification -- general factor loadings set to be equal. \nProceed with caution. \nThink about redoing the analysis with alternative values of the 'option' setting.\n\n";
|
|
15
|
+
const matMul = (A, B) => A.map((row) => B[0].map((_, j) => {
|
|
16
|
+
let s = 0;
|
|
17
|
+
for (let k = 0; k < row.length; k++)
|
|
18
|
+
s += row[k] * B[k][j];
|
|
19
|
+
return s;
|
|
20
|
+
}));
|
|
21
|
+
const transpose = (A) => A[0].map((_, j) => A.map((r) => r[j]));
|
|
22
|
+
const colSums = (m, f = (v) => v) => m[0].map((_, j) => sumOnce(m.map((r) => f(r[j]))));
|
|
23
|
+
const rowSums = (m, f = (v) => v) => m.map((r) => sumOnce(r.map(f)));
|
|
24
|
+
/** Sum of all entries (column by column, as R) */
|
|
25
|
+
const sumAll = (m, f = (v) => v) => sumOnce(m[0].flatMap((_, j) => m.map((r) => f(r[j]))));
|
|
26
|
+
const signOf = (v) => (v < 0 ? -1 : 1);
|
|
27
|
+
/** r_ij / sqrt(r_ii r_jj) with unit diagonal */
|
|
28
|
+
function toCorrelation(S) {
|
|
29
|
+
const sd = S.map((r, i) => Math.sqrt(r[i]));
|
|
30
|
+
return S.map((r, i) => r.map((v, j) => (i === j ? 1 : v / (sd[i] * sd[j]))));
|
|
31
|
+
}
|
|
32
|
+
/** Squared multiple correlations from the pseudo-inverse, clipped to [0, 1] (messages as psych's smc) */
|
|
33
|
+
function smc(S, messages) {
|
|
34
|
+
const R = toCorrelation(S);
|
|
35
|
+
const { d, u, v } = svd(R);
|
|
36
|
+
const kept = d.map((_, k) => k).filter((k) => d[k] > Math.sqrt(EPS) * d[0]);
|
|
37
|
+
const out = R.map((_, i) => {
|
|
38
|
+
let s = 0;
|
|
39
|
+
for (const k of kept)
|
|
40
|
+
s += v[i][k] * (1 / d[k]) * u[i][k];
|
|
41
|
+
return 1 - 1 / s;
|
|
42
|
+
});
|
|
43
|
+
if (out.some((x) => x > 1))
|
|
44
|
+
addMessage(messages, "In smc, smcs > 1 were set to 1.0");
|
|
45
|
+
if (out.some((x) => x < 0))
|
|
46
|
+
addMessage(messages, "In smc, smcs < 0 were set to .0");
|
|
47
|
+
return out.map((x) => (x > 1 ? 1 : x < 0 ? 0 : x));
|
|
48
|
+
}
|
|
49
|
+
const addMessage = (list, m) => {
|
|
50
|
+
if (!list.includes(m))
|
|
51
|
+
list.push(m);
|
|
52
|
+
};
|
|
53
|
+
/** The first q eigenvectors of S with diagonal `diag`, times the square roots of their eigenvalues (clipped by `clip`) */
|
|
54
|
+
function principalLoadings(S, diag, q, clip) {
|
|
55
|
+
const M = S.map((r, i) => r.map((v, j) => (i === j ? diag[i] : v)));
|
|
56
|
+
const E = eigen(M, { symmetric: true });
|
|
57
|
+
const w = E.values.slice(0, q).map((e) => Math.sqrt(clip(e)));
|
|
58
|
+
return E.vectors.map((row) => row.slice(0, q).map((v, k) => v * w[k]));
|
|
59
|
+
}
|
|
60
|
+
const outer = (L) => matMul(L, transpose(L));
|
|
61
|
+
/** Minres factor analysis of a correlation matrix with q factors (varimax for q > 1) */
|
|
62
|
+
function minres(S0, q, warnings, messages) {
|
|
63
|
+
const S = toCorrelation(S0);
|
|
64
|
+
const p = S.length;
|
|
65
|
+
const s = smc(S, messages);
|
|
66
|
+
const objective = (psi) => {
|
|
67
|
+
const L = principalLoadings(S, psi.map((v) => 1 - v), q, (e) => (e < EPS ? 100 * EPS : e));
|
|
68
|
+
const model = outer(L);
|
|
69
|
+
const terms = [];
|
|
70
|
+
for (let j = 0; j < p; j++)
|
|
71
|
+
for (let i = j + 1; i < p; i++)
|
|
72
|
+
terms.push((S[i][j] - model[i][j]) ** 2);
|
|
73
|
+
return sumOnce(terms);
|
|
74
|
+
};
|
|
75
|
+
const gradient = (psi) => {
|
|
76
|
+
const L = principalLoadings(S, psi.map((v, i) => S[i][i] - v), q, (e) => Math.max(e, 0));
|
|
77
|
+
return psi.map((v, i) => {
|
|
78
|
+
let h = 0;
|
|
79
|
+
for (let k = 0; k < q; k++)
|
|
80
|
+
h += L[i][k] * L[i][k];
|
|
81
|
+
return h + v - S[i][i];
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
const fit = optim(s.map((v) => 1 - v), objective, {
|
|
85
|
+
gr: gradient,
|
|
86
|
+
method: "L-BFGS-B",
|
|
87
|
+
lower: 0.005,
|
|
88
|
+
upper: Math.max(Math.max(...s), 1),
|
|
89
|
+
control: { fnscale: 1, parscale: new Array(p).fill(0.01) },
|
|
90
|
+
});
|
|
91
|
+
const psi = fit.par;
|
|
92
|
+
let L = principalLoadings(S, psi.map((v, i) => S[i][i] - v), q, (e) => Math.max(e, 0));
|
|
93
|
+
L = signColumns(L, q);
|
|
94
|
+
L = L.map((r) => r.map((v) => (v === 0 ? 1e-15 : v)));
|
|
95
|
+
if (rowSums(L, (v) => v * v).some((h) => h > 1)) {
|
|
96
|
+
addMessage(warnings, "An ultra-Heywood case was detected. Examine the results carefully");
|
|
97
|
+
}
|
|
98
|
+
if (q > 1) {
|
|
99
|
+
L = signColumns(varimax(L).loadings, q);
|
|
100
|
+
const ssq = colSums(L, (v) => v * v);
|
|
101
|
+
const order = ssq.map((_, j) => j).sort((a, b) => ssq[b] - ssq[a] || a - b);
|
|
102
|
+
L = L.map((r) => order.map((j) => r[j]));
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
L = signColumns(L, q);
|
|
106
|
+
}
|
|
107
|
+
return L;
|
|
108
|
+
}
|
|
109
|
+
/** q > 1: each column times the sign of its sum; q = 1: negated if its sum is negative */
|
|
110
|
+
function signColumns(L, q) {
|
|
111
|
+
const sign = colSums(L).map(signOf);
|
|
112
|
+
if (q === 1)
|
|
113
|
+
return sign[0] < 0 ? L.map((r) => r.map((v) => -v)) : L;
|
|
114
|
+
return L.map((r) => r.map((v, j) => sign[j] * v));
|
|
115
|
+
}
|
|
116
|
+
/** Quartimin criterion and gradient at loadings L */
|
|
117
|
+
function quartimin(L) {
|
|
118
|
+
const q = L[0].length;
|
|
119
|
+
const L2 = L.map((r) => r.map((v) => v * v));
|
|
120
|
+
const X = L2.map((r) => r.map((_, j) => {
|
|
121
|
+
let s = 0;
|
|
122
|
+
for (let m = 0; m < q; m++)
|
|
123
|
+
if (m !== j)
|
|
124
|
+
s += r[m];
|
|
125
|
+
return s;
|
|
126
|
+
}));
|
|
127
|
+
return { f: sumAll(L2.map((r, i) => r.map((v, j) => v * X[i][j]))) / 4, Gq: L.map((r, i) => r.map((v, j) => v * X[i][j])) };
|
|
128
|
+
}
|
|
129
|
+
/** Oblique quartimin (oblimin) rotation of A by gradient projection: the pattern and the factor correlations */
|
|
130
|
+
function oblimin(A) {
|
|
131
|
+
const q = A[0].length;
|
|
132
|
+
const at = (T) => {
|
|
133
|
+
const Ti = solve(T);
|
|
134
|
+
const L = matMul(A, transpose(Ti));
|
|
135
|
+
const { f, Gq } = quartimin(L);
|
|
136
|
+
const G = transpose(matMul(matMul(transpose(L), Gq), Ti)).map((r) => r.map((v) => -v));
|
|
137
|
+
return { L, f, G };
|
|
138
|
+
};
|
|
139
|
+
let T = Array.from({ length: q }, (_, i) => Array.from({ length: q }, (_, j) => (i === j ? 1 : 0)));
|
|
140
|
+
let alpha = 1;
|
|
141
|
+
let cur = at(T);
|
|
142
|
+
let previous;
|
|
143
|
+
const values = [];
|
|
144
|
+
let converged = false;
|
|
145
|
+
for (let iter = 0; iter <= 2000; iter++) {
|
|
146
|
+
const d = colSums(T.map((r, i) => r.map((v, j) => v * cur.G[i][j])));
|
|
147
|
+
const Gp = cur.G.map((r, i) => r.map((v, j) => v - T[i][j] * d[j]));
|
|
148
|
+
const s = Math.sqrt(sumAll(Gp, (v) => v * v));
|
|
149
|
+
values.push(cur.f);
|
|
150
|
+
if (s < 1e-5) {
|
|
151
|
+
converged = true;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
if (previous !== undefined) {
|
|
155
|
+
const P = previous;
|
|
156
|
+
const dT = T.map((r, i) => r.map((v, j) => v - P.T[i][j]));
|
|
157
|
+
const dG = Gp.map((r, i) => r.map((v, j) => v - P.Gp[i][j]));
|
|
158
|
+
if (sumAll(dG, (v) => v * v) > 0) {
|
|
159
|
+
alpha = sumAll(dT, (v) => v * v) / Math.abs(sumAll(dT.map((r, i) => r.map((v, j) => v * dG[i][j]))));
|
|
160
|
+
alpha = Math.max(1e-10, Math.min(alpha, 20));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
alpha = 2 * alpha;
|
|
165
|
+
}
|
|
166
|
+
const target = Math.max(...values.slice(-10));
|
|
167
|
+
let trial = cur;
|
|
168
|
+
let Tt = T;
|
|
169
|
+
for (let i = 0; i <= 10; i++) {
|
|
170
|
+
const X = T.map((r, a) => r.map((v, b) => v - alpha * Gp[a][b]));
|
|
171
|
+
const len = colSums(X, (v) => v * v).map((v) => 1 / Math.sqrt(v));
|
|
172
|
+
Tt = X.map((r) => r.map((v, j) => v * len[j]));
|
|
173
|
+
trial = at(Tt);
|
|
174
|
+
if (target - trial.f > 0.5 * s * s * alpha)
|
|
175
|
+
break;
|
|
176
|
+
alpha = alpha / 2;
|
|
177
|
+
}
|
|
178
|
+
previous = { T, Gp };
|
|
179
|
+
T = Tt;
|
|
180
|
+
cur = trial;
|
|
181
|
+
}
|
|
182
|
+
return { loadings: cur.L, phi: matMul(transpose(T), T), converged };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* McDonald's omega (hierarchical, asymptotic and total) from a Schmid-Leiman transformation of an oblique minres
|
|
186
|
+
* factor solution. Equivalent to R's `psych::omega(x, nfactors)` with its defaults (`fm = "minres"`, `rotate =
|
|
187
|
+
* "oblimin"`, `option = "equal"`, `flip = TRUE`).
|
|
188
|
+
*
|
|
189
|
+
* @param x The data matrix (array of rows, NaN for missing values: correlations of pairwise complete observations),
|
|
190
|
+
* or `null` with `options.covmat`.
|
|
191
|
+
* @param options See {@link OmegaOptions}.
|
|
192
|
+
*
|
|
193
|
+
* @example
|
|
194
|
+
* ```ts
|
|
195
|
+
* const om = omega(x); // x: an n x 12 data matrix
|
|
196
|
+
* om.omegaH; om.omegaTot; om.sl;
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
export function omega(x, options = {}) {
|
|
200
|
+
const q = options.nfactors ?? 3;
|
|
201
|
+
if (!Number.isInteger(q) || q < 1)
|
|
202
|
+
throw new RangeError("'nfactors' must be a positive integer");
|
|
203
|
+
let R;
|
|
204
|
+
if (options.covmat !== undefined) {
|
|
205
|
+
R = toCorrelation(options.covmat);
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
if (x === null)
|
|
209
|
+
throw new TypeError("neither 'x' nor 'covmat' supplied");
|
|
210
|
+
R = cor(x, undefined, { use: "pairwise.complete.obs" });
|
|
211
|
+
}
|
|
212
|
+
const p = R.length;
|
|
213
|
+
const warnings = [];
|
|
214
|
+
const messages = [];
|
|
215
|
+
const orthog = minres(R, q, warnings, messages);
|
|
216
|
+
let oblique;
|
|
217
|
+
let phi;
|
|
218
|
+
let gloading;
|
|
219
|
+
if (q === 1) {
|
|
220
|
+
oblique = orthog.map((r) => r.slice());
|
|
221
|
+
gloading = [1];
|
|
222
|
+
addMessage(messages, "Omega_h for 1 factor is not meaningful, just omega_t\n");
|
|
223
|
+
addMessage(warnings, "Omega_h and Omega_asymptotic are not meaningful with one factor");
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
const rot = oblimin(orthog);
|
|
227
|
+
if (!rot.converged)
|
|
228
|
+
addMessage(warnings, "oblimin did not converge in 2000 iterations");
|
|
229
|
+
oblique = rot.loadings;
|
|
230
|
+
phi = rot.phi;
|
|
231
|
+
if (q === 2) {
|
|
232
|
+
const r12 = phi[0][1];
|
|
233
|
+
const a = Math.sqrt(Math.abs(r12));
|
|
234
|
+
gloading = [a, signOf(r12) * a];
|
|
235
|
+
addMessage(messages, TWO_FACTOR_MESSAGE);
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
gloading = minres(phi, 1, warnings, messages).map((r) => r[0]);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
// Schmid-Leiman
|
|
242
|
+
const g = oblique.map((r) => {
|
|
243
|
+
let s = 0;
|
|
244
|
+
for (let k = 0; k < q; k++)
|
|
245
|
+
s += r[k] * gloading[k];
|
|
246
|
+
return s;
|
|
247
|
+
});
|
|
248
|
+
const h2 = rowSums(orthog, (v) => v * v);
|
|
249
|
+
const u2 = h2.map((h, i) => R[i][i] - h);
|
|
250
|
+
const groupLoadings = oblique.map((r, i) => r.map((v, k) => {
|
|
251
|
+
// one factor (gloading 1): v is 0 exactly, the formula would leave only a rounding residue
|
|
252
|
+
if (q === 1)
|
|
253
|
+
return 0;
|
|
254
|
+
const Rii = R[i][i];
|
|
255
|
+
let w = Rii - (Rii - v * v) - (v * gloading[k]) ** 2;
|
|
256
|
+
if (w < 0)
|
|
257
|
+
w = 0;
|
|
258
|
+
return signOf(v) * Math.sqrt(w);
|
|
259
|
+
}));
|
|
260
|
+
const p2 = g.map((v, i) => (v * v) / h2[i]);
|
|
261
|
+
const com = g.map((v, i) => {
|
|
262
|
+
const F = [v, ...groupLoadings[i]];
|
|
263
|
+
return sumOnce(F.map((f) => f * f)) ** 2 / sumOnce(F.map((f) => f ** 4));
|
|
264
|
+
});
|
|
265
|
+
// flip
|
|
266
|
+
const key = g.map(signOf);
|
|
267
|
+
if (key.some((k) => k < 0))
|
|
268
|
+
R = R.map((r, i) => r.map((v, j) => key[i] * v * key[j]));
|
|
269
|
+
const gs = g.map((v, i) => key[i] * v);
|
|
270
|
+
const Fs = groupLoadings.map((r, i) => r.map((v) => key[i] * v));
|
|
271
|
+
const sl = gs.map((v, i) => [v, ...Fs[i], h2[i], u2[i], p2[i], com[i]]);
|
|
272
|
+
// statistics
|
|
273
|
+
const Vt = sumAll(R);
|
|
274
|
+
const Vitem = sumOnce(R.map((r, i) => r[i]));
|
|
275
|
+
const gsq = sumOnce(gs) ** 2;
|
|
276
|
+
const U = sumOnce(u2);
|
|
277
|
+
const omegaH = gsq / Vt;
|
|
278
|
+
const omegaTot = (Vt - U) / Vt;
|
|
279
|
+
const omegaLim = gsq / (Vt - U);
|
|
280
|
+
const alpha = (((Vt - Vitem) / Vt) * p) / (p - 1);
|
|
281
|
+
const G6 = (Vt + sumOnce(smc(R, messages)) - Vitem) / Vt;
|
|
282
|
+
const ev = colSums(sl.map((r) => r.slice(0, q + 1)), (v) => v * v);
|
|
283
|
+
const ECV = ev[0] / sumOnce(ev);
|
|
284
|
+
// omega of each group
|
|
285
|
+
const group = Fs.map((r) => {
|
|
286
|
+
let best = 0;
|
|
287
|
+
for (let k = 1; k < q; k++)
|
|
288
|
+
if (Math.abs(r[k]) > Math.abs(r[best]))
|
|
289
|
+
best = k;
|
|
290
|
+
return best;
|
|
291
|
+
});
|
|
292
|
+
const groupRows = [];
|
|
293
|
+
const aSquares = [];
|
|
294
|
+
for (let k = 0; k < q; k++) {
|
|
295
|
+
const items = group.map((_, i) => i).filter((i) => group[i] === k);
|
|
296
|
+
const V = sumOnce(items.flatMap((j) => items.map((i) => R[i][j])));
|
|
297
|
+
const a = sumOnce(items.map((i) => Fs[i][k]));
|
|
298
|
+
const b = sumOnce(items.map((i) => gs[i]));
|
|
299
|
+
aSquares.push(a * a);
|
|
300
|
+
groupRows.push([(a * a + b * b) / V, (b * b) / V, (a * a) / V]);
|
|
301
|
+
}
|
|
302
|
+
const omegaGroup = [[omegaTot, sumOnce(gs) ** 2 / Vt, sumOnce(aSquares) / Vt], ...groupRows];
|
|
303
|
+
const out = {
|
|
304
|
+
omegaH,
|
|
305
|
+
omegaLim,
|
|
306
|
+
alpha,
|
|
307
|
+
omegaTot,
|
|
308
|
+
G6,
|
|
309
|
+
ECV,
|
|
310
|
+
sl,
|
|
311
|
+
slNames: ["g", ...Array.from({ length: q }, (_, k) => `F${k + 1}*`), "h2", "u2", "p2", "com"],
|
|
312
|
+
orthog,
|
|
313
|
+
oblique,
|
|
314
|
+
gloading,
|
|
315
|
+
key,
|
|
316
|
+
omegaGroup,
|
|
317
|
+
warnings,
|
|
318
|
+
messages,
|
|
319
|
+
};
|
|
320
|
+
if (phi !== undefined)
|
|
321
|
+
out.phi = phi;
|
|
322
|
+
return out;
|
|
323
|
+
}
|
|
@@ -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;
|