UNPKG

als-statistics

Version:

Modular JS statistics toolkit for Node.js and the browser: descriptive stats, correlations (Pearson/Spearman/Kendall), t-tests & ANOVA (Student/Welch), reliability (Cronbach’s alpha), regression (linear/logistic), clustering (DBSCAN/HDBSCAN), and table/co

53 lines (44 loc) 2.08 kB
import { Pearson } from './pearson.js'; import { CronbachAlpha } from './cronbach-alpha.js'; import { Spearman } from './spearman.js'; import { Kendall } from './kendall.js'; export class Correlate { static CronbachAlpha = CronbachAlpha; static Pearson = Pearson; static Spearman = Spearman; static Kendall = Kendall; constructor(samples) { this.columns = samples // expecting columns object or values this.keys = Object.keys(samples) if (this.keys.length < 2) throw new Error('At least 2 samples required') } #filterColumns(colFilter) { if (colFilter.length === 0) return this.columns const filtered = {} colFilter.forEach(k => { filtered[k] = this.columns[k] }); return filtered } cronbachAlpha(...colFilter) { return new CronbachAlpha(this.#filterColumns(colFilter)) } spearmanTwoSided(...colFilter) { return this.matrix(colFilter, (data) => new Spearman(data, true)) } spearman(...colFilter) { return this.matrix(colFilter, (data) => new Spearman(data, false)) } kendallTwoSided(...colFilter) { return this.matrix(colFilter, (data) => new Kendall(data, true)) } kendall(...colFilter) { return this.matrix(colFilter, (data) => new Kendall(data, false)) } pearson(...colFilter) { return this.matrix(colFilter, (data) => new Pearson(data, true)) } pearsonSample(...colFilter) { return this.matrix(colFilter, (data) => new Pearson(data, false)) } matrix(colFilter, fn) { const entries = Object.entries(this.#filterColumns(colFilter)) if (entries.length === 2) return fn({ [entries[0][0]]: entries[0][1], [entries[1][0]]: entries[1][1], }) const result = {} for (let i = 0; i < entries.length; i++) { const [name1, value1] = entries[i] for (let j = i + 1; j < entries.length; j++) { const [name2, values2] = entries[j] result[`${name1}|${name2}`] = fn({ [name1]: value1, [name2]: values2 }) } } return result } }