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
51 lines (45 loc) • 1.77 kB
JavaScript
import CDF from '../cdf/index.js';
import { TestBase } from '../test-base/index.js';
export class Pearson extends TestBase {
#sumCov; #covariance; #r; #p;#t;
constructor(samples, population = false) {
super(samples, `Pearson${population ? '' : ' Sample'} Test`, ['covariance','df','r','p','t'], { min: 2, sameSize: true })
this.df = this.n - 2;
this.population = population
}
get sumCov() {
if (this.#sumCov === undefined) {
const { n, samples: [{ values: v1, mean: m1 }, { values: v2, mean: m2 }] } = this
this.#sumCov = 0;
for (let i = 0; i < n; i++) { this.#sumCov += (v1[i] - m1) * (v2[i] - m2) }
}
return this.#sumCov
}
get covariance() {
if (this.#covariance === undefined) {
const { sumCov, population, n } = this
this.#covariance = population ? sumCov / n : n < 2 ? 0 : sumCov / (n - 1)
}
return this.#covariance
}
get r() {
if (this.#r === undefined) {
this.std1 = this.population ? this.samples[0].stdDev : this.samples[0].stdDevSample
this.std2 = this.population ? this.samples[1].stdDev : this.samples[1].stdDevSample
if (this.std1 === 0 || this.std2 === 0) this.#r = 0
else this.#r = this.covariance / (this.std1 * this.std2)
this.#t = this.#r * Math.sqrt(this.df / Math.max(1 - this.#r * this.#r, 1e-16));
}
return this.#r
}
get p() {
if (this.df <= 1) return null
if (this.#p === undefined) {
this.#p = 2 * (1 - CDF.t(Math.abs(this.#t), this.df));
if (this.#p < 0) this.#p = 0;
if (this.#p > 1) this.#p = 1;
}
return this.#p
}
get t() { return this.#t }
}