#GLMMs (Original record see DataS1)
#Load the required R packages.
library(lme4)
library(openxlsx)
library(ggplot2)
library(car)
library(emmeans)
library(mgcv)
#Import data.
data=read.xlsx("glmm.data.xlsx",sheet="Sheet1",colNames = T)
#Set variables.
escape = factor(data$escape)
success = data$escape
stretching = factor(data$prey_stretching)
experience <- data$experience
group_1 = factor(data$predator_id)
group_2 = factor(data$prey_id)
#Set model.
model <- glmer(success~stretching+experience+(1|group_1)+(1|group_2), family = binomial(link ='logit'))
summary(model)

#Frequency measurement of behaviour (see DataS7).
#Import data.
setwd("D:/R course")
getwd()
data1<-read.csv("DataS7.csv",header=T)
#t-test.
Rest<-data1$Resting
Move<-data1$Moving
t.test(Rest,Move,var.equal = T)

#Deviation angle of predator's head (see DataS2).
#Import data.
data2<-read.csv("DataS2.csv",header=T)
#t-test.
Before<-data2$Before
After<-data2$After
t.test(Before,After,var.equal = T)

#Speed comparison between control and treatment group (see DataS8).
#Import data.
data3<-read.csv("DataS8.csv",header=T)
#t-test.
Control<-data3$Mean.speed.CK
Treat<-data3$Mean.speed.TR
t.test(Control,Treat,var.equal = T)

#Comparison of survival rates between the normal-stretching group and the forelegs-disabled group (see Chisq.test.data).
#chisq-test.
x=c(39,10,2,19)
data4=matrix(x,ncol=2)
chisq.test(data4)

#Comparison of attack rates between the normal-stretching group and the non-stretching group (see Chisq.test.data).
#chisq-test.
x=c(11,8,30,1)
data5=matrix(x,ncol=2)
chisq.test(data5)

#Comparison of predator's targets between the normal-stretching group and the non-stretching group (see Chisq.test.data).
#chisq-test.
x=c(2,8,7,0)
data6=matrix(x,ncol=2)
chisq.test(data6)

#Comparison of predator's targets between the normal-stretching group and the forelegs-disabled group (see Chisq.test.data).
#chisq-test.
x=c(2,25,7,1)
data7=matrix(x,ncol=2)
chisq.test(data7)

#Survival rate of flower mantids when predators attack different body parts (see Chisq.test.data).
#chisq-test.
x=c(8,9,0,26)
data8=matrix(x,ncol=2)
data8
chisq.test(data8)

#The change in relative distance between predators and flower mantids over time (Original record see DataS3).
#Load the required R packages.
library(gcookbook)
library(ggplot2)
library(ggthemes)
#Import data.
data <- read.table("linear.regression.data.txt",header = T) 
#Convert the 'Stretching' variable to a factor variable.
data$Stretching <- as.factor(data$Stretching) 
#Plotting.
ggplot(data, aes(x = Time, y = Distance, color = Stretching, shape = Stretching)) +
  geom_smooth(method = lm) +
  geom_point()+  
  theme_classic()