# Supplementary R code for:
# Insightful spiders? Pholcus phalangioides  solve a prey capture problem differently across repeated trials
#Madison A. Rittinger*, Ava Mueller, and Rafael L. Rodr?guez
#Behavioral & Molecular Ecology Group, Department of Biological Sciences, University of Wisconsin - Milwaukee, Wisconsin, USA. 
#* Corresponding author; email: ritting2@uwm.edu; ORCID ID: 0000-0001-6326-1572



#running the packages for the below analyses
library("readxl")
library("glmmTMB")
library("car") 
library("multcomp")
library("writexl")
library("tidyverse") 
library("lme4") 
library("tidyr") 


#Importing data for assessing difficulty of the prey capture problems models ##################

        #these data include all 3 treatments and trials in which the spiders failed or successfully solved the problem
        SFdata<-read_xlsx("Problemsolvingms_data.xlsx_FINAL", na= "na", sheet=1)
        
        #correcting the variable types for the following
        SFdata$treat<-as.factor(SFdata$treat)
        SFdata$trial<-as.ordered(SFdata$trial)
        SFdata$success<-as.factor(SFdata$success)


        #sub-setting data so it only includes the spider's first trial 
        difficultdata<-subset(SFdata, success==1| reason=="spider")
        difficultdata<-subset(difficultdata, trial==1)
        
        #subsetting data to only include data from females to ensure males did not interfere with our results
        femearly<-subset(difficultdata, sex=="F")
        

#Assessing difficulty of the prey capture problems###############
        
        #logistic regression with whether the spider solved the treatment problem as the binomial response variable
        failmod <- glmmTMB(data=difficultdata, success ~ treat+sex+tibia, family=binomial (link="logit"))
        Anova(failmod, test="Chisq",  type="III")
        
                #testing if removing males interfered with main result
                femfailmod <- glmmTMB(data=femearly, success ~ treat+tibia, family=binomial (link="logit"))
                Anova(femfailmod, test="Chisq",  type="III")
                
        #post hoc tests between the treatments to determine which were significantly different using Tukey adjustment
        summary(glht(failmod, mcp(treat="Tukey")))

        #visually check residuals 
        res <- resid(failmod) 
        plot(fitted(failmod), res) 
        
        qqnorm(res) 

#Importing data for assessing qualitative and quantitative variation in solutions##############
        
        #these data include trials in which the spider caught the designated number of flies
        d<-read_xlsx("Problemsolvingms_data_FINAL.xlsx", na= "na", sheet=2)
        
        #correcting the variable types for the following
        d$treat<-as.factor(d$treat)
        d$success_number<-as.ordered(d$success_number)
        d$solution<-as.factor(d$solution)
        d$perc_caught<-as.factor(d$perc_caught)
        d$rough_prey_dist<-as.factor(d$rough_prey_dist)
        
        #subsetting data to only include trials for the multiple fly treatments
        sol_data<-subset(d, solution=="i"| solution=="pb"| solution=="g")

        #subsetting data to only include data from females to ensure males did not interfere with our results
        fem<-subset(sol_data, sex =="F")
#Assessing qualitative variation in solutions########################################

        #logistic regression with the type of solution used as the binomial response variable
        slnmod <- glmmTMB(data=sol_data, solution ~ success_number+tibia+flies_caught+rough_prey_dist+
                            (1|id), family=binomial (link="logit")) 
       
         Anova(slnmod, type=3)
        
                #testing if removing males interfered with main result
                Fslnmod <- glmmTMB(data=fem, solution ~ success_number+flies_caught+rough_prey_dist+tibia+
                                    (1|id), family=binomial (link="logit"))
                Anova(Fslnmod, type=3)
        
        #testing if ID matters
        slnmod2 <- glmmTMB(data=sol_data, solution ~ success_number+tibia+flies_caught+rough_prey_dist, family=binomial (link="logit")) 
        anova(slnmod,slnmod2)#ID not sig
        
                #testing if removing males interfered with main result
                Fslnmod2 <- glmmTMB(data=fem, solution ~ success_number+flies_caught+rough_prey_dist+tibia, family=binomial (link="logit"))
                anova(Fslnmod, Fslnmod2)
                
        #visually check residuals 
        res <- resid(slnmod) 
        plot(fitted(slnmod), res) 
        
        qqnorm(res) 
#Which solution is caught the most flies###############
        
        #logistic regression with the percentage of prey caught as the binomial response variable. 
        #Percentage in this context only includes two possible outcomes: spiders could catch 67% of flies (two of three) or 100% of flies (two of two or three of three)
        percmod <- glmmTMB(data=sol_data, perc_caught ~ solution+ 
                             (1|id), family=binomial (link="logit")) 
        Anova(percmod, type=3)
        
        #testing if ID matters
        percmod2 <- glmmTMB(data=sol_data, perc_caught ~ solution, family=binomial (link="logit")) 
        anova(percmod,percmod2)#ID is sig

        
#Does what happened previously affect next solution? ######################################
        
        #subsetting trials in which the spider succeeded either the first or second time only
        onevtwo_data<-subset(sol_data, success_number<=2)
        #reformating data for ease of analysis
        onevtwo_wide<-pivot_wider(data=onevtwo_data, names_from = success_number, 
                                  id_cols=c(id,web_cover,sex,tibia),
                                  values_from = c(solution,perc_caught,temp,endtime))

        #logistic regressions with the type of solution spiders used in the second trial as the response variable
        sln2_mod<-glmmTMB(data=onevtwo_wide, solution_2~endtime_1+perc_caught_1, family=binomial (link="logit"))
        Anova(sln2_mod, type=3)
        
        
        sln2_mod2<-glmmTMB(data=onevtwo_wide, solution_2~solution_1, family=binomial (link="logit"))
        Anova(sln2_mod2)
        
#Assessing quantitative variation in solutions################
       #testing assumption of normality
        shapiro.test(sol_data$endtime)#not normally distributed
        shapiro.test(sqrt(sol_data$endtime))#normally distributed
        
        #adding transformed data back to df
        sol_data$sqrtendtime<-sqrt(sol_data$endtime)
        fem$sqrtendtime<-sqrt(fem$endtime) 
        
        #linear mixed model with the time until the solution as the continuous response variable
        timemod <- lmer(data=sol_data, sqrtendtime ~ success_number+solution+tibia+temp+
                          (1|id)) 
        Anova(timemod, type="3", test.statistic = "F") 
        
                #testing if removing males interfered with main result
                Ftimemod <- lmer(data=fem, sqrtendtime ~ success_number+tibia+temp+solution+
                                  (1|id))
                Anova(Ftimemod, type="3", test.statistic = "F") 
                
        #testing if ID matters
        timemod2 <- lm(data=sol_data, sqrtendtime ~ success_number+tibia+temp+solution) 
        anova(timemod,timemod2)#ID not sig

        #visually check residuals
        res <- resid(timemod) 
        plot(fitted(timemod), res) 
        
        qqnorm(res)        
        
#Testing for trial and error#########################
        
        #generalized linear model with a Poisson distribution and the number of failed trials before the spider solved the problem as the continuous response variable
        TE_mod_all<-glmmTMB(data=d, spfails_before ~ success_number+treat+sex+web_cover+(1|id), family=poisson (link="log"), ziformula = ~1)
        Anova(TE_mod_all, type=3)
        
                #testing if removing males interfered with main result
                fem_TE_mod<-glmmTMB(data=fem, spfails_before ~ treat+success_number+web_cover+(1|id), family=poisson (link="log"), ziformula = ~ 1)
                Anova(fem_TE_mod, type=3)
        
        #post hoc tests between the treatments to determine which treatment spiders failed more in
        summary(glht(TE_mod_all, mcp(treat="Tukey"))) 
        
        #testing if ID matters
        TE_mod2<-glmmTMB(data=d, spfails_before ~ success_number+treat+sex+web_cover,
                         family=poisson (link="log"), ziformula = ~1)
        anova(TE_mod_all,TE_mod2)#ID is sig
        
        #visually check residuals 
        res <- resid(TE_mod_all) 
        plot(fitted(TE_mod_all), res) 
        
        qqnorm(res)        
        