> library(car) # Anova
> library(NCStats) # fit.plot
> options(contrasts=c("contr.sum","contr.poly"))
> library(car) # Anova
> library(NCStats) # fit.plot
> options(contrasts=c("contr.sum","contr.poly"))
The working directory is set, the box3_11.txt data file is read, and the structure of the data frame is observed with,
> setwd("c://aaaWork//web//fishR//bookex//AIFFD//Box3_11")
> d <- read.table("box3_11.txt", header = TRUE)
> str(d)
'data.frame': 29 obs. of 4 variables:
$ id : int 1 2 3 4 5 6 7 8 9 10 ...
$ substrate : Factor w/ 3 levels "Cobble","Gravel",..: 1 1 1 1 1 1 1 1 1 1 ...
$ egg_diameter: num 8.3 8.5 11.2 10.7 9.6 11.8 9.6 8.9 11.2 8.9 ...
$ growth : num 20 23.5 24.7 29.5 24.3 31.7 22.1 19 17.3 23.3 ...
The ANCOVA is fit with lm() (see linear models vignette for an introduction) and results are assigned to an object with,
> lm1 <- lm(growth ~ egg_diameter * substrate, data = d)
|
The right-hand-side of the lm() formula for an ANCOVA should be of the form quantitative*factor, where quantitative represents the quantitative covariate variable and factor represents the categorical group factor variable. |
|
In R, the apparent multiplication of two factor variables in a linear model formula is a short-hand notation to tell R to include each factor as main effects AND the interaction between the two factors. R denotes the interaction term by separating the main factors with a colon. |
The type-III SS (see discussion about SS in the preliminaries vignette) are obtained by submitting the lm object to Anova() with the type="III" argument as follows,
> Anova(lm1, type = "III")
Anova Table (Type III tests)
Response: growth
Sum Sq Df F value Pr(>F)
(Intercept) 138.85 1 11.944 0.0021464
egg_diameter 557.07 1 47.917 4.674e-07
substrate 266.12 2 11.445 0.0003548
egg_diameter:substrate 311.46 2 13.395 0.0001389
Residuals 267.39 23
The fit.plot() function from the NCStats package can be used to visually observe the regression fit between final length (i.e., "growth") and egg diameter for each substrate type.
> fit.plot(lm1, xlab = "Egg Diameter (mm)", ylab = "Final length (mm)", legend = "topleft", main = "")
The anova table of type II SS is obtained with,
> Anova(lm1, type = "II")
Anova Table (Type II tests)
Response: growth
Sum Sq Df F value Pr(>F)
egg_diameter 383.07 1 32.951 7.585e-06
substrate 420.10 2 18.068 1.921e-05
egg_diameter:substrate 311.46 2 13.395 0.0001389
Residuals 267.39 23
The p-value for the interaction (p=0.0001) is the same as that shown for the type-III SS because this was the last variable added to the model. Nevertheless, the interaction term is significant indicating a different slope between final length (i.e., "growth") and egg diameter among the three substrate types.