# How do you compute $R^2$ with a given model?

I see that the LinearModelFit function can give you the $R^2$ of the best fit, but I already have a model. I want to compare the data to the model (function) and have Mathematica tell me how good a fit it is. That is, I have a function, Mass[r], and I have a bunch of data, data = {{0, 1}, {1, 2}, {2, 4}, {3, 9}}. How can I tell how well Mass[r] matches data?

Here is a possible solution if you already have a model object:

rsquared[list___, model_] :=
1 - SquaredEuclideanDistance[list[[;; , 2]],
model /@ list[[;; , 1]]]/
SquaredEuclideanDistance[list[[;; , 2]], Mean@list[[;; , 2]]]


Testing for the given data

data = {{0, 1}, {1, 2}, {2, 4}, {3, 9}};
mass = LinearModelFit[data, x, x];
rsquared[data, mass]
(*0.889474*)


Verifying with the built in RSquared functionality

mass["RSquared"]
(*0.889474*)


Alternatively, with any defined function:

model[r_] := 2.6*r
rsquared[data, model]
(*0.888421*)

• Thank you. It works like a charm. So just to confirm, there's no built-in Mathematica operation that will do this? It seems so basic. Dec 8, 2016 at 11:33
• A quick look around doesn't seem to indicate that there is a built in function. Dec 8, 2016 at 15:18
• For the denominator, you could instead use ((Length[list] - 1) Variance[list[[;;, 2]]]). Dec 10, 2016 at 2:28