Link Search Menu Expand Document (external link)

How to compute R-squared for a simple linear model (in Julia)

See all solutions.

Task

Let’s say we have fit a linear model to two columns of data, one for a single independent variable $x$ and the other for a single dependent variable $y$. How can we compute $R^2$ for that model, to measure its goodness of fit?

Related tasks:

Solution

We assume you have already fit a linear model to the data, as in the code below, which is explained fully in a separate task, how to fit a linear model to two columns of data.

1
2
3
4
5
using GLM, DataFrames
xs = [ 393, 453, 553, 679, 729, 748, 817 ]
ys = [  24,  25,  27,  36,  55,  68,  84 ]
data = DataFrame( xs=xs, ys=ys )
model = lm( @formula( ys ~ xs ), data )
1
2
3
4
5
6
7
8
9
10
11
StatsModels.TableRegressionModel{LinearModel{GLM.LmResp{Vector{Float64}}, GLM.DensePredChol{Float64, LinearAlgebra.CholeskyPivoted{Float64, Matrix{Float64}, Vector{Int64}}}}, Matrix{Float64}}

ys ~ 1 + xs

Coefficients:
───────────────────────────────────────────────────────────────────────────
                 Coef.  Std. Error      t  Pr(>|t|)    Lower 95%  Upper 95%
───────────────────────────────────────────────────────────────────────────
(Intercept)  -37.3214    18.9954    -1.96    0.1066  -86.1508      11.5079
xs             0.13272    0.029589   4.49    0.0065    0.0566587    0.20878
───────────────────────────────────────────────────────────────────────────

You can get the $R^2$ value from your model using the r2 function in the GLM package.

1
r2( model )
1
0.8009488239830588

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)