---
title: "ESM5_Robert_et_al2023_SecondExperimentAnalysis"
author: "Théo Robert, Vivek Nityananda"
date: "2023-09-22"
output: html_document
---

```{r setup, include=FALSE}

rm(list=ls())
library('DHARMa')
library('glmmTMB')
library('dplyr')

#Loading data
df=read.csv("C:\\Users\\nvn6\\OneDrive - Newcastle University\\Documents\\LearningAttentionPaper\\Revision\\beeSearchDataRevised.csv")
propFrames=df$frames/df$visualSearchFrames;
df=cbind(df,propFrames);
df$propFrames=df$propFrames/df$regionArea

#Removing zero values from proportions to enable log transforms for the Second Task data
df_nz = filter_at(df, vars(propFrames), all_vars((.) != 0))
logProp=log(df_nz$propFrames)
df_nz=cbind(df_nz,logProp)

#Specifying factors
df_nz$regionType=factor(df_nz$regionType, levels=c("reward","distractor", "other"))
df_nz$flowerColour=factor(df_nz$flowerColour, levels=c("Yellow", "Blue"))
df_nz$trainingStage=factor(df_nz$trainingStage, levels=c("First Six","Last Six"))
```

```{r analysis, include=TRUE}
#Overall model testing for the effects of location, colour and learning stage - with yellow flowers and the first six choices as the intercept
m_all=glm(logProp~trainingStage*flowerColour*regionType, data=subset(df_nz, experiment == "Second"))
SimOutputMTot_NullSecond=simulateResiduals(fittedModel=m_all, plot = T)
testDispersion(SimOutputMTot_NullSecond)
summary(m_all)

#Reordering and running the model again - with blue flowers and the first six choices as the intercept
df_nz$flowerColour=factor(df_nz$flowerColour, levels=c("Blue","Yellow"))
df_nz$trainingStage=factor(df_nz$trainingStage, levels=c("First Six","Last Six"))
m_all=glm(logProp~trainingStage*flowerColour*regionType, data=subset(df_nz, experiment == "Second"))
summary(m_all)

#Reordering and running the model again - with yellow flowers and the last six choices as the intercept
df_nz$flowerColour=factor(df_nz$flowerColour, levels=c("Yellow", "Blue"))
df_nz$trainingStage=factor(df_nz$trainingStage, levels=c("Last Six", "First Six"))
m_all=glm(logProp~trainingStage*flowerColour*regionType, data=subset(df_nz, experiment == "Second"),weights=regionArea)
summary(m_all)

#Reordering and running the model again- with blue flowers and the last six choices as the intercept
df_nz$flowerColour=factor(df_nz$flowerColour, levels=c("Blue","Yellow"))
df_nz$trainingStage=factor(df_nz$trainingStage, levels=c("Last Six", "First Six"))
m_all=glm(logProp~trainingStage*flowerColour*regionType, data=subset(df_nz, experiment == "Second"),weights=regionArea)
summary(m_all)


```

