Below are the solutions to these exercises on “ANCOVA – Part 2.”

if (!require(car)){install.packages(car, dep=T)} library(car) if (!require(ggplot2)){install.packages(ggplot2, dep=T)} library(ggplot2) ############### # # # Exercise 1 # # # ############### # Load data limpet<-read.csv(file.choose()) limpet.lm <- lm(EGGS ~ DENSITY * SEASON, data = limpet) ############### # # # Exercise 2 # # # ############### predict(limpet.lm)

## 1 2 3 4 5 6 7 ## 2.3949692 2.3949692 2.3949692 1.6075953 1.6075953 1.6075953 2.1594217 ## 8 9 10 11 12 13 14 ## 2.1594217 2.1594217 1.3938428 1.3938428 1.3938428 1.6546769 1.6546769 ## 15 16 17 18 19 20 21 ## 1.6546769 0.9358016 0.9358016 0.9358016 1.1499321 1.1499321 1.1499321 ## 22 23 24 ## 0.4777604 0.4777604 0.4777604

############### # # # Exercise 3 # # # ############### vec.x<-expand.grid(DENSITY=unique(limpet$DENSITY),SEASON=levels(limpet$SEASON)) #Density and Season as repeated factors ############### # # # Exercise 4 # # # ############### predict(limpet.lm, newdata = vec.x)

## 1 2 3 4 5 6 7 ## 2.3949692 2.1594217 1.6546769 1.1499321 1.6075953 1.3938428 0.9358016 ## 8 ## 0.4777604

limpet.predict <- predict(limpet.lm, newdata = vec.x) predict.plot <- data.frame(vec.x, limpet.predict) #look at the dataframe predict.plot

## DENSITY SEASON limpet.predict ## 1 8 spring 2.3949692 ## 2 15 spring 2.1594217 ## 3 30 spring 1.6546769 ## 4 45 spring 1.1499321 ## 5 8 summer 1.6075953 ## 6 15 summer 1.3938428 ## 7 30 summer 0.9358016 ## 8 45 summer 0.4777604

############### # # # Exercise 5 # # # ############### predict.mean <- predict(limpet.lm, newdata = vec.x) predict.plot1<- data.frame(vec.x, predict.mean) ############### # # # Exercise 6 # # # ############### vec.x2 <- expand.grid(DENSITY = c(5, 10, 25, 35), SEASON = levels(limpet$SEASON)) # look at it vec.x2

## DENSITY SEASON ## 1 5 spring ## 2 10 spring ## 3 25 spring ## 4 35 spring ## 5 5 summer ## 6 10 summer ## 7 25 summer ## 8 35 summer

# now predict the mean values per season predict.levels <- predict(limpet.lm, newdata = vec.x2) predict.plot2 <- data.frame(vec.x2, predict.levels) ############### # # # Exercise 7 # # # ############### plot(EGGS ~ DENSITY, data = limpet, pch = 19,cex = 1.5, col = c("Black", "Red")[limpet$SEASON], xlab = list("Density", cex = 1.2), ylab = list("Eggs Produced", cex = 1.2)) xlim = c(0, 50) # limit the X axis # Now add a legend legend(35, 3, legend = c("Spring", "Summer"), col = c("black", "red"), pch = 19) # add lines lines(limpet.predict ~ DENSITY,subset(predict.plot,SEASON == "spring")) lines(limpet.predict ~ DENSITY,subset(predict.plot,SEASON == "summer"), col = "red")

**What's next:**

- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

## Leave a Reply