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

See all solutions.

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?

## 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
xs <- c( 393, 453, 553, 679, 729, 748, 817 )
ys <- c(  24,  25,  27,  36,  55,  68,  84 )
model <- lm( ys ~ xs )


You can get a lot of information about your model from its summary.

1
summary( model )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Call:
lm(formula = ys ~ xs)

Residuals:
1       2       3       4       5       6       7
9.163   2.199  -9.072 -16.795  -4.431   6.047  12.890

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -37.32142   18.99544  -1.965  0.10664
xs            0.13272    0.02959   4.485  0.00649 **
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 11.62 on 5 degrees of freedom
Multiple R-squared:  0.8009,	Adjusted R-squared:  0.7611
F-statistic: 20.12 on 1 and 5 DF,  p-value: 0.006486


In particular, it contains the $R^2$ value.

1
summary( model )\$r.squared

1
[1] 0.8009488