#PHYLOGENETIC ANOVA

setwd("C:/Users/alice/Desktop/files_for_bird_pANOVA")

library(RRPP)
library(ape)
library(geiger)

karldata<-read.csv("CoM_heteronorm_new.csv", row.names=1)
tree<-read.nexus("output.nex")

name.check(tree, karldata)
attach(karldata)



fitGLS <- lm.rrpp(CCCoM_Forelimb~ LocomotorMode, 
                  karldata = karldata, 
                  Cov = karldata$PhyCov,
                  print.progress = FALSE)

anova(fitGLS)

fitGLSm <- lm.rrpp(CCCoM_Forelimb~ LocomotorMode, 
                  karldata =karldata, 
                  Cov = karldata$PhyCov,
                  print.progress = FALSE)

anova(fitGLSm)

png('CCCoM_Forelimb.png')
boxplot(CCCoM_Forelimb ~LocomotorMode, karldata=karldata, col = (c("Blue", "Red")), 
main="", ylab="", xlab="LocomotorMode")
dev.off()

## Pairwise comparisons of LS means

# Note: one should increase RRPP iterations but a 
# smaller number is used here for demonstration 
# efficiency.  Generally, iter = 999 will take less
# than 1s for these examples with a modern computer.


fit1 <- lm.rrpp(CCCoM_Forelimb ~LocomotorMode, SS.type = "I", 
karldata = karldata, print.progress = FALSE, iter = 499) 
summary(fit1, formula = FALSE)
anova(fit1) 

pup.group <- interaction(karldata$LocomotorMode)
pup.group
PW1 <- pairwise(fit1, groups = pup.group)
PW1

# distances between means
summary(PW1, confidence = 0.95, test.type = "dist") 
summary(PW1, confidence = 0.95, test.type = "dist", stat.table = FALSE)