[R] Calculation of r squared from a linear regression

Daniel Malter daniel at umd.edu
Tue Jun 15 10:23:36 CEST 2010


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.



More information about the R-help mailing list