Skip to content

Instantly share code, notes, and snippets.

@kenkellner
Last active December 12, 2022 12:22
Show Gist options
  • Save kenkellner/c8181c4523a916b92acb to your computer and use it in GitHub Desktop.
Save kenkellner/c8181c4523a916b92acb to your computer and use it in GitHub Desktop.
Test for interaction effect in 2-way ANOVA using permutation
#############################################################
## Permutation test for interaction between 2 main effects ##
#############################################################
#Based on http://r.789695.n4.nabble.com/Randomization-of-a-two-way-ANOVA-td874581.html
#Read in data
data <- read.csv('final.project.data.csv',h=T)
#Full model with interaction
full.mod <- aov(Preymort~Predator*Pesticide,data=data)
actualval <- summary(full.mod)[[1]][["F value"]][3]
#Model with main effects only
simple.mod <- aov(Preymort~Predator+Pesticide,data=data)
base.fit <- simple.mod$fitted.values
base.res <- simple.mod$residuals
#Number of permutations
nperm = 500
nulldist <- vector(length=nperm)
for (i in 1:nperm){
#Rearrange residuals and add back to fitted values
newres <- sample(base.res)
newdat <- base.fit + newres
#Analyze new data with full model and extract interaction F
newfit <- aov(newdat ~ data$Predator*data$Pesticide)
nulldist[i] <- summary(newfit)[[1]][["F value"]][3]
}
#Plot distribution and calculate quasi-p
hist(nulldist)
abline(v=actualval,col='red')
quasi.p <- mean(nulldist>actualval)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment