#Loading packages
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(lme4)
## Loading required package: Matrix
library(knitr)
library(Matrix)
library(tidyr)
## 
## Attaching package: 'tidyr'
## The following objects are masked from 'package:Matrix':
## 
##     expand, pack, unpack
library(tinytex)
library(reshape2)
## 
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
## 
##     smiths
#Naming datasets
agonistic <- read.csv("Independent Project Data Set.csv")
agonisticsize <- read.csv("Independent Project Size Data Set.csv")
matched <- read.csv("Matched Behaviour.csv")
crossed <- read.csv("Crossed Behaviour.csv")
totalbehaviour <- read.csv("Total Behaviour.csv")
sizedifference <- read.csv("Size Difference.csv")
#SIZE DISTRIBUTION
##Histogram Showing Size Distribution of Male and Female Crayfish
ggplot(data = agonisticsize, aes(x = size, fill = sex)) +
    geom_histogram(bins=7) +
    facet_wrap(~ sex) +
    scale_fill_manual(values = c("bisque2", "bisque4")) + ggtitle("Size Distribution") +
  xlab("Size (mm)") + ylab("Crayfish Count") +
  theme_minimal()+
  theme(strip.text = element_blank())+
  theme(plot.title = element_text(hjust = 0.5),
        axis.line = element_line(color = "black", size = 1))
## Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
## ℹ Please use the `linewidth` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

#BEHAVIOUR DISTRIBUTION
##Histogram Showing Behaviour Distribution of Crayfish in Sex Matched Trials
df <- data.frame(
  behavior = c(-2, -1, 1, 2, 3, 4, 5),
  Female = matched$female,
  Male = matched$male
)

df_long <- melt(df, id.vars = "behavior", variable.name = "Sex", value.name = "Count")

ggplot(df_long, aes(x = factor(behavior), y = Count, fill = Sex)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "MATCHED: Behaviour Distribution", x = "Behavior", y = "Average Count", fill = "Sex") +
  scale_fill_manual(values = c("Female" = "bisque2", "Male" = "bisque4")) +
  facet_wrap(~ Sex, labeller = labeller(Sex = c(Male = "Male Behavior", Female = "Female Behavior"))) + 
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5))

##Histogram Showing Behaviour Distribution of Crayfish in Sex Crossed Trials
df <- data.frame(
  behavior = c(-2, -1, 1, 2, 3, 4, 5),
  Female = crossed$female,
  Male = crossed$male
)

df_long <- melt(df, id.vars = "behavior", variable.name = "Sex", value.name = "Count")

ggplot(df_long, aes(x = factor(behavior), y = Count, fill = Sex)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "CROSSED: Behaviour Distribution", x = "Behavior", y = "Average Count", fill = "Sex") +
  scale_fill_manual(values = c("Female" = "bisque2", "Male" = "bisque4")) +
  facet_wrap(~ Sex, labeller = labeller(Sex = c(Male = "Male Behavior", Female = "Female Behavior"))) + 
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5))

#SCATTERPLOTS

agonistic_crossed <- subset(agonistic, match == "n")
agonistic_matched <- subset(agonistic, match == "y")

##Scatterplot of Crayfish Sex and Size in Relation to Intensity (CROSSED INTERACTIONS)
plot(agonistic_crossed$size, agonistic_crossed$intensity,
     col = ifelse(agonistic_crossed$sex == "female", "bisque2", "bisque4"),
     pch = ifelse(agonistic_crossed$sex == "female", 20, 20),
     main = "CROSSED: Aggression in Relation to Sex and Size",
     xlab = "Size (mm)",
     ylab = "Intensity Score")
legend("topleft", 
       pch = c(20, 20), 
       c("Female Response", "Male Response"), 
       col = c("bisque2", "bisque4")) 

abline(lm(intensity ~ size, data = subset(agonistic_crossed, sex == "female")), col = "bisque2")
abline(lm(intensity ~ size, data = subset(agonistic_crossed, sex == "male")), col = "bisque4")

##Scatterplot of Crayfish Sex and Size in Relation to Intensity (MATCHED INTERACTIONS)
plot(agonistic_matched$size, agonistic_matched$intensity,
     col = ifelse(agonistic_matched$sex == "female", "bisque2", "bisque4"),
     pch = ifelse(agonistic_matched$sex == "female", 20, 20),
     main = "MATCHED: Aggression in Relation to Sex and Size",
     xlab = "Size (mm)",
     ylab = "Intensity Score")
legend("topleft", 
       pch = c(20, 20), 
       c("Female Response", "Male Response"), 
       col = c("bisque2", "bisque4")) 

abline(lm(intensity ~ size, data = subset(agonistic_matched, sex == "female")), col = "bisque2")
abline(lm(intensity ~ size, data = subset(agonistic_matched, sex == "male")), col = "bisque4")

agonistic_crossed1 <- subset(sizedifference, match == "n")
agonistic_matched1 <- subset(sizedifference, match == "y")

##Scatterplot of Crayfish Sex and Size Difference in Relation to Intensity (CROSSED INTERACTIONS)
plot(agonistic_crossed1$size.difference, agonistic_crossed1$intensity,
     col = ifelse(agonistic_crossed1$sex == "female", "bisque2", "bisque4"),
     pch = ifelse(agonistic_crossed1$sex == "female", 20, 20),
     main = "CROSSED: Aggression in Relation to Sex and Size Difference",
     xlab = "Size Difference (mm)",
     ylab = "Intensity Score")
legend("topleft", 
       pch = c(20, 20), 
       c("Female Response", "Male Response"), 
       col = c("bisque2", "bisque4")) 

abline(lm(intensity ~ size.difference, data = subset(agonistic_crossed1, sex == "female")), col = "bisque2")
abline(lm(intensity ~ size.difference, data = subset(agonistic_crossed1, sex == "male")), col = "bisque4")

##Scatterplot of Crayfish Sex and Size Difference in Relation to Intensity (MATCHED INTERACTIONS)
plot(agonistic_matched1$size.difference, agonistic_matched1$intensity,
     col = ifelse(agonistic_matched1$sex == "female", "bisque2", "bisque4"),
     pch = ifelse(agonistic_matched1$sex == "female", 20, 20),
     main = "MATCHED: Aggression in Relation to Sex and Size Difference",
     xlab = "Size Difference (mm)",
     ylab = "Intensity Score")
legend("topleft", 
       pch = c(20, 20), 
       c("Female Response", "Male Response"), 
       col = c("bisque2", "bisque4")) 

abline(lm(intensity ~ size.difference, data = subset(agonistic_matched1, sex == "female")), col = "bisque2")
abline(lm(intensity ~ size.difference, data = subset(agonistic_matched1, sex == "male")), col = "bisque4")

#STATISTICAL TESTING

##Generalized Linear Model for ALL Trials
glm_sexmatchinteraction <- glm(intensity ~ sex + size + size.difference+ match + sex*match, data = agonistic)

summary(glm_sexmatchinteraction)
## 
## Call:
## glm(formula = intensity ~ sex + size + size.difference + match + 
##     sex * match, data = agonistic)
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     -47.6891    23.5800  -2.022  0.04466 *  
## sexmale          37.2699     5.3425   6.976 6.09e-11 ***
## size              1.3614     0.8739   1.558  0.12108    
## size.difference  -0.1516     0.5875  -0.258  0.79666    
## matchy           15.1261     5.4579   2.771  0.00619 ** 
## sexmale:matchy  -21.1823     8.0107  -2.644  0.00894 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 610.9262)
## 
##     Null deviance: 157490  on 179  degrees of freedom
## Residual deviance: 106301  on 174  degrees of freedom
## AIC: 1673.4
## 
## Number of Fisher Scoring iterations: 2
plot(glm_sexmatchinteraction)

##Generalized Linear Model for Matched Trials
glm_matched <- glm(intensity ~ size + size.difference + sex, data = subset(agonistic, match == "y"), family = gaussian)

summary(glm_matched)
## 
## Call:
## glm(formula = intensity ~ size + size.difference + sex, family = gaussian, 
##     data = subset(agonistic, match == "y"))
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)  
## (Intercept)      -44.708     34.944  -1.279   0.2046  
## size               1.840      1.368   1.345   0.1826  
## size.difference    1.517      0.915   1.658   0.1014  
## sexmale           14.853      6.731   2.207   0.0304 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 657.0145)
## 
##     Null deviance: 69374  on 79  degrees of freedom
## Residual deviance: 49933  on 76  degrees of freedom
## AIC: 751.94
## 
## Number of Fisher Scoring iterations: 2
plot(glm_matched)

##Generalized Linear Model for Crossed Trials
glm_crossed <- glm(intensity ~ size + size.difference + sex, data = subset(agonistic, match == "n"), family = gaussian)

summary(glm_crossed)
## 
## Call:
## glm(formula = intensity ~ size + size.difference + sex, family = gaussian, 
##     data = subset(agonistic, match == "n"))
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     -41.7232    27.2752  -1.530    0.129    
## size              0.9871     1.0157   0.972    0.334    
## size.difference  -1.5196     0.6856  -2.216    0.029 *  
## sexmale          45.2943     4.9170   9.212 7.35e-15 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 463.1927)
## 
##     Null deviance: 87202  on 99  degrees of freedom
## Residual deviance: 44467  on 96  degrees of freedom
## AIC: 903.52
## 
## Number of Fisher Scoring iterations: 2
plot(glm_crossed)

##Correlation Testing
##Correlation Testing for Size Difference and Intensity
agonistic2 <- agonistic %>% group_by(day, interaction) %>% filter(size.difference>0)

cor.test(agonistic2$size.difference, agonistic2$intensity, method = "pearson")
## 
##  Pearson's product-moment correlation
## 
## data:  agonistic2$size.difference and agonistic2$intensity
## t = 0.30826, df = 88, p-value = 0.7586
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.1754419  0.2383127
## sample estimates:
##        cor 
## 0.03284243
##Correlation Testing for Size and Intensity
cor.test(agonistic2$size, agonistic2$intensity, method = "pearson")
## 
##  Pearson's product-moment correlation
## 
## data:  agonistic2$size and agonistic2$intensity
## t = 1.5835, df = 88, p-value = 0.1169
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.04209349  0.36109282
## sample estimates:
##       cor 
## 0.1664486
##Correlation Testing for Sex and Intensity
agonistic$sex_numeric <- ifelse(agonistic$sex == "female", 0, 1)
correlation <- cor.test(agonistic$sex_numeric, agonistic$intensity, method = "spearman")
## Warning in cor.test.default(agonistic$sex_numeric, agonistic$intensity, :
## Cannot compute exact p-value with ties
print(correlation)
## 
##  Spearman's rank correlation rho
## 
## data:  agonistic$sex_numeric and agonistic$intensity
## S = 351008, p-value < 2.2e-16
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##     rho 
## 0.63887
##Correlation Testing for Female Behaviour (Matched)
correlationfemalematch <- cor.test(matched$behaviour, matched$female, method = "spearman")
print(correlationfemalematch)
## 
##  Spearman's rank correlation rho
## 
## data:  matched$behaviour and matched$female
## S = 104, p-value = 0.02381
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##        rho 
## -0.8571429
##Correlation Testing for Male Behaviour (Matched)
correlationmalematch <- cor.test(matched$behaviour, matched$male, method = "spearman")
print(correlationmalematch)
## 
##  Spearman's rank correlation rho
## 
## data:  matched$behaviour and matched$male
## S = 84, p-value = 0.2667
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##  rho 
## -0.5
##Correlation Testing for Female Behaviour (Crossed)
correlationfemalecross <- cor.test(crossed$behaviour, crossed$female, method = "spearman")
## Warning in cor.test.default(crossed$behaviour, crossed$female, method =
## "spearman"): Cannot compute exact p-value with ties
print(correlationfemalecross)
## 
##  Spearman's rank correlation rho
## 
## data:  crossed$behaviour and crossed$female
## S = 103.43, p-value = 0.0162
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##        rho 
## -0.8468812
##Correlation Testing for Male Behaviour (Crossed)
correlationmalecross <- cor.test(crossed$behaviour, crossed$male, method = "spearman")
## Warning in cor.test.default(crossed$behaviour, crossed$male, method =
## "spearman"): Cannot compute exact p-value with ties
print(correlationmalecross)
## 
##  Spearman's rank correlation rho
## 
## data:  crossed$behaviour and crossed$male
## S = 38.846, p-value = 0.504
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
##       rho 
## 0.3063187