Documentation

Linear Regression

@statili/stats ·v0.0.2-beta.0 ·1 export

signatures
linear(arg1: Partial<RegressionOptions>): (args_0: DataPoint[]) => RegressionResult
linear(suppliedOptions: Partial<RegressionOptions>, data: DataPoint[]): RegressionResult
Performs simple linear regression to model the relationship between a dependent variable (y) and an independent variable (x).
Fits a straight line (y = slope·x + intercept) through the data by minimising the sum of squared residuals between observed and predicted y values (Ordinary Least Squares).

Parameters

NameTypeDescription
suppliedOptions Partial<RegressionOptions> Optional overrides, e.g. { precision: 4 }.
data DataPoint[] Array of [x, y] tuples. Requires at least 2 points with distinct x values.

Returns

RegressionResult

Discriminant union:

  • ok: true — includes slope, intercept, r2, rmse, n, points, predict.
  • ok: false — includes errorType and message describing why regression failed.
insight
  • Trend directionslope > 0 positive, slope < 0 negative, slope ≈ 0 flat.
  • Rate of changeslope quantifies Y change per unit X.
  • Goodness of fitr2 (0–1): higher = better fit.
  • Prediction accuracyrmse in Y-axis units; enables “predictions within ±X” statements.
  • Sample reliabilityn allows warnings for small sample sizes.
  • Future predictionpredict(x) returns [x, predictedY] for any x.

Examples

Basic usage
const data: DataPoint[] = [[1, 2], [2, 3], [3, 4], [4, 5]];
const result = linear({}, data);
if (result.ok) {
  console.log(`slope: ${result.slope}`);       // 1
  console.log(`intercept: ${result.intercept}`); // 1
  console.log(`R²: ${result.r2}`);              // 1
  console.log(`RMSE: ${result.rmse}`);           // 0
  console.log(`n: ${result.n}`);                 // 4
  console.log(`predict(5): ${result.predict(5)[1]}`); // 6
}
// Curried / partial application (data-last for composability)
const regressionWithPrecision = linear({ precision: 4 });
const result = regressionWithPrecision(data);
Handling errors
const vertical: DataPoint[] = [[1, 1], [1, 2], [1, 3]];
const err = linear({}, vertical);
// err.ok === false, err.errorType === "DegenerateInput"