# Supplementary Material for:
# "Constitutive gene expression differs in three brain regions important 
# for cognition in neophobic and non-neophobic house sparrows (Passer 
# domesticus)"
# Christine R. Lattin, Tosha R. Kelly, Morgan W. Kelly, Kevin M. Johnson
# Cox Proportional Hazard Models & Kaplan-Meier Survival Curves
# using coxme and survminer packages
# Started: 13 April 2020
# Finalized: 15 Sept 2021

# THIS SCRIPT IS TO INVESTIGATE EFFECT OF PHENOTYPE ON NOVEL OBJECT RESPONSE
# AND REPEATABILITY OF THIS RESPONSE
## all subjects included, object trials only

# Notes on data:
## Controls (where included) are not averaged 
## 4 different object trials per bird
## Female HOSPs 106, 108 and 112 are assigned phenotype 3 (neophobic) & 
## Female HOSPs 99, 100 & 110 are assigned phenotype 1 (non-neophobic)
## These were the 6 birds used for RNAseq analysis.
## Neophobic also includes female 103 and males 101, 104, and 111
## Non-neophobic also includes females 102 and 105 and males 98, 107, and 109
## Missing 1 object trial from HOSP 112 
## and 1 object trial from HOSP 102 (video malfunctions) 
## Objects: 0=Control, 1=Keychain, 2=Red dish, 3=Light, 4=Egg, 5=Cover
## Phenotype: 1=not neophobic, 3=neophobic
## Status = 0=Did not feed, 1=Fed
## Object_noobject = 0=control, 1=object

# resources for packages:
## coxme command is from the 'coxme' package - can handle random effects: https://cran.r-project.org/web/packages/coxme/coxme.pdf
### interpretation of cox regression model coefficients:
### http://www.sthda.com/english/wiki/cox-proportional-hazards-model (~ 1/2 way down the page)

#packages
install.packages(c("survival","survminer"))
library("survival") 
library("survminer") 
library("coxme")

#Reset R's brain
rm(list=ls())
#getwd tells you where R is currently looking
getwd()
#setwd tells R where to look
setwd("/Neophobia projects/RNAseq project/R analysis")
#use getwd to confirm that R is now looking there
getwd()
#name the datafile
birds<-read.csv("2018_object_times_for_R_nocontrols.csv")
head(birds)
str(birds)
#make appropriate data types (must all be numeric for survival plots)
birds$ID<-factor(birds$ID)
birds$OBJECT<-factor(birds$OBJECT)
birds$PHENOTYPE<-factor(birds$PHENOTYPE)
birds$TIME<-as.numeric(birds$TIME)
birds$STATUS<-as.numeric(birds$STATUS)
birds$TRIAL<-as.numeric(birds$TRIAL)
birds$SEX<-factor(birds$SEX)

str(birds)

##################
# CHECKING ASSUMPTIONS #
##################
#From: http://www.sthda.com/english/wiki/cox-model-assumptions
#Check Schoenfeld residuals to check the proportional hazards assumption 
#of Cox models
#Do not have continuous covariates, so no need to check Martingale residuals 
#to assess nonlinearity
#Can also check deviance residuals (symmetric transformation of the Martinguale 
#residuals), to examine influential observations
#These tests can only be used for fixed effects, not random effects

#Make a Cox model with fixed effects only
res.cox<-coxph(Surv(TIME,STATUS)~PHENOTYPE+TRIAL+OBJECT,data=birds)
res.cox

#Test the proportional hazards assumption 
#using the function cox.zph() in the survival package
test.ph<-cox.zph(res.cox)
test.ph

#Can also check graphs of the scaled Schoenfeld residuals against the 
#transformed time using ggcoxzph() in the survminer package
ggcoxzph(test.ph)

#To check for influential observations, can visualize the dfbeta values 
#or the deviance residuals
#Using the function ggcoxdiagnostics() in the survminer package: 
ggcoxdiagnostics(res.cox,type="dfbeta", linear.predictions=FALSE, ggtheme=theme_bw())

##################
# PHENOTYPE EFFECTS #
##################
##Full Cox model controlling for individual random effects using coxme package:
cox.sparrow.ID<-coxme(Surv(TIME,STATUS)~PHENOTYPE+TRIAL+OBJECT+(1|ID),data=birds)
cox.sparrow.ID

###Survival plots of feed probability by phenotype####
fit.object<-survfit(Surv(TIME,STATUS)~PHENOTYPE,data=birds)
ggsurvplot(fit.object,
           data=birds,
           size=0.5, #change line size
           palette = c("#0004FF","#FF0008"), #custom colour
           conf.int = TRUE, #add confidence interval
           #conf.int.style = "ribbon", #"ribbon or "step"
           #conf.int.alpha = 0.3, #0 = transparent & 1 = not transparent
           pval=FALSE, #add p-value
           pval.coord=c(2700,0.9), #change position of p-value
           risk.table = TRUE, #add risk table
           risk.table.col = "strata", #risk table colour by groups
           legend.labs = c("Non-neophobic","Neophobic"), #change legend labels
           xlab = "Time (seconds)", #change x-axis label
           ylab = "Proportion yet to feed", #change y-axis label
           break.time.by = 300,
           risk.table.height = 0.3, #useful to change when you have multiple groups
           risk.table.title = "Number yet to feed",
           ggtheme = theme_bw() #change ggplot theme
)

###Assessing the repeatability of novel object responses using ICCs
### INTRACLASS CORRELATION COEFFICIENT ###
# with ICC package
library(ICC)
ICCbareF(birds$ID, birds$TIME, data=birds) 
# same calculation, additional info (lower & upper confidence; n)
ICCest(birds$ID, birds$TIME, data=birds, alpha=0.05, CI.type="THD")
# visualize
plot(birds$TIME~birds$ID)
