Thursday, April 8, 2010

R: Linear Regression Example of Faraway (2002)

See pp.23 of Faraway (2002), Practical Regression and Anova using R at:
http://cran.r-project.org/doc/contrib/Faraway-PRA.pdf

> data(gala)
> gala
> gfit <- lm(Species ˜ Area + Elevation + Nearest + Scruz + Adjacent,data=gala)
> summary(gfit)

The following is to compute some statistics by writing R code, just for illustrative purpose (since these estimates are already computed by the function lm())

> x <- cbind(1,gala[,-c(1,2)])
> y <- gala$Species
> t(x) %*% x
Error: %*% requires numeric matrix/vector arguments

> x <- as.matrix(x)
> t(x) %*% x
> xtxi <- solve(t(x) %*% x)
> xtxi

># Get it using lm()
> gfit <- lm(Species ˜ Area + Elevation + Nearest + Scruz + Adjacent,data=gala)
> gs <- summary(gfit)
> gs$cov.unscaled
> names(gs)
> names(gfit)
> gfit$fit
> gfit$res

>#Get beta_hat by
> xtxi %*% t(x) %*% y #or
> solve(t(x) %*% x, t(x) %*% y)

> sqrt(sum(gfit$resˆ2)/(30-6))
> sqrt(diag(xtxi))*60.975
> #R^2
> 1-sum(gfit$resˆ2)/sum((y-mean(y))ˆ2)

No comments:

Post a Comment