als-statistics
Version:
A powerful and lightweight JavaScript library for descriptive statistics, regression, clustering, outlier detection, and noise analysis using a flexible table/column architecture.
47 lines (41 loc) • 1.92 kB
JavaScript
const BaseColumn = require('./base');
class Column extends BaseColumn {
constructor(values, columnFilter) {
super(values, columnFilter)
}
clone(filtered=true,table) { return new this.constructor(filtered ? this.values : this._values,table) }
get frequencies() { // Absolute frequencies for each unique value
return this.cached('absoluteFrequencies', () => {
const freq = new Map();
for (const v of this.values) { freq.set(v, (freq.get(v) || 0) + 1) }
return Object.fromEntries(freq);
});
}
get relativeFrequencies() { // Relative frequencies (the proportion of each value relative to the total)
return this.cached('relativeFrequencies', () => {
const { frequencies, n } = this, relFreq = {};
for (const key in frequencies) { relFreq[key] = frequencies[key] / n }
return relFreq;
});
}
get sorted() {
return this.cached('sorted', () => {
const valuesCopy = this.values.slice();
if (valuesCopy.length === 0) return valuesCopy;
if (this.type === Number) return valuesCopy.sort((a, b) => a - b);
return valuesCopy.sort((a, b) => String(a).localeCompare(String(b)));
});
}
percentile(p) {
const { sorted, n } = this
if (p < 0 || p > 100) throw new Error("Percentile must be between 0 and 100");
if (p === 0) return sorted[0];
if (p === 100) return sorted[n - 1];
const index = Math.floor((p / 100) * (n - 1)); // Берем нижний индекс
return sorted[index]; // Возвращаем число без усреднения
}
get median() { return this.cached('median', () => this.percentile(50)) }
get q1() { return this.cached('q1', () => this.percentile(25)) }
get q3() { return this.cached('q3', () => this.percentile(75)) }
}
module.exports = Column