# Clerid_eggs_th.R
# Two-way ANOVA for T. dubius egg mortality

# Load necessary libraries
library(car)
library(ggplot2)
library(emmeans)
library(multcomp)

# Read in data set
mortdata <- read.table(header=T,colClasses=c("factor","factor","numeric"),text="
temp rh mortrate
15    55  0.137
15    75  0.102
15   100  0.333
20    55  0.181
20    75  0.337
20   100  0.188
25    55  0.123
25    75  0.259
25   100  0.205
30    55  0.202
30    75  0.321
30   100  0.226
35    55  0.680
35    75  0.447
35   100  0.431
37.5  55  1.000
37.5  75  1.000
37.5 100  1.000
")

# Apply transformations here
mortdata <- transform(mortdata,y=asin(sqrt(mortrate)))

# Print data set
mortdata

# Graphics using ggplot2
print(ggplot(mortdata,aes(temp,y,group=rh,color=rh))+
geom_line(size=1))

# Two-way ANOVA without replication
options(contrasts=c("contr.sum","contr.poly"))
aovout <- aov(y~temp+rh,data=mortdata)

# Type II SS
print(Anova(aovout))

# Calculate least squares means
emmeans(aovout,~temp)
emmeans(aovout,~rh)

# All pairwise comparisons - Tukey method
compout <- glht(aovout,linfct=mcp(temp="Tukey"))
summary(compout)
confint(compout)
cld(compout)

# All pairwise comparisons - Tukey method
compout <- glht(aovout,linfct=mcp(rh="Tukey"))
summary(compout)
confint(compout)
cld(compout)

# Diagnostic plots to check ANOVA assumptions
p <- predict(aovout)
r <- resid(aovout)
plot(p,r)
qqnorm(r)
