# Re: [R] Calculation of r squared from a linear regression

From: Daniel Malter <daniel_at_umd.edu>
Date: Tue, 15 Jun 2010 01:23:36 -0700 (PDT)

Hi, as pointed out previously, the problem is in using the canned routine (lm) without including an intercept term. Here is a working, generic example with commented code.

#Simulate data

```x=rnorm(100)
e=rnorm(100)
y=x+e

```

#Create X matrix with intercept

X=cbind(1,x)

#Projection matrix

P=X%*%solve(t(X)%*%X)%*%t(X)

#Fitted values

fv=P%*%y

#Run canned regression

reg=lm(y~x)

#Canned and hand computed fitted values
cbind(fitted(reg),fv)

#Are they all equal?

all.equal(as.vector(as.numeric(fitted(reg))),as.vector(as.numeric(fv)))
#This already implies that the R-squared is equal

#Compute R-squared by hand

R.sq=1-sum((y-fv)^2)/sum((y-mean(y))^2)

#Is this equal to the R-squared from the canned routine?
summary(reg)\$r.squared==R.sq

Daniel

```--
View this message in context: http://r.789695.n4.nabble.com/Calculation-of-r-squared-from-a-linear-regression-tp2251438p2255537.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help