Linear Regression
# linear function
packages/stats/src/regression/linear.ts:59linear(arg1: Partial<RegressionOptions>): (args_0: DataPoint[]) => RegressionResult
linear(suppliedOptions: Partial<RegressionOptions>, data: DataPoint[]): RegressionResultPerforms 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
| Name | Type | Description |
|---|---|---|
| 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
RegressionResultDiscriminant union:
ok: true— includesslope,intercept,r2,rmse,n,points,predict.ok: false— includeserrorTypeandmessagedescribing why regression failed.
insight
- Trend direction —
slope > 0positive,slope < 0negative,slope ≈ 0flat. - Rate of change —
slopequantifies Y change per unit X. - Goodness of fit —
r2(0–1): higher = better fit. - Prediction accuracy —
rmsein Y-axis units; enables “predictions within ±X” statements. - Sample reliability —
nallows warnings for small sample sizes. - Future prediction —
predict(x)returns[x, predictedY]for any x.
Examples
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);const vertical: DataPoint[] = [[1, 1], [1, 2], [1, 3]];
const err = linear({}, vertical);
// err.ok === false, err.errorType === "DegenerateInput"