# LinearModelFit: How to compute $R^2$? [closed]

Is there a simple way to computed the $R^2$ (adjusted and not adjusted), from the LinearModelFit?

It has so many options, but none for the $R^2$, that I suspect there's a simple way to compute it it the info given by some of the options.

Any help would be appreciated.

• It's "AdjustedRSquared" and "RSquared". Check the Details and Options section of the documentation for details. – Karsten 7. Feb 9 '16 at 20:36
• @Karsten7. you're right. I checked the 'Details and Options' section, but I should have scrolled further down... – An old man in the sea. Feb 9 '16 at 21:18

Clear[x];
lm = LinearModelFit[xydata, x, x];
r2 = lm["RSquared"]


Alternatively calculating in steps.

{x, y} = Transpose[xydata];

MapIndexed[(X@#2[] = #1) &, x];
MapIndexed[(Y@#2[] = #1) &, y];

n = Length[xydata];
ΣX = Sum[X[i], {i, n}];
ΣY = Sum[Y[i], {i, n}];
ΣXY = Sum[X[i] Y[i], {i, n}];
ΣX2 = Sum[X[i]^2, {i, n}];

Clear[a, b];
{{a, b}} = {a, b} /. Solve[{
(*Normal equations for straight line*)
ΣY == n a + b ΣX,
ΣXY == a ΣX + b ΣX2}, {a, b}];

(*Least-squares regression of Y on X*)
Array[(Yhat[#] = a + b X[#]) &, n];

Array[(e[#] = Y[#] - Yhat[#]) &, n];
(*Residual or unexplained sum of squares*)

Ymean = ΣY/n;
Array[(Yd[#] = Y[#] - Ymean) &, n];
(*Total sum of squares in the dependent variable,
TSS = Sum[Yd[i]^2, {i, n}];

(*Coefficient of determination, R-squared*)

• I have a bunch of observed data and I have my model. I don't want to know what the best fit is, I want to know how my model compares to the observed data. Same question: how do you calculate the $R^2$? – Quarkly Dec 8 '16 at 1:00
• Thank you but I want to know how to do this in Mathematica. The $\chi^2$ and $R^2$ functions work on fitted models. I need either test done for a predictive model. That is, I want to know how well the observed data matches the model that I provide. – Quarkly Dec 8 '16 at 11:37