#load packages ====
library(ggplot2)
library(ggfortify)
library(dplyr)
library(plyr)
library(lme4)
library(data.table)
library(gmodels)
library(ape)
library(permuco)
library(emmeans)
library(lmPerm)
library(multcomp)
library(Ecdat)
library(hexbin)
library(sp)
library(geometry)
library(MASS)
library(car)
library(ClassDiscovery)
library(PCDimension)
library(factoextra)
library(rela)
library(psych)
library(rela)
library(qqplotr)
library(mvnormtest)
library(devtools)
library(factoextra)
library(ClassDiscovery)
library(PCDimension)
library(ggpubr)
library(ggrepel)
library(boot)
library(grid)
library(gridExtra)
library(gtable)
library(patchwork)
library(svglite)
library(cowplot)
library(vioplot)
library(resample)
library(coin)
library(mosaic)
library(tidyverse)
library(rcompanion)
library(ICC)
library(multilevel)
library(purrr)
library(ggbiplot)
library(lmerTest)
library(Rmisc)
library(GGally)
library(lmtest)


########################################################################
#####Coral cover analysis#####
########################################################################
coral<-coral_2019

#check distribution using residuals====
lm.residual<- lm(CC~Site, data=coral)
sresid <- studres(lm.residual) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

#ANOVA
ANOVA_coral<-aov(CC~Site+Year+Year*Site, data=coral)
summary(ANOVA_coral)

#Boxplot
coral_cover<-ggplot(coral, aes(x=Site, y=CC))+
	geom_boxplot(width=0.4, position=position_dodge(0.65))+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				axis.text.y=element_text(size= 12, colour="Black"),
				axis.text.x = element_text(angle=90, vjust=0.5, size=12, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=14))+
	guides(fill=guide_legend(title=NULL))+
	labs(x="Site", y="Coral cover (%)")+
	scale_x_discrete(labels=c("HIGH", "LOW"))+
	facet_wrap(~Year)

ggsave(file="coral_cover.png")

#calculate mean coral
mean_coral<- aggregate(coral$CC, by=list(coral$Year,coral$Site), FUN=mean) 


########################################################################
#####Territory mapping analysis#####
########################################################################
#load data
territories<-chaet_territories_area

#Calculate area for each territory
#SAM_T1
SAM_T1_Hull_X<-c(18.2,3.6,0.1,4.2,15.7,19.7)
SAM_T1_Hull_Y<-c(0.4,3.7,9,11.3,12.8,9.1)
SAM_T1<-polyarea(SAM_T7_Hull_X, SAM_T7_Hull_Y)

#PK_T1
PK_T1_Hull_X<-c(8.1,8.1,1.3,0.2,0,0,0.5,6.8) 
PK_T1_Hull_Y<- c(5.8,2.4,3.1,3.4,6.3,8,10.2,9.4)
PK_T1<-polyarea(PK_T8_Hull_X, PK_T8_Hull_Y)

#SAM_T2
SAM_T2_Hull_X<-c(22.3,16.1,15,10,3.9,5.7,16,18.3,22.1)
SAM_T2_Hull_Y<-c(6.8,5.4,5.3,5.3,6.4,8.8,12,11.2,8.1)
SAM_T2<-polyarea(SAM_T5_Hull_X,SAM_T5_Hull_Y)

#PK_T2
PK_T2_Hull_X<-c(13.6,6,0,2.5,9.6)
PK_T2_Hull_Y<-c(3.2,0,0.8,11.9,10.1)
PK_T2<-polyarea(PK_T4_Hull_X, PK_T4_Hull_Y)

#SAM_T3
SAM_T3_Hull_X<-c(27,18.7,4,4,6.8,12.2,15.1,18.2,22.4)
SAM_T3_Hull_Y<-c(3.6,2.8,10,11,13,15.5,15.5,14.3,12.6)
SAM_T3<-polyarea(SAM_T6_Hull_X, SAM_T6_Hull_Y)

#PK_T3
PK_T3_Hull_X<-c(15,14.5,8.5,4.4,0.4,1.2,5.1,11.3)
PK_T3_Hull_Y<-c(1.2,0.9,0.6,0.7,4.7,6.3,7.2,8)
PK_T3<-polyarea(PK_T1_Hull_X, PK_T1_Hull_Y)

#SAM_T4
SAM_T4_Hull_X<-c(16.1,8.9,1.2,0.4,10,21)
SAM_T4_Hull_Y<-c(0.5,1,3,8.3,13.4,8.4)
SAM_T4<-polyarea(SAM_T4_Hull_X, SAM_T4_Hull_Y)

#PK_T4
PK_T4_Hull_X<-c(16.6,16.7,6,2.1,4.3,12.2)
PK_T4_Hull_Y<-c(2.4,2,2.8,4.2,4.9,4.3)
PK_T4<-polyarea(PK_T2_Hull_X, PK_T2_Hull_Y)

#PK_T5
PK_T5_Hull_X<-c(16.1,15.3,13.9,11.4,7.6,7.1,7.9)
PK_T5_Hull_Y<-c(3.9,0.4,0,2.6,7.9,12.4,17.1)
PK_T5<-polyarea(PK_T3_Hull_X, PK_T3_Hull_Y)

#SAM_T5
SAM_T5_Hull_X<-c(23.8,28.1,22.7,17.3,7.2,3.6,5,15.3)
SAM_T5_Hull_Y<-c(6.8,0.9,0,0.3,3.5,6.9,21.2,18)
SAM_T5<-polyarea(SAM_T3_Hull_X, SAM_T3_Hull_Y)

Site_name<-c("PK","PK","PK","PK","PK","SAM","SAM","SAM","SAM","SAM")
Pair_ID<-c("PK_T1", "PK_T2", "PK_T3", "PK_T4", "PK_T5", "SAM_T1", "SAM_T2", "SAM_T3", "SAM_T4", "SAM_T5")
Area<-c(PK_T1, PK_T2, PK_T3, PK_T4, PK_T5, SAM_T1, SAM_T2, SAM_T3, SAM_T4, SAM_T5)

territory_size<-cbind(Site_name, Pair_ID, Area)
territory_size<-as.data.frame(territory_size)
territory_size$Area<-as.numeric(territory_size$Area)
#####################################################################
#Analyse
territory_PK<-
	territory_size%>%
	filter(Site_name=="PK")
mean(territory_PK$Area)
sd(territory_PK$Area)/sqrt(length(territory_PK$Area))

territory_SAM<-
	territory_size%>%
	filter(Site_name=="SAM")
mean(territory_SAM$Area)
sd(territory_SAM$Area)/sqrt(length(territory_SAM$Area))


lm.residual_territory<- lm(Area~Site_name, data=territory_size)
sresid <- studres(lm.residual_territory) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

territory_anova<-aov(Area~Site_name, data=territory_size)
summary(territory_anova)

#####################################################################

#plot
find_hull<- function(df) df[chull(df$X, df$Y),]
hulls<- ddply(territories, "Territory", find_hull)

territory_size<-ggplot(territories, aes(x= X, y=Y, group=1, fill=Site))+
	geom_point(size=2, col="Black")+
	geom_polygon(data=hulls, alpha=0.5)+
	theme(panel.grid.major = element_blank(),
				panel.grid.minor = element_blank(),
				panel.background = element_blank(),
				axis.line = element_line(colour = "Black"), 
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				axis.title.x = element_text(colour = "Black", face="bold", size=14), 
				axis.title.y = element_text(colour = "Black", face="bold", size=14),
				strip.background = element_rect( fill="White"),
				legend.title = element_text(size = 16),
				legend.text = element_text(size = 12),
				strip.text.x = element_text(face="bold", size=12))+
	facet_wrap(~Label, nrow=2)+
	labs(x="X Transect (m)", y= "Y Transect (m)", fill="Coral cover")+
	scale_fill_manual(values =c("deepskyblue2", "firebrick4"),labels=c("HIGH", "LOW"))

ggsave("territory_size.tiff", units="in", width=9, height=6)


#######################################################################
#Behavioural analyses====
######################################################################
#Mean times for each pair
chaet_behaviour_mean<-aggregate(cbind(Aggression, Feeding, Searching, Travelling, Sociability, Exploration)~Pair_ID+Site_name, data=chaet_behaviour, FUN="mean")

######################################################################
#MANOVA#====
MANOVA_prop<-manova(cbind(Aggression,Exploration,Feeding, Sociability)~Site_name, data=chaet_behaviour_mean)
summary(MANOVA_prop)
print(MANOVA_prop)
summary.aov(MANOVA_prop, p.adjust.method="bonferroni")

######################################################################
#Boxplots for each trait using proportions
######################################################################
#Create dataframe
chaet_boxplot$Behaviour <- factor(chaet_boxplot$Behaviour, 
																			 levels=c("Exploration", "Feeding", "Sociability", "Aggression"))

p1 <- ggplot(chaet_boxplot, aes(x=Behaviour, y=Time_s, fill=Site_name))+ 
	geom_boxplot(width=0.3, position=position_dodge(0.45), alpha=0.8)+
	geom_point(position=position_dodge(0.45), size=3, alpha=0.6)+
	theme(panel.grid.major = element_blank(),
				panel.grid.minor = element_blank(),
				panel.background = element_blank(),
				axis.line = element_line(colour = "Black"), 
				axis.text.y=element_text(size= 14, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=14, colour="Black"),
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				strip.background = element_rect( fill="White"),
				legend.position="none")+
	annotate(geom = 'segment', x= Inf, xend = Inf, y = -Inf, yend = Inf)+
	labs(x="Behaviour category", y="Time (seconds)", fill="Coral cover")+
	scale_fill_manual(values =c("deepskyblue2", "firebrick4"),labels=c("HIGH", "LOW"))


p2 <- ggplot(chaet_boxplot, aes(x=Behaviour, y=Time_s_Agg, fill=Site_name))+ 
	geom_boxplot(width=0.3, position=position_dodge(0.45),  alpha=0.8)+
	geom_point(position=position_dodge(0.45), size=3, alpha=0.6)+
	theme(panel.grid.major = element_blank(),
				panel.grid.minor = element_blank(),
				panel.background = element_blank(),
				axis.line = element_line(colour = "Black"), 
				axis.text.y=element_text(size= 14, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=14, colour="Black"),
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				strip.background = element_rect( fill="White"),
				legend.position="none")+
	annotate(geom = 'segment', x= Inf, xend = Inf, y = -Inf, yend = Inf)+
	labs(x="Behaviour category", y="Proportion of time invested", breaks =c(0,0.01,0.02,0.03,0.04,0.05), fill="Coral cover")+
	scale_x_discrete(labels=c("Exploration", "Feeding", "Sociability", "Aggression"))+
	scale_fill_manual(values =c("deepskyblue2", "firebrick4"),labels=c("HIGH", "LOW"))+
theme(panel.background = element_rect(fill = NA))

g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, 
										 pp$l, pp$b, pp$l)
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

boxplot<-grid.draw(as_ggplot(g))
ggsave("overall_plot.tiff")


#Check to see if aggression is a consequence of abundance

#sum for each pair
prob<-encounter_data
prob_A<- aggregate(Prop_A~Pair_ID+Site_name, prob,FUN="mean")
number<-aggregate(Total~Pair_ID+Site_name,prob,FUN="mean")

#Test residuals
lm.residual<- lm(Prop_A~Site_name, data=prob)
sresid <- studres(lm.residual) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

prob_glm<-glm(Prop_A~Site_name, family=quasibinomial(), data=prob_A)
summary(prob_glm)
plot(prob_glm)

#number of encounters
lm.residual.n<- lm(Total~Site_name, data=number)
sresid <- studres(lm.residual.n) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

encounter_glm<-glm(Total~Site_name, data=number, family=quasipoisson())
summary(encounter_glm)
plot(encounter_glm)

#####################################################################
#comparing feeding and foraging behaviours across sites====
######################################################################
#Between sites feeding
lm.residual.F<- lm(Feeding~Site_name, data=chaet_behaviour_mean)
sresid <- studres(lm.residual.F) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

ANOVA_F<-aov(Feeding~Site_name, data=chaet_behaviour_mean)
summary(ANOVA_F)

#Between sites searching
lm.residual.FS<- lm(Searching~Site_name, data=chaet_behaviour_mean)
sresid <- studres(lm.residual.FS) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

ANOVA_FS<-aov(Searching~Site_name, data=chaet_behaviour_mean)
summary(ANOVA_FS)


#Individual sites
#PK
behav_FFS_PK<-
	chaet_FFS%>%
	filter(Site_name=="High")

lm.residual.FFS.PK<- lm(time_seconds~Behaviour, data=behav_FFS_PK)
sresid <- studres(lm.residual.FFS.PK) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

ANOVA_FFS.PK<-aov(time_seconds~Behaviour, data=behav_FFS_PK)
summary(ANOVA_FFS.PK)

######################################################################
#SAM
behav_FFS_SAM<-
	chaet_FFS%>%
	filter(Site_name=="Low")

lm.residual.FFS.SAM<- lm(time_seconds~Behaviour, data=behav_FFS_SAM)
sresid <- studres(lm.residual.FFS.SAM) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

ANOVA_FFS.SAM<-aov(time_seconds~Behaviour, data=behav_FFS_SAM)
summary(ANOVA_FFS.SAM)

######################################################################
#plot
FFS_plot<- ggplot(chaet_FFS, aes(x=Site_name, y=time_seconds, fill=Behaviour))+
	geom_boxplot(width=0.7)+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				axis.text.y=element_text(size= 12, colour="Black"),
				axis.text.x = element_text(angle=90, vjust=0.5, size=12, colour="Black"),
				strip.background = element_rect( fill="White"),  
				legend.text=element_text(size=14),
				strip.text.x = element_text(face="bold", size=9.5))+
	guides(fill=guide_legend(title=NULL, size=60))+
	labs(x="Resource availability", y="Time (seconds)")+
	scale_x_discrete(labels=c("HIGH", "LOW"))+
	scale_fill_manual(values=c("#808080", "#E0E0E0"), labels = c("Feeding", "Searching"))

ggsave("FFS_plot.png", units="in", width=9, height=5, dpi=300)


######################################################################
#Principal component analysis==== 
######################################################################
behav_PCA <- chaet_behaviour_mean[, 3:7]
head(behav_PCA)

######################################################################
#compute PCA
behav.pca.site <- prcomp(behav_PCA, scale = TRUE)
summary(behav_PCA)

#get eigenvalues
ev <- behav.pca.site$sdev^2
ev

Eigenvalue.plot<- function(ev) {
	n = length(ev)
	bsm = data.frame(j=seq(1:n), p=0)
	bsm$p[1] = 1/n
	for (i in 2:n) bsm$p[i] = bsm$p[i-1] + (1/(n + 1 - i))
	bsm$p = 100*bsm$p/n
	
	
	op = par(mfrow=c(2,1),omi=c(0.1,0.3,0.1,0.1), mar=c(1, 1, 1, 1))
	barplot(ev, col="Grey", las=2)
	abline(h=mean(ev), col="red")
	legend("topright", "Mean eigenvalue", lwd=1, col=2, bty="n")
	barplot(t(cbind(100*ev/sum(ev), bsm$p[n:1])), beside=TRUE, 
					col=c("Grey",2), las=2)
	legend("topright", c("% variation", "Broken stick model"), 
				 pch=15, col=c("Grey",2), bty="n")
	par(op)
}
######################################################################
#Visualise PCA
######################################################################

fviz_eig(behav.pca.site)

#PCA loadings
behav.pca.site$rotation

loadings<-behav.pca.site$rotation
loadings<-format(round(loadings, 3), nsmall = 3) 
loadings_plot<-loadings[, 1:2] 
loadings_plot<-ggtexttable(loadings_plot, theme=ttheme(base_style="blank"))

loadings_plot<-loadings_plot%>%
	tab_add_hline(at.row = c(1, 2), row.side = "top", linewidth = 3, linetype = 1) %>%
	tab_add_hline(at.row = c(6), row.side = "bottom", linewidth = 3, linetype = 1) %>%
	tab_add_vline(at.column = c(1), column.side = "left", linewidth = 3, linetype = 1) %>%
	tab_add_vline(at.column = c(3), column.side = "right", linewidth = 3, linetype = 1) %>%
	tab_add_vline(at.column = 2:tab_ncol(loadings_plot), column.side = "left", from.row = 2, linetype = 2)

#Join individuals and variables in biplot
fviz_pca_biplot(behav.pca.site, repel = TRUE,col.var = "Black", col.ind = "#696969")

#Add in site as group
set.seed(1)
groups<-as.factor(behav.PCA$Site_name[1:20])
biplot<-fviz_pca_biplot(behav.pca.site, repel=T, habillage=chaet_behaviour_mean$Site_name, palette =c("deepskyblue2", "firebrick4"),  
												col.var = "Black", alpha.var=0.6, 
												addEllipses=TRUE, labelsize=7, expand=20,  ellipse.type = "confidence", ellipse.alpha=0.3, 
												geom=c("point", "text"))+
	theme(axis.line = element_line(colour = "Black"), 
				panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				legend.position= "none",
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				axis.text.y=element_text(size= 12, colour="Black"),
				axis.text.x = element_text( vjust=0.5, size=12, colour="Black"),
				title=NULL)+
	ggtitle(NULL)+
	labs(x="PC1(62.4%)", y="PC2 (16.7%)")

biplot<-fviz_pca_biplot(behav.pca.site, repel=T, habillage=chaet_behaviour_mean$Site_name, palette =c("deepskyblue2", "firebrick4"),  
								col.var = "Black", alpha.var=0.9, 
								addEllipses=TRUE, labelsize=7, expand=20,  ellipse.type = "confidence", ellipse.alpha=0.3, 
								geom=c("point", "text"))+
	theme(axis.line = element_line(colour = "Black"), 
				panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				legend.position= "none",
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				axis.text.y=element_text(size= 12, colour="Black"),
				axis.text.x = element_text( vjust=0.5, size=12, colour="Black"),
				title=NULL)+
	ggtitle(NULL)+
	labs(x="PC1(62.4%)", y="PC2 (16.7%)")



biplot_figure<-biplot+inset_element(loadings_plot, 0, 0.3, 1.8, 0.1, on_top=FALSE)

ggsave(file="biplot_figure.tiff")

######################################################################
#Checking assumptions 
######################################################################

#Sphericity (bartlett test)
assumptions <- paf(as.matrix(behav_PCA), eigcrit = 1, convcrit = .001)
bartlettTest <- cortest.bartlett(behav.pers.site.pca, n = 20)
bartlettTest

#Sampling accuracy
print(assumptions$KMO)

######################################################################
##### Abundance/ Density #####
######################################################################

#Abundance/density
abundance<-fish_abundance

abundance_lun<-
	abundance%>%
	filter(Species=="C.lunulatus")

abundance_lun$Site<-as.factor(abundance_lun$Site)
abundance_lun$Depth<-as.factor(abundance_lun$Depth)

mean_abundance<- aggregate(abundance_lun$Abundance, by=list(abundance_lun$Site), FUN=mean) 
sd_abundance<- aggregate(abundance_lun$Abundance, by=list(abundance_lun$Site), FUN=sd) 


mean_depth<-aggregate(abundance_lun$Abundance, by=list(abundance_lun$Site, abundance_lun$Depth), FUN=mean) 
sd_depth<- aggregate(abundance_lun$Abundance, by=list(abundance_lun$Site, abundance_lun$Depth), FUN=sd) 


lm.residual_abundance_lun<- lm(Abundance~Site, data=abundance_lun)
sresid <- studres(lm.residual_abundance_lun) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

glm_abundance<-glm(Abundance~Site, data=abundance_lun, family = gaussian())
summary(glm_abundance)
plot(glm_abundance)
anova(glm_abundance)

#plot  sites
abundance_plot<-ggplot(abundance_lun, aes(x=Site, y=Abundance))+
	geom_boxplot(width=0.5, position=position_dodge(0.65))+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				axis.text.y=element_text(size= 12, colour="Black"),
				axis.text.x = element_text(angle=90, vjust=0.5, size=12, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	guides(fill=guide_legend(title=NULL))+
	labs(x="Site", y="Density")

ggsave(file="abundance_plot.png")

#plot  depth
ggplot(abundance_lun, aes(x=Site, y=Abundance, fill=Depth))+
	geom_boxplot(width=0.5, position=position_dodge(0.65))+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold"), 
				axis.title.y = element_text(colour = "Black", face="bold"),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(angle=90, vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	guides(fill=guide_legend(title=NULL))+
	scale_fill_brewer(palette="Greys")+
	labs(x="Site", y="Abundance")


#Species analysis with each site separately
abundance_PK<-
	abundance%>%
	filter(Site=="HIGH")

lm.residual_abundance_pk<- lm(Abundance~Species, data=abundance_PK)
sresid <- studres(lm.residual_abundance_pk) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

glm_species<-glm(Abundance~Species, data=abundance_PK, family=gaussian())
summary(glm_species)
plot(glm_species)

#Compare with depth as interaction
glm_species_depth<-glm(Abundance~Species*Depth, data=abundance_PK, family = gaussian())
summary(glm_species_depth)
plot(glm_species_depth)
anova(glm_species_depth)

#Compare with depth as additional factor
glm_species_depth_2<-glm(Abundance~Species+Depth, data=abundance_PK, family = gaussian())
summary(glm_species_depth_2)
plot(glm_species_depth_2)
anova(glm_species_depth_2)

#Compare with likelihood ratio test#
lrtest(glm_species,glm_species_depth,glm_species_depth_2)

#Use interaction term model in results.

abundance_SAM<-
	abundance%>%
	filter(Site=="LOW")

lm.residual_abundance_SAM<- lm(Abundance~Species, data=abundance_SAM)
sresid <- studres(lm.residual_abundance_SAM) 
hist(sresid, freq=FALSE)
xfit<-seq(min(sresid),max(sresid),length=40) 
yfit<-dnorm(xfit) 
lines(xfit, yfit)

glm_species_sam<-glm(Abundance~Species, data=abundance_SAM, family=gaussian())
summary(glm_species_sam)
plot(glm_species_sam)

#Compare with depth as interaction
glm_species_depth<-glm(Abundance~Species*Depth, data=abundance_SAM, family = gaussian())
summary(glm_species_depth)
plot(glm_species_depth)
anova(glm_species_depth)

#Compare with depth as additional factor
glm_species_depth_2<-glm(Abundance~Species+Depth, data=abundance_SAM, family = gaussian())
summary(glm_species_depth_2)
plot(glm_species_depth_2)
anova(glm_species_depth_2)

#Compare with likelihood ratio test#
lrtest(glm_species,glm_species_depth,glm_species_depth_2)

#Use interaction term model in results.

abundance.spp<-ggplot(abundance, aes(x=Site, y=Abundance, fill=Species))+
	geom_boxplot(width=0.5, position=position_dodge(0.65))+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=16), 
				axis.title.y = element_text(colour = "Black", face="bold", size=16),
				axis.text.y=element_text(size= 12, colour="Black"),
				axis.text.x = element_text(angle=90, vjust=0.5, size=12, colour="Black"),
				strip.background = element_rect( fill="White"),
				legend.text=element_text(size=12),
				legend.key = element_rect(fill = "transparent"),
				strip.text.x = element_text(face="bold", size=9.5))+
	guides(fill=guide_legend(title=NULL))+
	labs(x="Resource availability", y="Density")+
	scale_fill_manual(values=c("White", "Dark Grey"))+
	facet_wrap(~Depth)

ggsave(file="abundance.spp.png")

######################################################################
#Individual level analyses====
######################################################################

#Pair ID MANOVA
#PK
behav.pk<-
	chaet_behaviour%>%
	filter(Site_name=="PK")

MANOVA_PK<- manova(cbind(Aggression,Exploration,Feeding,Sociability, Searching, Travelling)~Pair_ID, data=behav.pk)

summary.aov(MANOVA_PK, p.adjust.method="bonferroni")

#SAM
behav.sam<-
	chaet_behaviour%>%
	filter(Site_name=="SAM")

MANOVA_SAM<- manova(cbind(Aggression,Exploration,Feeding,Sociability, Searching, Travelling)~Pair_ID, data=behav.sam)
summary.aov(MANOVA_SAM, p.adjust.method="bonferroni")

#boxplot feeding
ggplot(behav.sam, aes(x=Pair_ID, y=Feeding, fill=Site_name))+ 
	geom_boxplot(width=0.3, position=position_dodge(0.45))+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=15), 
				axis.title.y = element_text(colour = "Black", face="bold", size=15),
				axis.text.y=element_text(size= 15, colour="Black"),
				axis.text.x = element_text(angle=45, vjust=0.5,  size=15, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=15))+
	labs(x="Pair", y="Feeding")+
	scale_y_continuous("Proportion", breaks =c(0,0.25,0.5,0.75,1))+
	scale_fill_manual(values =c("grey39", "grey"),labels=c("HIGH", "LOW"))


#Among individual variation data frame#
summary.aov(MANOVA_PK)

Site<-c("High", "Low","High", "Low","High", "Low","High", "Low","High", "Low","High", "Low","High", "Low","High", "Low","High", "Low","High", "Low")
Behaviour<-c("Aggression", "Aggression", "Feeding", "Feeding", "Searching", "Searching", "Travelling", "Travelling", "Sociability", "Sociability","Aggression", "Aggression", "Feeding", "Feeding", "Searching", "Searching", "Travelling", "Travelling", "Sociability", "Sociability")
Total<-c(1104.78, 65.041, 13740, 16931.1, 12876.9, 14351.4, 3390.2,8060.6,22624,25681)
Variance<-c(413.52, 37.505, 6517.9, 11703.2, 7236.2, 5958.8, 1849.7, 3984.0, 9964,10434) 
Residual<-Total-Variance
Variance<-c(413.52, 37.505, 6517.9, 11703.2, 7236.2, 5958.8, 1849.7, 3984.0, 9964,10434, Residual) 
Type<-c("Among","Among","Among","Among","Among","Among","Among","Among","Among","Among",
				"Residual","Residual","Residual","Residual","Residual","Residual","Residual","Residual","Residual","Residual")
				
Proportion<-Variance/Total

Variance<-as.data.frame(cbind(Site, Behaviour, Variance, Type, Proportion))

#Plots of variation
#Actual variations variation 
ggplot(Variance, aes(x=Site, y=Proportion, fill=Type))+
	geom_bar(stat="Identity", width=0.7)+
	theme(panel.grid.major = element_blank(), 
				panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold"),
				axis.title.y = element_text(colour = "Black", face="bold"),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(angle=45, vjust=0.5, size=10, colour="Black"))+
	labs(x="Behaviour", y= "Data points")+
	guides(fill=guide_legend(title=NULL))+
	scale_fill_manual(values=c("Black", "Grey"))+
	facet_wrap(~Behaviour)

Variance$Behaviour<-factor(Behaviour,
														levels=c("Aggression","Feeding","Searching", "Travelling", "Sociability")) 


#Proportion of variation 
Variance$Proportion<-as.numeric(Variance$Proportion)

variance_prop<-ggplot(Variance, aes(x=Site, y=Proportion, fill=Type))+
	geom_bar(stat="Identity", width=0.7)+
	theme(panel.grid.major = element_blank(), 
				panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				strip.background = element_rect( fill="White"),  
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12),
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				legend.text = element_text(size = 10, face="bold"),
				panel.spacing=unit(0.7, "cm"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"))+
	labs(x=NULL, y= "Proportion")+
	scale_y_continuous(breaks=seq(0, 1, 0.25))+
	guides(fill=guide_legend(title=NULL))+
	scale_fill_manual(values=c("Black", "Grey"))+
	facet_wrap(~Behaviour, nrow=1, scales="free_x")+
	theme(strip.text = element_text(size = 10, face="bold"))

#Individual behaviours
#Aggression
Variance_agg<-
Variance%>%
	filter(Behaviour=="Aggression")

agg_variance<-ggplot(Variance_agg, aes(x=Site, y=Proportion, fill=Type))+
	geom_bar(stat="Identity", width=0.7)+
	theme(panel.grid.major = element_blank(), 
				panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				plot.title=element_text(face="bold"),
				strip.background = element_rect( fill="White"),  
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12),
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				legend.text = element_text(size = 10, face="bold"),
				panel.spacing=unit(0.7, "cm"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"))+
	labs(x=NULL, y= "Proportion")+
	ggtitle("Aggression")+
	guides(fill=guide_legend(title=NULL))+
	scale_y_continuous(breaks=seq(0, 1, 0.25))+
	scale_fill_manual(values=c("Black", "Grey"))

#Feeding
Variance_feed<-
	Variance%>%
	filter(Behaviour=="Feeding")

feed_variance<-ggplot(Variance_feed, aes(x=Site, y=Proportion, fill=Type))+
	geom_bar(stat="Identity", width=0.7)+
	theme(panel.grid.major = element_blank(), 
				panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				strip.background = element_rect( fill="White"),  
				plot.title=element_text(face="bold"),
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12),
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				legend.text = element_text(size = 10, face="bold"),
				panel.spacing=unit(0.7, "cm"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"))+
	labs(x=NULL, y= "Proportion")+
	ggtitle("Feeding")+
	guides(fill=guide_legend(title=NULL))+
	scale_y_continuous(breaks=seq(0, 1, 0.25))+
	scale_fill_manual(values=c("Black", "Grey"))


#Searching
Variance_search<-
	Variance%>%
	filter(Behaviour=="Searching")

search_variance<-ggplot(Variance_search, aes(x=Site, y=Proportion, fill=Type))+
	geom_bar(stat="Identity", width=0.7)+
	theme(panel.grid.major = element_blank(), 
				panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				plot.title=element_text(face="bold"),
				strip.background = element_rect( fill="White"),  
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12),
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				legend.text = element_text(size = 10, face="bold"),
				panel.spacing=unit(0.7, "cm"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"))+
	labs(x=NULL, y= "Proportion")+
	ggtitle("Searching")+
	guides(fill=guide_legend(title=NULL))+
	scale_y_continuous(breaks=seq(0, 1, 0.25))+
	scale_fill_manual(values=c("Black", "Grey"))

#Travelling
Variance_travel<-
	Variance%>%
	filter(Behaviour=="Travelling")

travel_variance<-ggplot(Variance_travel, aes(x=Site, y=Proportion, fill=Type))+
	geom_bar(stat="Identity", width=0.7)+
	theme(panel.grid.major = element_blank(), 
				panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				plot.title=element_text(face="bold"),
				strip.background = element_rect( fill="White"),  
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12),
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				legend.text = element_text(size = 10, face="bold"),
				panel.spacing=unit(0.7, "cm"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"))+
	labs(x=NULL, y= "Proportion")+
	ggtitle("Travelling")+
	guides(fill=guide_legend(title=NULL))+
	scale_y_continuous(breaks=seq(0, 1, 0.25))+
	scale_fill_manual(values=c("Black", "Grey"))


#Sociability
Variance_soc<-
	Variance%>%
	filter(Behaviour=="Sociability")

sociability_variance<-ggplot(Variance_soc, aes(x=Site, y=Proportion, fill=Type))+
	geom_bar(stat="Identity", width=0.7)+
	theme(panel.grid.major = element_blank(), 
				panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				strip.background = element_rect( fill="White"),  
				plot.title=element_text(face="bold"),
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12),
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				legend.text = element_text(size = 10, face="bold"),
				panel.spacing=unit(0.7, "cm"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"))+
	labs(x=NULL, y= "Proportion")+
	ggtitle("Sociability")+
	guides(fill=guide_legend(title=NULL))+
	scale_y_continuous(breaks=seq(0, 1, 0.25))+
	scale_fill_manual(values=c("Black", "Grey"))

variance_plot<-ggarrange(agg_variance, feed_variance, search_variance, travel_variance, sociability_variance, nrow=5)

#bootstrap means for each behaviour at each site 
behav_mean_PK<-
	chaet_behaviour_mean%>%
	filter(Site_name=="PK")

behav_mean_SAM<-
	chaet_behaviour_mean%>%
	filter(Site_name=="SAM")

#bootstrap populations for each behaviour 
boot.mean.full = function(x,B,binwidth=NULL) {
	n = length(x)
	boot.samples = matrix( sample(x,size=n*B,replace=TRUE), B, n)
	boot.statistics = apply(boot.samples,1,mean)
	se = sd(boot.statistics)
	require(ggplot2)
	if ( is.null(binwidth) )
		binwidth = diff(range(boot.statistics))/30
	p = ggplot(data.frame(x=boot.statistics),aes(x=x)) +
		geom_histogram(aes(y=..density..),binwidth=binwidth, fill="grey55")+
		geom_density(color="Black")+
		theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
					panel.background = element_blank(), 
					axis.line = element_line(colour = "Black"), 
					axis.title.x = element_text(colour = "Black", face="bold", size=20), 
					axis.title.y = element_text(colour = "Black", face="bold", size=20),
					axis.text.y=element_text(size= 15, colour="Black"),
					axis.text.x = element_text(angle=45, vjust=0.5, size=15, colour="Black"),
					strip.background = element_rect( fill="White"),  
					strip.text.x = element_text(face="bold", size=9.5))+
		labs(x="Aggression",y="Density")+
		geom_vline(xintercept = mean(boot.statistics), linetype="dashed")
	plot(p)
	svg(filename="plot.svg")
	plot(p)
	dev.off()
	
	interval = mean(x) + c(-1,1)*2*se
	print( interval )
	return( list(boot.statistics = boot.statistics, interval=interval, se=se, plot=p) )
}

#just mean
boot.mean = function(x,B,binwidth=NULL) {
	n = length(x)
	boot.samples = matrix( sample(x,size=n*B,replace=TRUE), B, n)
	boot.statistics = apply(boot.samples,1,mean)
}


#Aggression
set.seed(1234)
out.pk = with(behav_mean_PK, boot.mean(Aggression, B = 1000))
quantile(out.pk,c(0.025, 0.975))


set.seed(1234)
out.sam = with(behav_mean_SAM, boot.mean(Aggression, B = 1000))
quantile(out.sam,c(0.025, 0.975))

PK<-data.frame(out.pk)
names(PK)[1] <- "BOOT"

SAM<-data.frame(out.sam)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Agg <-rbind(PK, SAM)

Aggression<-ggplot(Agg, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	geom_vline(xintercept=c(8.67,19.15), linetype="solid",color = "black", size=1)+
	geom_vline(xintercept=c(0.19,3.26), linetype="dashed", color = "black", size=1)+
	scale_fill_manual(values=c("Black", "Grey45"))+
	labs(x="Aggression",y="Density")

#Sociability
set.seed(1234)
out.pk = with(behav_mean_PK, boot.mean(Sociability, B = 1000))

quantile(out.pk,c(0.025, 0.975))

set.seed(1234)
out.sam = with(behav_mean_SAM, boot.mean(Sociability, B = 1000))
quantile(out.sam,c(0.025, 0.975))


PK<-data.frame(out.pk)
names(PK)[1] <- "BOOT"

SAM<-data.frame(out.sam)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Soc <-rbind(PK, SAM)

Sociability<-ggplot(Soc, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(525.35,576.06), linetype="solid",color = "black", size=1)+
	geom_vline(xintercept=c(467.41,522.42), linetype="dashed", color = "black", size=1)+
	labs(x="Sociability",y=NULL) 

#Searching
set.seed(1234)
out.pk = with(behav_mean_PK, boot.mean(Searching, B = 1000))
quantile(out.pk,c(0.025, 0.975))

set.seed(1234)
out.sam = with(behav_mean_SAM, boot.mean(Searching, B = 1000))
quantile(out.sam,c(0.025, 0.975))


PK<-data.frame(out.pk)
names(PK)[1] <- "BOOT"

SAM<-data.frame(out.sam)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Search <-rbind(PK, SAM)

Searching<-ggplot(Search, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	geom_vline(xintercept=c(249.68,294.17), linetype="solid",color = "black", size=1)+
	geom_vline(xintercept=c(303.21,344.61), linetype="dashed", color = "black", size=1)+
	scale_fill_manual(values=c("Black", "Grey45"))+
	labs(x="Searching",y=NULL)

#Travelling
set.seed(1234)
out.pk = with(behav_mean_PK, boot.mean(Travelling, B = 1000))
quantile(out.pk,c(0.025, 0.975))

set.seed(1234)
out.sam = with(behav_mean_SAM, boot.mean(Travelling, B = 1000))
quantile(out.sam,c(0.025, 0.975))

PK<-data.frame(out.pk)
names(PK)[1] <- "BOOT"

SAM<-data.frame(out.sam)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Travel <-rbind(PK, SAM)

Travelling<-ggplot(Travel, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(19.20,40.63), linetype="solid",color = "black", size=1)+
	geom_vline(xintercept=c(50.71,86.02), linetype="dashed", color = "black", size=1)+
	labs(x="Travelling",y=NULL)

#Feeding
set.seed(1234)
out.pk = with(behav_mean_PK, boot.mean(Feeding, B = 1000))
quantile(out.pk,c(0.025, 0.975))

set.seed(1234)
out.sam = with(behav_mean_SAM, boot.mean(Feeding, B = 1000))
quantile(out.sam,c(0.025, 0.975))

PK<-data.frame(out.pk)
names(PK)[1] <- "BOOT"

SAM<-data.frame(out.sam)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Feed <-rbind(PK, SAM)

Feeding<-ggplot(Feed, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	geom_vline(xintercept=c(258.54,300.33), linetype="solid",color = "black", size=1)+
	geom_vline(xintercept=c(166.50,224.42), linetype="dashed", color = "black", size=1)+
	scale_fill_manual(values=c("Black", "Grey45"))+
	labs(x="Feeding",y=NULL)

#Join plots#
bootstrap_plot<-ggarrange(Aggression, Feeding, Searching, Travelling, Sociability, nrow=1)
ggsave("bootstrap_plot.tiff", width=12)

#Repeatability and bootstrapped distributions 
#PK
repeat_PK<-
	chaet_behaviour%>%
	filter(Site_name=="PK")
MANOVA_PK<- manova(cbind(Aggression,Exploration,Feeding,Sociability, Searching, Travelling)~Pair_ID, data=repeat_PK)
summary.aov(MANOVA_PK)

#SAM
repeat_SAM<-
	chaet_behaviour%>%
	filter(Site_name=="SAM")
MANOVA_SAM<- manova(cbind(Aggression,Exploration,Feeding,Sociability, Searching, Travelling)~Pair_ID, data=repeat_SAM)
summary.aov(MANOVA_SAM)


#Sociability
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Sociability, B = 1000))

PK_soc<-ICCest(Pair_ID, Sociability, data=repeat_PK, CI.type="Smith")
PK_soc_boot<-boot.icc(repeat_PK$Sociability, repeat_PK$Pair_ID, 1000, aov.est=TRUE) 
summary(PK_soc_boot)
quantile(PK_soc_boot,c(0.025, 0.975))
as.vector(PK_soc_boot)
t.test(PK_soc_boot,conf.level = 0.95)

#bootstrap among individual variation
PK_soc_aov<- aov(Sociability~Pair_ID, data=repeat_PK)
summary(PK_soc_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(PK_soc_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Sociability~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)

data.PK <- data.frame(out.mean, between)
data.PK$MS=100*(between/(out.mean^2))
mean(data.PK$MS)
quantile(data.PK$MS,c(0.025, 0.975))

#SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Sociability, B = 1000))

ICCest(Pair_ID, Sociability, data=repeat_SAM, CI.type="Smith")
SAM_soc_boot<-boot.icc(repeat_SAM$Sociability, repeat_SAM$Pair_ID, 1000, aov.est=TRUE) 
summary(SAM_soc_boot)
quantile(SAM_soc_boot,c(.025,0.975))
as.vector(SAM_soc_boot)
t.test(SAM_soc_boot,conf.level = 0.95)

#bootstrap among individual variation
SAM_soc_aov<- aov(Aggression~Pair_ID, data=repeat_SAM)
summary(SAM_soc_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(SAM_soc_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Sociability~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

#combine vectors
out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)
data.SAM <- data.frame(out.mean, between)
data.SAM$MS=100*(between/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Soc.MS <-rbind(PK, SAM)


#Feeding
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Feeding, B = 1000))

ICCest(Pair_ID, Feeding, data=repeat_PK, CI.type="Smith")
PK_feed_boot<-boot.icc(repeat_PK$Feeding, repeat_PK$Pair_ID, 1000, aov.est=TRUE) 
summary(PK_feed_boot)
quantile(PK_feed_boot,c(0.025, 0.975))
as.vector(PK_feed_boot)
t.test(PK_feed_boot,conf.level = 0.95)

#bootstrap among individual variation
PK_F_aov<- aov(Feeding~Pair_ID, data=repeat_PK)
summary(PK_F_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(PK_F_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Feeding~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)
data.PK <- data.frame(out.mean, between)
data.PK$MS=(between/(out.mean^2)*100)
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))


#Feeding SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Feeding, B = 1000))

ICCest(Pair_ID, Feeding, data=repeat_SAM, CI.type="Smith") #GLM equivalent= 0.200
SAM_feed_boot<-boot.icc(repeat_SAM$Feeding, repeat_SAM$Pair_ID, 1000, aov.est=TRUE) 
summary(SAM_feed_boot)
quantile(SAM_feed_boot,c(0.025, 0.975))
as.vector(SAM_feed_boot)
t.test(SAM_feed_boot,conf.level = 0.95)

#bootstrap among individual variation
SAM_F_aov<- aov(Feeding~Pair_ID, data=repeat_SAM)
summary(SAM_F_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(SAM_F_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Feeding~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

#combine vectors
out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)
data.SAM <- data.frame(out.mean, between)
data.SAM$MS=100*(between/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Feed.MS <-rbind(PK, SAM)

#Searching
set.seed(12334)
out.mean = with(repeat_PK, boot.mean(Searching, B = 1000))

ICCest(Pair_ID, Searching, data=repeat_PK, CI.type="Smith") #GLM equivalent=0.054
PK_search_boot<-boot.icc(repeat_PK$Searching, repeat_PK$Pair_ID, 1000, aov.est=TRUE) 
summary(PK_search_boot)
quantile(PK_search_boot,c(0.025, 0.975))
as.vector(PK_search_boot)
t.test(PK_search_boot,conf.level = 0.95)

#bootstrap among individual variation
PK_FS_aov<- aov(Searching~Pair_ID, data=repeat_PK)
summary(PK_FS_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(PK_FS_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Searching~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

data.PK <- data.frame(out.mean, between)
data.PK$MS=100*(between/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))


#Searching SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Searching, B = 1000))

ICCest(Pair_ID, Searching, data=repeat_SAM, CI.type="Smith")
SAM_search_boot<-boot.icc(repeat_SAM$Searching, repeat_SAM$Pair_ID, 1000, aov.est=TRUE) 
summary(SAM_search_boot)
quantile(SAM_search_boot,c(0.025, 0.975))
as.vector(SAM_search_boot)
t.test(SAM_search_boot,conf.level = 0.95)

#bootstrap among individual variation
SAM_FS_aov<- aov(Searching~Pair_ID, data=repeat_SAM)
summary(SAM_FS_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(SAM_FS_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Searching~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

#combine vectors
out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)
data.SAM <- data.frame(out.mean, between)
data.SAM$MS=100*(between/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS, c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Search.MS <-rbind(PK, SAM)


#Travelling
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Travelling, B = 1000))

ICCest(Pair_ID, Travelling, data=repeat_PK, CI.type="Smith") #GLM equivalent=0.039
PK_travel_boot<-boot.icc(repeat_PK$Travelling, repeat_PK$Pair_ID, 1000, aov.est=TRUE) 
summary(PK_travel_boot)
quantile(PK_travel_boot,c(0.025, 0.975))
as.vector(PK_travel_boot)
t.test(PK_travel_boot,conf.level = 0.95)

#bootstrap among individual variation
PK_S_aov<- aov(Travelling~Pair_ID, data=repeat_PK)
summary(PK_S_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(PK_S_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Travelling~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

data.PK <- data.frame(out.mean, between)
data.PK$MS=100*(between/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))


#Travelling SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Travelling, B = 1000))

ICCest(Pair_ID, Travelling, data=repeat_SAM, CI.type="Smith")
SAM_travel_boot<-boot.icc(repeat_SAM$Travelling, repeat_SAM$Pair_ID, 1000, aov.est=TRUE) 
summary(SAM_travel_boot)
quantile(SAM_travel_boot,c(0.025, 0.975))
as.vector(SAM_travel_boot)
t.test(SAM_travel_boot,conf.level = 0.95)

#bootstrap among individual variation
SAM_S_aov<- aov(Travelling~Pair_ID, data=repeat_SAM)
summary(SAM_S_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(SAM_S_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Travelling~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

#combine vectors
out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)
data.SAM <- data.frame(out.mean, between)
data.SAM$MS=100*(between/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Travel.MS <-rbind(PK, SAM)


#Aggression
set.seed(1234)

#bootstrap population
out.mean = with(repeat_PK, boot.mean(Aggression, B = 1000))

ICCest(Pair_ID, Aggression, data=repeat_PK, CI.type="Smith")
PK_agg_boot<-boot.icc(repeat_PK$Aggression, repeat_PK$Pair_ID, 1000, aov.est=TRUE) 
summary(PK_agg_boot)
quantile(PK_agg_boot,c(0.025, 0.975))
as.vector(PK_agg_boot)
t.test(PK_agg_boot,conf.level = 0.95)

#bootstrap among individual variation
PK_Agg_aov<- aov(Aggression~Pair_ID, data=repeat_PK)
summary(PK_Agg_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(PK_Agg_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Aggression~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

#combine vectors
out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)
data.PK <- data.frame(out.mean, between)
data.PK$MS=100*(between/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))

#Aggression SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Aggression, B = 1000))

ICCest(Pair_ID, Aggression, data=repeat_SAM, CI.type="Smith")
SAM_agg_boot<-boot.icc(repeat_SAM$Aggression, repeat_SAM$Pair_ID, 1000, aov.est=TRUE) 
summary(SAM_agg_boot)
quantile(SAM_agg_boot,c(0.025, 0.975), na.rm=TRUE)
as.vector(SAM_agg_boot)
t.test(SAM_agg_boot,conf.level = 0.95)

#bootstrap among individual variation
SAM_agg_aov<- aov(Aggression~Pair_ID, data=repeat_SAM)
summary(SAM_agg_aov)

get_MS <- function(model) {
	anova(model)$`Mean Sq`[1]
}
get_MS(SAM_agg_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Aggression~Pair_ID, data = .))) %>% 
	mutate(between_group_ms = map_dbl(models, get_MS))

#Mean and confidence interval 
between<-as.vector(permuted$between_group_ms)
t.test(between,conf.level = 0.95)

#combine vectors
out.mean<-as.vector(out.mean)
between<-as.vector(permuted$between_group_ms)
data.SAM <- data.frame(out.mean, between)
data.SAM$MS=100*(between/(out.mean^2))
data.clean <- data.SAM[-which(data$out.mean == "0" ), ] 
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.clean$MS,c(0.025, 0.975))


PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Agg.MS <-rbind(PK, SAM)

#Differences between sites- plot ICC distributions====
#Sociability
PK<-data.frame(PK_soc_boot)
names(PK)[1] <- "BOOT"

SAM<-data.frame(SAM_soc_boot)
names(SAM)[1] <- "BOOT"


PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Soc.ICC <-rbind(PK, SAM)

Sociability.ICC<-ggplot(Soc.ICC, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.6, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("deepskyblue2", "firebrick4"))+
	geom_vline(xintercept=c(-0.08,0.45), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(-0.11,0.43), linetype="dashed", color = "black", size=0.5)+
	labs(x="Sociability",y="Density", fill="Coral cover")


#Feeding
PK<-data.frame(PK_feed_boot)
names(PK)[1] <- "BOOT"

SAM<-data.frame(SAM_feed_boot)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

feed.ICC <-rbind(PK, SAM)

Feeding.ICC<-ggplot(feed.ICC, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.6, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("deepskyblue2", "firebrick4"))+
	geom_vline(xintercept=c(-0.08,0.45), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(-0.02,0.61), linetype="dashed",color = "black", size=0.5)+
	labs(x="Feeding",y="Density", fill="Coral cover")


#Searching
PK<-data.frame(PK_search_boot)
names(PK)[1] <- "BOOT"

SAM<-data.frame(SAM_search_boot)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

search.ICC <-rbind(PK, SAM)

Searching.ICC<-ggplot(search.ICC, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.6, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(),
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("deepskyblue2", "firebrick4"))+
	geom_vline(xintercept=c(-0.07,0.50), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(-0.15,0.48), linetype="dashed",color = "black", size=0.5)+
	labs(x="Searching",y="Density", fill="Coral cover")

#Travelling
PK<-data.frame(PK_travel_boot)
names(PK)[1] <- "BOOT"

SAM<-data.frame(SAM_travel_boot)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

travel.ICC <-rbind(PK, SAM)

Travelling.ICC<-ggplot(travel.ICC, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.6, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("deepskyblue2", "firebrick4"))+
	geom_vline(xintercept=c(-0.03,0.59), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(-0.08,0.46), linetype="dashed",color = "black", size=0.5)+
	labs(x="Travelling",y="Density", fill="Coral cover")

#Aggression
PK<-data.frame(PK_agg_boot)
names(PK)[1] <- "BOOT"

SAM<-data.frame(SAM_agg_boot)
names(SAM)[1] <- "BOOT"

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Agg.ICC <-rbind(PK, SAM)

Aggression.ICC<-ggplot(Agg.ICC, aes(BOOT, fill = Site)) + 
	geom_histogram(alpha = 0.6, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text( vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("deepskyblue2", "firebrick4"))+
	geom_vline(xintercept=c(-0.10,0.40), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(-0.05,0.59), linetype="dashed",color = "black", size=0.5)+
	labs(x="Aggression",y="Density", fill="Coral cover")

#combine plots#
ICC_plot<-ggarrange(Aggression.ICC, Feeding.ICC, Searching.ICC, Travelling.ICC, Sociability.ICC, nrow=1)

#Add summary table
#Aggression
R<-c("0.108", "0.195")
Ia<-c("421.735", "4300.551")
Iw<-c("410.463", "4497.196")

Table_Aggression<-rbind(R,Ia,Iw)
colnames(Table_Aggression) <- c("High", "Low")
rownames(Table_Aggression) <- c("R", "Ia", "Iw")

#Feeding 
R<-c("0.164", "0.298")
Ia<-c("8.987", "16.964")
Iw<-c("9.091", "17.272")

Table_Feeding<-rbind(R,Ia,Iw)
colnames(Table_Feeding) <- c("High", "Low")
rownames(Table_Feeding) <- c("R", "Ia", "Iw")

#Searching
R<-c("0.211", "0.104")
Ia<-c("8.067", "7.638")
Iw<-c("8.133", "7.537")

Table_Searching<-rbind(R,Ia,Iw)
colnames(Table_Searching) <- c("High", "Low")
rownames(Table_Searching) <- c("R", "Ia", "Iw")


#Travel
R<-c("0.227", "0.162")
Ia<-c("194.054", "100.117")
Iw<-c("197.323", "99.463")

Table_Travel<-rbind(R,Ia,Iw)
colnames(Table_Travel) <- c("High", "Low")
rownames(Table_Travel) <- c("R", "Ia", "Iw")

#Sociability
R<-c("0.112", "0.099")
Ia<-c("3.952", "5.915)")
Iw<-c("3.946", "5.821")

Table_Sociability<-rbind(R,Ia,Iw)
colnames(Table_Sociability) <- c("High", "Low")
rownames(Table_Sociability) <- c("R", "Ia", "Iw")

#Finalise tables
Table_Aggression<-ggtexttable(Table_Aggression, theme=ttheme(base_style="blank"))
Table_Aggression<-Table_Aggression%>%
	tab_add_vline(at.column =  c(2), column.side =  "right", linewidth = 3, linetype = 1) %>%
	tab_add_hline(at.row = c(1), row.side = "bottom", linewidth = 3, linetype = 1) 

Table_Feeding<-ggtexttable(Table_Feeding, theme=ttheme(base_style = "blank"))
Table_Feeding<-Table_Feeding%>%
	tab_add_vline(at.column =  c(2), column.side =  "right", linewidth = 3, linetype = 1) %>%
	tab_add_hline(at.row = c(1), row.side = "bottom", linewidth = 3, linetype = 1) 

Table_Searching<-ggtexttable(Table_Searching, theme=ttheme(base_style = "blank"))
Table_Searching<-Table_Searching%>%
	tab_add_vline(at.column =  c(2), column.side =  "right", linewidth = 3, linetype = 1) %>%
	tab_add_hline(at.row = c(1), row.side = "bottom", linewidth = 3, linetype = 1) 

Table_Travel<-ggtexttable(Table_Travel, theme=ttheme(base_style = "blank"))
Table_Travel<-Table_Travel%>%
	tab_add_vline(at.column =  c(2), column.side =  "right", linewidth = 3, linetype = 1) %>%
	tab_add_hline(at.row = c(1), row.side = "bottom", linewidth = 3, linetype = 1) 

Table_Sociability<-ggtexttable(Table_Sociability, theme=ttheme(base_style = "blank"))
Table_Sociability<-Table_Sociability%>%
	tab_add_vline(at.column =  c(2), column.side =  "right", linewidth = 3, linetype = 1) %>%
	tab_add_hline(at.row = c(1), row.side = "bottom", linewidth = 3, linetype = 1) 

Aggression_plot<-ggarrange(agg_variance, Aggression.ICC, Table_Aggression, nrow=1, widths=c(1,1,0.5))
Feeding_plot<-ggarrange(feed_variance,  Feeding.ICC, Table_Feeding, nrow=1,widths=c(1,1,0.5))
Searching_Plot<-ggarrange(search_variance, Searching.ICC, Table_Searching, nrow=1,widths=c(1,1,0.5))
Travelling_plot<-ggarrange(travel_variance, Travelling.ICC, Table_Travel, nrow=1,widths=c(1,1,0.5))
Sociability_plot<-ggarrange(sociability_variance, Sociability.ICC, Table_Sociability, nrow=1,widths=c(1,1,0.5))

#combine plots and table
repeatability_plot<-ggarrange(Aggression_plot, Feeding_plot, Searching_Plot,
															Travelling_plot, Sociability_plot, nrow=5)

ggsave("repeatability_plot.tiff", height=9, width=9)


#plot mean standardisation distributions#
Sociability.MS<-ggplot(Soc.MS, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.8, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(3.87, 4.03), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(5.78, 6.05), linetype="dashed", color = "black", size=0.5)+
	labs(x="Sociability",y=NULL)

Feeding.MS<-ggplot(Feed.MS, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(2.92, 17.48), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(6.29, 34.75), linetype="dashed",color = "black", size=0.5)+
	labs(x="Feeding",y=NULL)

Searching.MS<-ggplot(Search.MS, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(2.54,15.48), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(2.70, 13.60), linetype="dashed",color = "black", size=0.5)+
	labs(x="Searching",y=NULL)

Travelling.MS<-ggplot(Travel.MS, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(37.15, 226.93), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(26.45, 171.79), linetype="dashed",color = "black", size=0.5)+
	labs(x="Travelling",y=NULL)

Aggression.MS<-ggplot(Agg.MS, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(102.04, 1019.61), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(217.19, 27788.38), linetype="dashed",color = "black", size=0.5)+
	labs(x="Aggression",y="Density")

#join plots
MS_plot<-ggarrange(Aggression.MS, Feeding.MS, Searching.MS, Travelling.MS, Sociability.MS, nrow=1)
ggsave("MS_plot.tiff", width=12)


##### Bootstrap residual MS #####
#Aggression
#PK
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Aggression, B = 1000))

PK_Agg_aov<- aov(Aggression~Pair_ID, data=repeat_PK)
summary(PK_Agg_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(PK_Agg_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Aggression~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.PK <- data.frame(out.mean, within)
data.PK$MS=100*(within/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))

#SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Aggression, B = 1000))

#bootstrap within individual variation
SAM_Agg_aov<- aov(Aggression~Pair_ID, data=repeat_SAM)
summary(SAM_Agg_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(SAM_Agg_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Aggression~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.SAM <- data.frame(out.mean, within)
data.SAM$MS=100*(within/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))
mean(data.SAM$MS)

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Agg.MS.R <-rbind(PK, SAM)

Aggression.MS.R<-ggplot(Agg.MS.R, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(165.05, 854.78), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(267.78, 84980.47), linetype="dashed",color = "black", size=0.5)+
	labs(x="Aggression",y="Density")


#Feeding
#PK
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Feeding, B = 1000))

PK_Feed_aov<- aov(Feeding~Pair_ID, data=repeat_PK)
summary(PK_Feed_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(PK_Feed_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Feeding~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.PK <- data.frame(out.mean, within)
data.PK$MS=100*(within/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))

#SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Feeding, B = 1000))

#bootstrap within individual variation
SAM_Feed_aov<- aov(Feeding~Pair_ID, data=repeat_SAM)
summary(SAM_Feed_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(SAM_Feed_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Feeding~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.SAM <- data.frame(out.mean, within)
data.SAM$MS=100*(within/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Feed.MS.R <-rbind(PK, SAM)


Activity_F.MS.R<-ggplot(Feed.MS.R, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(6.86, 11.26), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(11.61, 24.19), linetype="dashed",color = "black", size=0.5)+
	labs(x="Feeding",y=NULL)

svg(filename="Activity_F_MS_R.svg") 
plot(Activity_F.MS.R) 
dev.off()

#Searching
#PK
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Searching, B = 1000))

#bootstrap within individual variation
PK_search_aov<- aov(Searching~Pair_ID, data=repeat_PK)
summary(PK_search_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(PK_search_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Searching~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.PK <- data.frame(out.mean, within)
data.PK$MS=100*(within/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))

#SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Searching, B = 1000))

#bootstrap within individual variation
SAM_search_aov<- aov(Searching~Pair_ID, data=repeat_SAM)
summary(SAM_search_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(SAM_search_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Searching~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.SAM <- data.frame(out.mean, within)
data.SAM$MS=100*(within/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

search.MS.R <-rbind(PK, SAM)


FS.MS.R<-ggplot(search.MS.R, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(),
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(6.06, 10.33), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(7.47, 7.57), linetype="dashed",color = "black", size=0.5)+
	labs(x="Searching",y="Density")

#Travelling
#PK
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Travelling, B = 1000))

#bootstrap within individual variation
PK_travel_aov<- aov(Travelling~Pair_ID, data=repeat_PK)
summary(PK_travel_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(PK_travel_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Travelling~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.PK <- data.frame(out.mean, within)
data.PK$MS=100*(within/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))

#SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Travelling, B = 1000))

#bootstrap within individual variation
SAM_travel_aov<- aov(Travelling~Pair_ID, data=repeat_SAM)
summary(SAM_travel_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(SAM_travel_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Travelling~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.SAM <- data.frame(out.mean, within)
data.SAM$MS=100*(within/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

travel.MS.R <-rbind(PK, SAM)


S.MS.R<-ggplot(travel.MS.R, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				legend.position="none",
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(91.56, 457.18), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(56.29, 161.75), linetype="dashed",color = "black", size=0.5)+
	labs(x="Travelling",y="Density")


#Sociability
#PK
set.seed(1234)
out.mean = with(repeat_PK, boot.mean(Sociability, B = 1000))

#bootstrap within individual variation
PK_soc_aov<- aov(Sociability~Pair_ID, data=repeat_PK)
summary(PK_soc_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(PK_soc_aov)

permuted <- repeat_PK %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Sociability~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.PK <- data.frame(out.mean, within)
data.PK$MS=100*(within/(out.mean^2))
t.test(data.PK$MS,conf.level = 0.95)
quantile(data.PK$MS,c(0.025, 0.975))

#SAM
set.seed(1234)
out.mean = with(repeat_SAM, boot.mean(Sociability, B = 1000))

#bootstrap within individual variation
SAM_soc_aov<- aov(Sociability~Pair_ID, data=repeat_SAM)
summary(SAM_soc_aov)

get_WS <- function(model) {
	anova(model)$`Mean Sq`[2]
}
get_WS(SAM_soc_aov)

permuted <- repeat_SAM %>%
	modelr::permute(1000, Pair_ID) %>% 
	mutate(models = map(perm, ~ aov(Sociability~Pair_ID, data = .))) %>% 
	mutate(within_group_ms = map_dbl(models, get_WS))

#Mean and confidence interval 
within<-as.vector(permuted$within_group_ms)
t.test(within,conf.level = 0.95)

out.mean<-as.vector(out.mean)
within<-as.vector(permuted$within_group_ms)

data.SAM <- data.frame(out.mean, within)
data.SAM$MS=100*(within/(out.mean^2))
t.test(data.SAM$MS,conf.level = 0.95)
quantile(data.SAM$MS,c(0.025, 0.975))

PK<-data.frame(data.PK)
SAM<-data.frame(data.SAM)

PK$Site <- 'HIGH'
SAM$Site <- 'LOW'

Soc.MS.R <-rbind(PK, SAM)


Sociability.MS.R<-ggplot(Soc.MS.R, aes(MS, fill = Site)) + 
	geom_histogram(alpha = 0.7, aes(y = ..density..), position = 'identity')+
	theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
				panel.background = element_blank(), 
				axis.line = element_line(colour = "Black"), 
				axis.title.x = element_text(colour = "Black", face="bold", size=12), 
				axis.title.y = element_text(colour = "Black", face="bold", size=12),
				axis.text.y=element_text(size= 10, colour="Black"),
				axis.text.x = element_text(vjust=0.5, size=10, colour="Black"),
				strip.background = element_rect( fill="White"),  
				strip.text.x = element_text(face="bold", size=9.5))+
	scale_fill_manual(values=c("Black", "Grey45"))+
	geom_vline(xintercept=c(3.08, 4.64), linetype="solid",color = "black", size=0.5)+
	geom_vline(xintercept=c(4.46, 6.92), linetype="dashed",color = "black", size=0.5)+
	labs(x="Sociability",y=NULL)

#combine plots#
Residual_plot<-ggarrange(Aggression.MS.R, Activity_F.MS.R, FS.MS.R, S.MS.R, Sociability.MS.R, nrow=1)
ggsave("Residual_plot.tiff", width=12)

