function linearRegression(data, options){
options = Object.assign({
x: (d,i) => d[i].x,
y: (d,i) => d[i].y,
length: d => d.length
}, options);
function accessor(str) { return (d,i) => d[i][str] }
if (typeof options.x == "string") options.x = accessor(options.x);
if (typeof options.y == "string") options.y = accessor(options.y);
const n = options.length(data);
let sx = 0;
let sy = 0;
let sxy = 0;
let sxx = 0;
let syy = 0;
for (let i = 0; i < n; i++) {
let x = options.x(data,i), y = options.y(data,i);
sx += x;
sy += y;
sxy += x * y;
sxx += x * x;
syy += y * y;
}
const mx = sx / n;
const my = sy / n;
const yy = n * syy - sy * sy;
const xx = n * sxx - sx * sx;
const xy = n * sxy - sx * sy;
const slope = xy / xx;
const intercept = my - slope * mx;
const r = xy / Math.sqrt(xx * yy);
const r2 = Math.pow(r,2);
let sst = 0;
for (let i = 0; i < n; i++) {
sst += Math.pow((options.y(data,i) - my), 2);
}
const sse = sst - r2 * sst;
const see = Math.sqrt(sse / (n - 2));
const ssr = sst - sse;
return {slope, intercept, r, r2, sse, ssr, sst, sy, sx, see};
}