## Sunday, May 1, 2011

### R Code Example for Linear Regression and Analysis of Variance

```# EXAMPLE CODE FOR REGRESSION & AOV

x<-c(20,16,34,23,27,32,18,22)
y<-c(64,61,84,70,88,92,72,77)

mymodel <- lm(y~x) # run regression model
summary(mymodel)  # output

dat1 <- data.frame(x,y) # combine x and y into an R data frame

ss <- aov(y~x, data = dat1) # conduct analysis of variance & save results as 'ss'
summary(ss)  # print results

# to read the output you must realize that the row 'x' gives you the SSR & MSR
# the row 'Residuals' gives tyou SSE & MSE
# SST is not given but you know the formula to get it SST = SSR + SSE

# based on output, calculate SST = SSR + SSE

SST <- 658.5 + 227.5
print(SST) # this gives you SST

#  use this info to calculate R-square = SSR / SST

658.5/SST # gives .743 which was given in the original regression output

# verify that the F- stat is MSR / MSE based on the output from summary(ss)

F<- 658.5/37.92
print(F) # this gives the same results as summary(ss)```
Created by Pretty R at inside-R.org