# Supplementary Information - Online Resource 6
# The script used to build the LMMs described in this paper 
# and test the significance of fixed effects.

# Visitation rate, but not foraging range, responds to brood size 
# manipulation in an aerial insectivore 

# Sage A. Madden, Molly T. McDermott, Rebecca J. Safran

# Journal: Behavioral Ecology and Sociobiology

# Affiliations:
# SAM, MTM, RJS: Department of Ecology and Evolutionary Biology, 
# University of Colorado Boulder, Boulder, CO, USA

# SAM: Department of Evolution and Ecology, 
# University of California Davis, Davis, CA, USA


# To whom correspondence should be addressed: Sage A. Madden, University of California Davis, Department of Evolution and Ecology, One Shields Avenue, 2320 Storer Hall, Davis, CA 95616 
# Email: saamadden@ucdavis.edu	
# Phone: 1+(720)-879-4053


###### Barn swallow BSM paper LMMs
###### Created: Fall 2020
###### Last modified: July 24, 2022

# This script contains all of the code necessary to run the linear mixed models 
# used in the analyses of two years of barn swallow parental care and 
# foraging behavior data, as described in the paper named above. 
# The script includes commands to build the models, check diagnostics, and 
# test the significance of fixed effects via F tests with a Kenward-Roger
# approximation (abbreviated KR F tests here). 
# At the end of the script there are commands to generate summary statistics
# and for Wilcoxen Rank Sum tests we used to test for any potentially important
# differences in brood size or hatch date between our randomized treatment 
# groups before our manipulations. 

# Load libraries
library(dplyr)
library(lme4)
library(car)
library(lmerTest)
library(pbkrtest)
library(MuMIn)
library(stringr)
library(lubridate)

#### Clean and reformat data

# Read in the data
# Adult data
mcu <- read.csv("ESM_3.csv")
# Nestling data
nestling <- read.csv("ESM_4.csv")

# Rename mapleton -- folsom and mapleton are very close together and 
# considered a single site 
mcu$site[mcu$site == "Mapleton"] <- "Folsom"
nestling$site[nestling$site == "Mapleton"] <- "Folsom"

# Create treatment column
for(i in 1:length(mcu$band)){
  if(mcu$chick_age[i] == 7 | mcu$chick_age[i] == 8){
    mcu$treatment[i] <- "C"
  } 
  else{
    mcu$treatment[i] <- mcu$bsm[i]
  }
}

# Make sure some variables are factors
mcu$bsm <- as.factor(mcu$bsm)
mcu$treatment <- as.factor(mcu$treatment)
mcu$tag <- as.factor(mcu$tag)
mcu$year <- as.factor(mcu$year)
mcu$fband <- as.factor(mcu$band)
mcu$fsite <- as.factor(mcu$site)
nestling$bsm <- as.factor(nestling$bsm)
nestling$fsite <- as.factor(nestling$site)
nestling$tag <- as.factor(nestling$tag)
nestling$year <- as.factor(nestling$year)

# Remove nests with 1N transferred 
filter(nestling, X2nTransferred == "N")
nestling <- filter(nestling, X2nTransferred == "Y")
mcu <- filter(mcu, band != "2640-97571" & band != "2640-97374")

# Remove Hoops 16 -- gps tag was placed on a male, so drop this
mcu <- filter(mcu, band != "2850-57510")
nestling <- filter(nestling, band != "2850-57510")

# Create subsets of the data for use in certain models and plots
mcugps <- filter(mcu, chick_age == 7 | chick_age == 9)
mcuobs <- filter(mcu, is.na(num_vis_f) == FALSE)


#### Run linear mixed models, F-tests, and model diagnostics

# Remove an outlier where birds could not be sexed reliably during observations
noMB54 <- dplyr::filter(mcuobs, band != "2640-97596")

###########################################################################
# Female visitation rate
## Make linear mixed effects models with different environmental variables
vis_lmer_temp <- lmer(num_vis_f ~ treatment + year + tag + avg_temp_obs +
                        treatment:tag + (1|fband) + (1|fsite), data = noMB54)

vis_lmer_wind <- lmer(num_vis_f ~ treatment + year + tag + avg_windspeed_obs +
                        treatment:tag + (1|fband) + (1|fsite), data = noMB54) 

vis_lmer_precip <- lmer(num_vis_f ~ treatment + year + tag + totalprecip12_obs +
                          treatment:tag + (1|fband) + (1|fsite), data = noMB54) 

vis_lmer_noweath <- lmer(num_vis_f ~ treatment + year + tag + 
                           treatment:tag + (1|fband) + (1|fsite), data = noMB54) 

## Use Kenwood-Roger F tests to decide which environmental variable explains the most 
## variation
KRmodcomp(vis_lmer_temp, vis_lmer_noweath)
KRmodcomp(vis_lmer_wind, vis_lmer_noweath)
KRmodcomp(vis_lmer_precip, vis_lmer_noweath)
# Only temperature explains significant variation in female visitation rate

## Check diagnostics for the full model
plot(vis_lmer_temp)
# Normal QQplot
{qqnorm(resid(vis_lmer_temp))
  qqline(resid(vis_lmer_temp))}
# Histogram of residuals
hist(resid(vis_lmer_temp))
# Checking for influential outliers
infIndexPlot(vis_lmer_temp, vars=c("Cook"))
infIndexPlot(vis_lmer_temp, vars=c("Studentized"))
# Normality test
vis_resid <- residuals(vis_lmer_temp, type = "pearson")
shapiro.test(vis_resid)

## Create model without interaction
vis_lmer_temp_ni <- lmer(num_vis_f ~ treatment + year + tag + avg_temp_obs +
                           (1|fband) + (1|fsite), data = noMB54)

# KR F test for interaction
KRmodcomp(vis_lmer_temp, vis_lmer_temp_ni)
# Interaction is not significant, so remove it from the final model

## KR F tests for significance of other terms
# Treatment
vis_lmer_temp_ntre <- lmer(num_vis_f ~ year + tag + avg_temp_obs +
                           (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(vis_lmer_temp_ni, vis_lmer_temp_ntre)
# Test treatment vs. control
difflsmeans(vis_lmer_temp_ni, test.effs="Treatment", ddf = "Kenward-Roger")

# Tag
vis_lmer_temp_nta <- lmer(num_vis_f ~ year + treatment + avg_temp_obs +
                             (1|fband) + (1|fsite), data = noMB54) #Singular
KRmodcomp(vis_lmer_temp_ni, vis_lmer_temp_nta) 

# Year
vis_lmer_temp_ny <- lmer(num_vis_f ~ treatment + tag + avg_temp_obs +
                             (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(vis_lmer_temp_ni, vis_lmer_temp_ny)

# Temp
vis_lmer_temp_nte <- lmer(num_vis_f ~ year + tag + treatment +
                             (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(vis_lmer_temp_ni, vis_lmer_temp_nte)

## Get coefficients, SE, etc. and R-squared for final model excluding
## non-significant interaction 
summary(vis_lmer_temp_ni)
r.squaredGLMM(vis_lmer_temp_ni)


#############################################################################
# Female per capita visitation rate 
## Make linear mixed effects models with different environmental variables
vispn_lmer_temp <- lmer(num_vis_pn ~ treatment + tag + year + avg_temp_obs +
                          treatment:tag + (1|fband) + (1|fsite), data = noMB54)

vispn_lmer_wind <- lmer(num_vis_pn ~ treatment + tag + year + avg_windspeed_obs +
                          treatment:tag + (1|fband) + (1|fsite), data = noMB54)

vispn_lmer_precip <- lmer(num_vis_pn ~ treatment + tag + year + totalprecip12_obs +
                          treatment:tag + (1|fband) + (1|fsite), data = noMB54)

vispn_lmer_noweath <- lmer(num_vis_pn ~ treatment + year + tag + 
                           treatment:tag + (1|fband) + (1|fsite), data = noMB54)
# All singular -- very little variation explained by site

## Use KR F tests to decide which environmental variable explains the most 
## variation
KRmodcomp(vispn_lmer_temp, vispn_lmer_noweath)
KRmodcomp(vispn_lmer_wind, vispn_lmer_noweath)
KRmodcomp(vispn_lmer_precip, vispn_lmer_noweath)
# Only temperature explains significant variation in female per capita 
# visitation rate

## Check diagnostics for full model
plot(vispn_lmer_temp)
# Normal QQplot
{qqnorm(resid(vispn_lmer_temp))
  qqline(resid(vispn_lmer_temp))}
# Histogram of residuals
hist(resid(vispn_lmer_temp))
# Checking for influential outliers
infIndexPlot(vispn_lmer_temp, vars=c("Cook"))
infIndexPlot(vispn_lmer_temp, vars=c("Studentized"))
# Normality test
vispn_resid <- residuals(vispn_lmer_temp, type = "pearson")
shapiro.test(vispn_resid)

## Create model without interaction
vispn_lmer_temp_ni <- lmer(num_vis_pn ~ treatment + tag + year + avg_temp_obs 
                           + (1|fband) + (1|fsite), data = noMB54) #Singular

## KR test for interaction
KRmodcomp(vispn_lmer_temp, vispn_lmer_temp_ni)
# Interaction is not significant, so remove it from the final model

## KR tests for significance of other terms
# Treatment
vispn_lmer_temp_ntre <- lmer(num_vis_pn ~ year + tag + avg_temp_obs +
                             (1|fband) + (1|fsite), data = noMB54) #Singular
KRmodcomp(vispn_lmer_temp_ni, vispn_lmer_temp_ntre)

# Tag
vispn_lmer_temp_nta <- lmer(num_vis_pn ~ year + treatment + avg_temp_obs +
                            (1|fband) + (1|fsite), data = noMB54) # Singular
KRmodcomp(vispn_lmer_temp_ni, vispn_lmer_temp_nta)

# Year
vispn_lmer_temp_ny <- lmer(num_vis_pn ~ treatment + tag + avg_temp_obs +
                           (1|fband) + (1|fsite), data = noMB54) # Singular
KRmodcomp(vispn_lmer_temp_ni, vispn_lmer_temp_ny)

# Temp
vispn_lmer_temp_nte <- lmer(num_vis_pn ~ year + tag + treatment +
                            (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(vispn_lmer_temp_ni, vispn_lmer_temp_nte)

## Get coefficients, SE, etc. and R-squared for final model excluding
## non-significant interaction 
summary(vispn_lmer_temp_ni)
r.squaredGLMM(vispn_lmer_temp_ni)


###############################################################################
# Male visitation rate
## Make linear mixed effects models with different environmental variables
mvis_lmer_temp <- lmer(num_vis_m ~ treatment + year + tag + avg_temp_obs +
                        treatment:tag + (1|fband) + (1|fsite), data = noMB54)

mvis_lmer_wind <- lmer(num_vis_m ~ treatment + year + tag + avg_windspeed_obs +
                        treatment:tag + (1|fband) + (1|fsite), data = noMB54)

mvis_lmer_precip <- lmer(num_vis_m ~ treatment + year + tag + totalprecip12_obs +
                          treatment:tag + (1|fband) + (1|fsite), data = noMB54)

mvis_lmer_noweath <- lmer(num_vis_m ~ treatment + year + tag + 
                             treatment:tag + (1|fband) + (1|fsite), data = noMB54)

## Use KR F tests tests to decide which environmental variable explains the most 
## variation
KRmodcomp(mvis_lmer_temp, mvis_lmer_noweath)
KRmodcomp(mvis_lmer_wind, mvis_lmer_noweath)
KRmodcomp(mvis_lmer_precip, mvis_lmer_noweath)
# Only temperature explains significant variation in male visitation rate

## Check diagnostics for full model
plot(mvis_lmer_temp)
# Normal QQplot
{qqnorm(resid(mvis_lmer_temp))
  qqline(resid(mvis_lmer_temp))}
# Histogram of residuals
hist(resid(mvis_lmer_temp))
# Checking for influential outliers
infIndexPlot(mvis_lmer_temp, vars=c("Cook"))
infIndexPlot(mvis_lmer_temp, vars=c("Studentized"))
# Normality test
vis_resid <- residuals(mvis_lmer_temp, type = "pearson")
shapiro.test(vis_resid)

## Create model without interaction
mvis_lmer_temp_ni <- lmer(num_vis_m ~ treatment + year + tag + avg_temp_obs +
                         (1|fband) + (1|fsite), data = noMB54)

## KR F test for interaction
KRmodcomp(mvis_lmer_temp, mvis_lmer_temp_ni)
# Interaction is not significant, so remove it from the final model

## KR F tests for significance of other terms
# Treatment
mvis_lmer_temp_ntre <- lmer(num_vis_m ~ year + tag + avg_temp_obs +
                               (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvis_lmer_temp_ni, mvis_lmer_temp_ntre)
# Test treatment vs. control
difflsmeans(mvis_lmer_temp_ni, test.effs = "Treatment", ddf = "Kenward-Roger")

# Tag
mvis_lmer_temp_nta <- lmer(num_vis_m ~ year + treatment + avg_temp_obs +
                              (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvis_lmer_temp_ni, mvis_lmer_temp_nta)

# Year
mvis_lmer_temp_ny <- lmer(num_vis_m ~ treatment + tag + avg_temp_obs +
                             (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvis_lmer_temp_ni, mvis_lmer_temp_ny)

# Temp
mvis_lmer_temp_nte <- lmer(num_vis_m ~ year + tag + treatment +
                              (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvis_lmer_temp_ni, mvis_lmer_temp_nte)

## Get coefficients, SE, etc. and R-squared for final model excluding
## non-significant interaction 
summary(mvis_lmer_temp_ni)
r.squaredGLMM(mvis_lmer_temp_ni)


##############################################################################
# Male per capita feeding rate
## Make linear mixed effects models with different environmental variables
mvispn_lmer_temp <- lmer(num_vis_pn_m ~ treatment + year + tag + avg_temp_obs +
                           treatment:tag + (1|fband) + (1|fsite), data = noMB54)

mvispn_lmer_wind <- lmer(num_vis_pn_m ~ treatment + year + tag + avg_windspeed_obs +
                           treatment:tag + (1|fband) + (1|fsite), data = noMB54)

mvispn_lmer_precip <- lmer(num_vis_pn_m ~ treatment + year + tag + totalprecip12_obs +
                           treatment:tag + (1|fband) + (1|fsite), data = noMB54)

mvispn_lmer_noweath <- lmer(num_vis_pn_m ~ treatment + year + tag + 
                            treatment:tag + (1|fband) + (1|fsite), data = noMB54)

## Use KR F tests to decide which environmental variable explains the most 
## variation
KRmodcomp(mvispn_lmer_temp, mvispn_lmer_noweath)
KRmodcomp(mvispn_lmer_wind, mvispn_lmer_noweath)
KRmodcomp(mvispn_lmer_precip, mvispn_lmer_noweath)
# Only temperature explains significant variation in male per capita visitation rate

## Check diagnostics for full model
plot(mvispn_lmer_temp)
# Normal QQplot
{qqnorm(resid(mvispn_lmer_temp))
  qqline(resid(mvispn_lmer_temp))}
# Histogram of residuals
hist(resid(mvispn_lmer_temp))
# Checking for influential outliers
infIndexPlot(mvispn_lmer_temp, vars=c("Cook"))
infIndexPlot(mvispn_lmer_temp, vars=c("Studentized"))
# Normality test
vis_resid <- residuals(mvispn_lmer_temp, type = "pearson")
shapiro.test(vis_resid)

## Create model without interaction
mvispn_lmer_temp_ni <- lmer(num_vis_pn_m ~ treatment + year + tag + avg_temp_obs +
                              (1|fband) + (1|fsite), data = noMB54)
## KR F test for interaction
KRmodcomp(mvispn_lmer_temp, mvis_lmer_temp_ni)
# Interaction is not significant, so remove it from the final model

## KR F tests for significance of other terms
# Treatment
mvispn_lmer_temp_ntre <- lmer(num_vis_pn_m ~ year + tag + avg_temp_obs +
                              (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvispn_lmer_temp_ni, mvispn_lmer_temp_ntre)

# Tag
mvispn_lmer_temp_nta <- lmer(num_vis_pn_m ~ year + treatment + avg_temp_obs +
                             (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvispn_lmer_temp_ni, mvispn_lmer_temp_nta)

# Year
mvispn_lmer_temp_ny <- lmer(num_vis_pn_m ~ treatment + tag + avg_temp_obs +
                            (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvispn_lmer_temp_ni, mvispn_lmer_temp_ny)

# Temp
mvispn_lmer_temp_nte <- lmer(num_vis_pn_m ~ year + tag + treatment +
                             (1|fband) + (1|fsite), data = noMB54)
KRmodcomp(mvispn_lmer_temp_ni, mvispn_lmer_temp_nte)

## Get coefficients, SE, etc. and R-squared for final model excluding
## non-significant interaction 
summary(mvispn_lmer_temp_ni)
r.squaredGLMM(mvispn_lmer_temp_ni)


###############################################################################
# Foraging range area
## Make linear mixed effects models with different environmental variables
for_lmer_temp <- lmer(log(foraging_area100) ~ treatment + year + avg_temp_gps_BA
                        + (1|fband) + (1|fsite), data = mcugps)

for_lmer_wind <- lmer(log(foraging_area100) ~ treatment + year + avg_windspeed_gps_BA 
                      + (1|fband) + (1|fsite), data = mcugps)

for_lmer_precip <- lmer(log(foraging_area100) ~ treatment + year + totalprecip12_gps_BA
                      + (1|fband) + (1|fsite), data = mcugps)

for_lmer_noweath <- lmer(log(foraging_area100) ~ treatment + year 
                          + (1|fband) + (1|fsite), data = mcugps)

## Use KR tests to decide which environmental variable explains the most 
## variation
KRmodcomp(for_lmer_temp, for_lmer_noweath)
KRmodcomp(for_lmer_wind, for_lmer_noweath)
KRmodcomp(for_lmer_precip, for_lmer_noweath)
# No weather variables explain significant variation in foraging range area

## Check diagnostics for full model
plot(for_lmer_noweath)
# Normal QQplot
{qqnorm(resid(for_lmer_noweath))
  qqline(resid(for_lmer_noweath))}
# Histogram of residuals
hist(resid(for_lmer_noweath))
# Checking for influential outliers
infIndexPlot(for_lmer_noweath, vars=c("Cook"))
infIndexPlot(for_lmer_noweath, vars=c("Studentized"))
# Normality test
for_resid <- residuals(for_lmer_noweath, type = "pearson")
shapiro.test(for_resid)

## Remove outlier
noM4 <- mcugps[-19,]
## Create model without outlier
for_lmer_noweath_no <- lmer(log(foraging_area100) ~ treatment + year 
                         + (1|fband) + (1|fsite), data = noM4)

## Check diagnostics with outlier removed
plot(for_lmer_noweath_no)
# Normal QQplot
{qqnorm(resid(for_lmer_noweath_no))
  qqline(resid(for_lmer_noweath_no))}
# Histogram of residuals
hist(resid(for_lmer_noweath_no))
# Checking for influential outliers
infIndexPlot(for_lmer_noweath_no, vars=c("Cook"))
infIndexPlot(for_lmer_noweath_no, vars=c("Studentized"))
# Normality test
for_resid <- residuals(for_lmer_noweath_no, type = "pearson")
shapiro.test(for_resid)

## KR F tests for significance of other terms
# Treatment
# With outlier
for_lmer_ntre <- lmer(log(foraging_area100) ~ year 
                           + (1|fband) + (1|fsite), data = mcugps)
KRmodcomp(for_lmer_noweath, for_lmer_ntre)
# Without
for_lmer_ntre_no <- lmer(log(foraging_area100) ~ year 
                          + (1|fband) + (1|fsite), data = noM4)
KRmodcomp(for_lmer_noweath_no, for_lmer_ntre_no)

# Year
# With outlier
for_lmer_ny <- lmer(log(foraging_area100) ~ treatment 
                           + (1|fband) + (1|fsite), data = mcugps)
KRmodcomp(for_lmer_noweath, for_lmer_ny)
# Without
for_lmer_ny_no <- lmer(log(foraging_area100) ~ treatment 
                    + (1|fband) + (1|fsite), data = noM4)
KRmodcomp(for_lmer_noweath_no, for_lmer_ny_no)

## Get coefficients, SE, etc. and R-squared for final model excluding
## non-significant interaction 
summary(for_lmer_noweath_no)
r.squaredGLMM(for_lmer_noweath_no)

# With outlier
summary(for_lmer_noweath)
r.squaredGLMM(for_lmer_noweath)

###############################################################################
# Average distance from the nest
## Make linear mixed effects models with different environmental variables
forDis_lmer_temp <- lmer(log(avg_dis) ~ treatment + year + avg_temp_gps
                      + (1|fband) + (1|fsite), data = mcu)

forDis_lmer_wind <- lmer(log(avg_dis) ~ treatment + year + avg_windspeed_gps 
                      + (1|fband) + (1|fsite), data = mcu)

forDis_lmer_precip <- lmer(log(avg_dis) ~ treatment + year + totalprecip12_gps
                        + (1|fband) + (1|fsite), data = mcu)

forDis_lmer_noweath <- lmer(log(avg_dis) ~ treatment + year 
                         + (1|fband) + (1|fsite), data = mcu)


## Use KR F tests to decide which environmental variable explains the most 
## variation
KRmodcomp(forDis_lmer_temp, forDis_lmer_noweath)
KRmodcomp(forDis_lmer_wind, forDis_lmer_noweath)
KRmodcomp(forDis_lmer_precip, forDis_lmer_noweath)
# No weather variables explain significant variation 

## Check diagnostics for full model
plot(forDis_lmer_precip)
# Normal QQplot
{qqnorm(resid(forDis_lmer_precip))
  qqline(resid(forDis_lmer_precip))}
# Histogram of residuals
hist(resid(forDis_lmer_precip))
# Checking for influential outliers
infIndexPlot(forDis_lmer_precip, vars=c("Cook"))
infIndexPlot(forDis_lmer_precip, vars=c("Studentized"))
# Normality test
for_resid <- residuals(forDis_lmer_precip, type = "pearson")
shapiro.test(for_resid)

## Remove outlier
noM4 <- mcu[-c(37,38), ]
## Removing both because 38 has a studentized resid above 3 once 37 is removed 
## and there are issues with normality

## Create model with no outlier
forDis_lmer_noweath_no <- lmer(log(avg_dis) ~ treatment + year
                            + (1|fband) + (1|fsite), data = noM4) #Singular

## Check diagnostics with outlier removed
plot(forDis_lmer_noweath_no)
# Normal QQplot
{qqnorm(resid(forDis_lmer_noweath_no))
  qqline(resid(forDis_lmer_noweath_no))}
# Histogram of residuals
hist(resid(forDis_lmer_noweath_no))
# Checking for influential outliers
infIndexPlot(forDis_lmer_noweath_no, vars=c("Cook"))
infIndexPlot(forDis_lmer_noweath_no, vars=c("Studentized"))
# Normality test
for_resid <- residuals(forDis_lmer_noweath_no, type = "pearson")
shapiro.test(for_resid)

## KR F tests for significance of other terms
# Treatment
# With outlier
forDis_lmer_ntre <- lmer(log(avg_dis) ~ year 
                      + (1|fband) + (1|fsite), data = mcu)
KRmodcomp(forDis_lmer_noweath, forDis_lmer_ntre)
# Without
forDis_lmer_ntre_no <- lmer(log(avg_dis) ~ year 
                         + (1|fband) + (1|fsite), data = noM4)
KRmodcomp(forDis_lmer_noweath_no, forDis_lmer_ntre_no)

# Year
# With
forDis_lmer_ny <- lmer(log(avg_dis) ~ treatment 
                    + (1|fband) + (1|fsite), data = mcu) 
KRmodcomp(forDis_lmer_noweath, forDis_lmer_ny)
# Without
forDis_lmer_ny_no <- lmer(log(avg_dis) ~ treatment 
                       + (1|fband) + (1|fsite), data = noM4)
KRmodcomp(forDis_lmer_noweath_no, forDis_lmer_ny_no)

## Get coefficients, SE, etc. for final model excluding
## non-significant interaction 
summary(forDis_lmer_noweath_no)
r.squaredGLMM(forDis_lmer_noweath_no)



##############################################################################
# Maximum distance traveled from the nest
## Make linear mixed effects models with different environmental variables
forDisM_lmer_temp <- lmer(log(max_dis) ~ treatment + year + avg_temp_gps
                         + (1|fband) + (1|fsite), data = mcu)

forDisM_lmer_wind <- lmer(log(max_dis) ~ treatment + year + avg_windspeed_gps 
                         + (1|fband) + (1|fsite), data = mcu)

forDisM_lmer_precip <- lmer(log(max_dis) ~ treatment + year + totalprecip12_gps
                           + (1|fband) + (1|fsite), data = mcu)

forDisM_lmer_noweath <- lmer(log(max_dis) ~ treatment + year 
                            + (1|fband) + (1|fsite), data = mcu)


## Use LR tests to decide which environmental variable explains the most 
## variation
KRmodcomp(forDisM_lmer_temp, forDisM_lmer_noweath)
KRmodcomp(forDisM_lmer_wind, forDisM_lmer_noweath)
KRmodcomp(forDisM_lmer_precip, forDisM_lmer_noweath)
# No weather variables explain significant variation

#Check diagnostics for full model
plot(forDisM_lmer_noweath)
#Normal QQplot
{qqnorm(resid(forDisM_lmer_noweath))
  qqline(resid(forDisM_lmer_noweath))}
#Histogram of residuals
hist(resid(forDisM_lmer_noweath))
#Checking for influential outliers
infIndexPlot(forDisM_lmer_noweath, vars=c("Cook"))
infIndexPlot(forDisM_lmer_noweath, vars=c("Studentized"))
#Normality test
for_resid <- residuals(forDisM_lmer_noweath, type = "pearson")
shapiro.test(for_resid)


## KR F tests for significance of other terms
# Treatment
forDisM_lmer_ntre <- lmer(log(max_dis) ~ year 
                         + (1|fband) + (1|fsite), data = mcu)
KRmodcomp(forDisM_lmer_noweath, forDisM_lmer_ntre)

# Year
forDisM_lmer_ny <- lmer(log(max_dis) ~ treatment 
                       + (1|fband) + (1|fsite), data = mcu) 
KRmodcomp(forDisM_lmer_noweath, forDisM_lmer_ny)

## Get coefficients, SE, etc. for final model excluding
## non-significant interaction 
summary(forDisM_lmer_noweath)
r.squaredGLMM(forDisM_lmer_noweath)

###############################################################################
# Nestling growth from days 8 to 12
# Include only nests where all survived and remove the nest where the male
# was GPS tagged
nestlingF <- filter(nestling, all_survived == "Y" & band != "2850-57510")
str(nestlingF)

# Remove reduced nests with 1N transferred
nestlingF <- filter(nestlingF, X2nTransferred == "Y")

## Make linear mixed effects models with different environmental variables
pn_growth_lmer_temp <- lmer(mass8to12_pn ~ bsm + tag + year + avg_temp_nestl + 
                              bsm:tag + (1|fsite),
                            data = nestlingF) #Singular
pn_growth_lmer_wind <- lmer(mass8to12_pn ~ bsm + tag + year + avg_windspeed_nestl + 
                              bsm:tag +  (1|fsite),
                            data = nestlingF) #Singular
pn_growth_lmer_precip <- lmer(mass8to12_pn ~ bsm + tag + year + totalprecip_nestl + 
                                bsm:tag +  (1|fsite),
                              data = nestlingF) #Singular
pn_growth_lmer_noweath <- lmer(mass8to12_pn ~ bsm + tag + year +  
                                 bsm:tag + (1|fsite),
                              data = nestlingF) #Singular

## Use KR F tests to decide which environmental variable explains the most 
## variation
KRmodcomp(pn_growth_lmer_temp, pn_growth_lmer_noweath)
KRmodcomp(pn_growth_lmer_wind, pn_growth_lmer_noweath)
KRmodcomp(pn_growth_lmer_precip, pn_growth_lmer_noweath)
# No weather variables explain significant variation 

## Check diagnostics for full model
plot(pn_growth_lmer_noweath)
# Normal QQplot
{qqnorm(resid(pn_growth_lmer_noweath))
  qqline(resid(pn_growth_lmer_noweath))}
# Histogram of residuals
hist(resid(pn_growth_lmer_noweath))
# Checking for influential outliers
infIndexPlot(pn_growth_lmer_noweath, vars=c("Cook"))
infIndexPlot(pn_growth_lmer_noweath, vars=c("Studentized"))
# Normality test
vis_resid <- residuals(pn_growth_lmer_noweath, type = "pearson")
shapiro.test(vis_resid)

## Create model without an interaction
pn_growth_lmer_noweath_ni <- lmer(mass8to12_pn ~ bsm + tag + year +(1|fsite),
                                  data = nestlingF)

# KR F test for the interaction
KRmodcomp(pn_growth_lmer_noweath, pn_growth_lmer_noweath_ni)

# KR tests for other terms
# Treatment
pn_growth_lmer_ntr <- lmer(mass8to12_pn ~ tag + year + (1|fsite),
                           data = nestlingF) #Singular
KRmodcomp(pn_growth_lmer_noweath, pn_growth_lmer_ntr)

# Tag
pn_growth_lmer_nta <- lmer(mass8to12_pn ~ bsm + year + (1|fsite),
                           data = nestlingF) #Singular
KRmodcomp(pn_growth_lmer_noweath, pn_growth_lmer_nta)

# Year
pn_growth_lmer_ny <- lmer(mass8to12_pn ~ tag + bsm + (1|fsite),
                           data = nestlingF) #Singular
KRmodcomp(pn_growth_lmer_noweath, pn_growth_lmer_ny)

## Get coefficients, SE, etc. and R-squared for final model excluding
## non-significant interaction 
summary(pn_growth_lmer_noweath)
r.squaredGLMM(pn_growth_lmer_noweath)


###########################################################################
## Summary stats AND
## Wilcox tests for differences between hatch date and pre-manipulation
## brood size across treatment groups and study years

## Summary stats for response variables
# Female visitation rate 
# Total
aggregate(num_vis_f ~ treatment * tag, FUN = mean, data = noMB54)
aggregate(num_vis_f ~ treatment * tag, FUN = sd, data = noMB54)
# Per nestling
aggregate(num_vis_pn ~ treatment * tag, FUN = mean, data = noMB54)
aggregate(num_vis_pn ~ treatment * tag, FUN = sd, data = noMB54)

# Male visitation rate
# Total
aggregate(num_vis_m ~ treatment * tag, FUN = mean, data = noMB54)
aggregate(num_vis_m ~ treatment * tag, FUN = sd, data = noMB54)
# Per nestling
aggregate(num_vis_pn_m ~ treatment * tag, FUN = mean, data = noMB54)
aggregate(num_vis_pn_m ~ treatment * tag, FUN = sd, data = noMB54)

# Female foraging range area
aggregate(foraging_area100 ~ treatment, FUN = mean, data = noM4)
aggregate(foraging_area100 ~ treatment, FUN = sd, data = noM4)

# Nestling growth post-BSM
aggregate(mass8to12_pn ~ bsm * tag, FUN = mean, data = nestlingF)
aggregate(mass8to12_pn ~ bsm * tag, FUN = sd, data = nestlingF)


## Comparing brood size before and after manipulation
# Brood size before and after manipulation
aggregate(chick_num ~ bsm * time, FUN = mean, data = mcuobs)
aggregate(chick_num ~ bsm * time, FUN = sd, data = mcuobs)

## Looking at brood size before manipulation by treatment
# Brood size before manipulation for the nestling growth dataset
aggregate(preBSM_chick_num ~ bsm, FUN = mean, data = nestlingF)
aggregate(preBSM_chick_num ~ bsm, FUN = sd, data = nestlingF)

# Brood size before manipulation by BSM and tag treatment
before <- filter(noMB54, chick_age == 8)
before$treatGrp <- paste(before$bsm, before$tag, sep = "_")
aggregate(chick_num ~ treatGrp, FUN = mean, data = before)
aggregate(chick_num ~ treatGrp, FUN = sd, data = before)

beforeE <- filter(before, bsm == "E")
beforeR <- filter(before, bsm == "R")
beforeT <- filter(before, tag == "Y")
beforeNT <- filter(before, tag == "N")

TbeforeE <- filter(beforeE, tag == "Y")
TbeforeR <- filter(beforeR, tag == "Y")


## Wilcox rank sum tests comparing brood size before BSM treatment
## between treatment groups for different datasets
# Wilcoxon rank sum comparing pre-manipulation brood size by BSM treatment and 
# tag treatment for the behavioral obs dataset
wilcox.test(x = beforeE$chick_num, y = beforeR$chick_num)
wilcox.test(x = beforeT$chick_num, y = beforeNT$chick_num)

# Brood size by BSM treatment for tagged birds only
beforeTag <- filter(noM4, chick_age == 7 & tag == "Y")
aggregate(chick_num ~ bsm, FUN = mean, data = beforeT)
aggregate(chick_num ~ bsm, FUN = sd, data = beforeT)

# Wilcoxon rank sum comparing pre-manipulation brood size by BSM treatment for 
# the GPS tag dataset
wilcox.test(x = TbeforeE$chick_num, y = TbeforeR$chick_num)

# Nestling growth by BSM and tag treatment
nestling$treatGrp <- paste(nestling$bsm, nestling$tag, sep = "_")
aggregate(preBSM_chick_num ~ treatGrp, FUN = mean, data = nestling)
aggregate(preBSM_chick_num ~ treatGrp, FUN = sd, data = nestling)

nE <- filter(nestling, bsm == "E")
nR <- filter(nestling, bsm == "R")
nT <- filter(nestling, tag == "Y")
nNT <- filter(nestling, tag == "N")

# Wilcoxon rank sum comparing pre-manipulation brood size by BSM treatment  
# and tag treatment for the nestling growth dataset
wilcox.test(nE$preBSM_chick_num, nR$preBSM_chick_num)
wilcox.test(nT$preBSM_chick_num, nNT$preBSM_chick_num)


## Calculating hatch date as days since June 1
# Get dates into the format I want
before$hatch_date <- mdy(before$hatch_date)
before$hatch_date <- as.character(before$hatch_date)

beforeTag$hatch_date <- mdy(beforeTag$hatch_date)
beforeTag$hatch_date <- as.character(beforeTag$hatch_date)

nestling$hatch_date <- mdy(nestling$hatch_date)
nestling$hatch_date <- as.character(nestling$hatch_date)

# Function to convert dates into days since June 1
DaysOfSummer <- function(hatch) {
  splitDate <- str_split(hatch, "-")
  splitDate <- unlist(splitDate)
  day <- as.numeric(splitDate[3])
  month <- as.numeric(splitDate[2])
  if(month == 6){
    dos <- day
  }
  else{
    dos <- day + 30
  }
  return(as.character(dos))
}

# Run function to get days since June 1 for each dataset
for(i in 1:length(before$hatch_date)){
  before$daysOfSum[i] <- DaysOfSummer(before$hatch_date[i])
}


for(i in 1:length(beforeTag$hatch_date)){
  beforeTag$daysOfSum[i] <- DaysOfSummer(beforeTag$hatch_date[i])
}

for(i in 1:length(nestling$hatch_date)){
  nestling$daysOfSum[i] <- DaysOfSummer(nestling$hatch_date[i])
}

## Calculate summary statistics for hatch date by BSM treatment and tag
aggregate(as.numeric(daysOfSum) ~ bsm * tag, FUN = mean, data = before)
aggregate(as.numeric(daysOfSum) ~ bsm * tag, FUN = sd, data = before)

aggregate(as.numeric(daysOfSum) ~ bsm * tag, FUN = mean, data = nestling)
aggregate(as.numeric(daysOfSum) ~ bsm * tag, FUN = sd, data = nestling)

aggregate(as.numeric(daysOfSum) ~ bsm, FUN = mean, data = beforeTag)
aggregate(as.numeric(daysOfSum) ~ bsm, FUN = sd, data = beforeTag)


## Wilcoxon rank sum tests comparing hatch date between treatment groups 
## for different data sets
# Create new data sets for wilcox tests
dBeforeE <- filter(before, bsm == "E")
dBeforeR <- filter(before, bsm == "R")
dBeforeT <- filter(before, tag == "Y")
dBeforeNT <- filter(before, tag == "N")

dBeforeET <- filter(dBeforeT, bsm == "E")
dBeforeRT <- filter(dBeforeT, bsm == "R")

dnE <- filter(nestling, bsm == "E")
dnR <- filter(nestling, bsm == "R")
dnT <- filter(nestling, tag == "Y")
dnNT <- filter(nestling, tag == "N")

# Wilcoxon tests comparing hatch date across BSM and tag treatments for the 
# behavioral obs dataset
wilcox.test(as.numeric(dBeforeE$daysOfSum), as.numeric(dBeforeR$daysOfSum))
wilcox.test(as.numeric(dBeforeT$daysOfSum), as.numeric(dBeforeNT$daysOfSum))

# Wilcoxon tests comparing hatch date across BSM and tag treatments for the 
# nestling growth data set
wilcox.test(as.numeric(dnE$daysOfSum), as.numeric(dnR$daysOfSum))
wilcox.test(as.numeric(dnT$daysOfSum), as.numeric(dnNT$daysOfSum))

# Wilcoxon tests comparing hatch date across BSM treatments for the 
# GPS tag dataset
wilcox.test(as.numeric(dBeforeET$daysOfSum), as.numeric(dBeforeRT$daysOfSum))

## Wilcoxon rank sum tests comparing brood size and hatch date between
## study years for different data sets 
# New data sets to compare brood size and hatch dates across year
before2019 <- filter(before, year == "2019")
before2020 <- filter(before, year == "2020")

beforeT2019 <- filter(dBeforeT, year == "2019")
beforeT2020 <- filter(dBeforeT, year == "2020")

nestling2019 <- filter(nestling, year == "2019")
nestling2020 <- filter(nestling, year == "2020")

# Wilcoxon test to compare brood size in 2019 and 2020 for the 
# behavioral obs dataset
wilcox.test(before2019$chick_num, before2020$chick_num)

# Summary stats for brood size by year
aggregate(chick_num ~ year, FUN = mean, data = before)
aggregate(chick_num ~ year, FUN = sd, data = before)

# Wilcoxon test to compare hatch date in 2019 and 2020 for the 
# behavioral obs dataset
wilcox.test(as.numeric(before2019$daysOfSum), as.numeric(before2020$daysOfSum))

# Summary stats for hatch date by year
aggregate(as.numeric(daysOfSum) ~ year, FUN = mean, data = before)
aggregate(as.numeric(daysOfSum) ~ year, FUN = sd, data = before)

# Wilcoxon test to compare brood size in 2019 and 2020 for the 
# GPS tag dataset
wilcox.test(beforeT2019$chick_num, beforeT2020$chick_num)

# Summary stats for brood size by year for the GPS tag dataset
aggregate(chick_num ~ year, FUN = mean, data = beforeT)
aggregate(chick_num ~ year, FUN = sd, data = beforeT)

# Wilcoxon test to compare hatch date in 2019 and 2020 for the 
# GPS tag dataset
wilcox.test(as.numeric(beforeT2019$daysOfSum), as.numeric(beforeT2020$daysOfSum))

# Summary stats for hatch date by year for the GPS tag dataset
aggregate(as.numeric(daysOfSum) ~ year, FUN = mean, data = dBeforeT)
aggregate(as.numeric(daysOfSum) ~ year, FUN = sd, data = dBeforeT)

# Wilcoxon test to compare brood size in 2019 and 2020 for the 
# nestling dataset
wilcox.test(nestling2019$preBSM_chick_num, nestling2020$preBSM_chick_num)

# Summary stats for brood size by year for the nestling growth dataset 
aggregate(preBSM_chick_num ~ year, FUN = mean, data = nestling)
aggregate(preBSM_chick_num ~ year, FUN = sd, data = nestling)

# Wilcox test to compare hatch date in 2019 and 2020 for the 
# nestling growth dataset
wilcox.test(as.numeric(nestling2019$daysOfSum), as.numeric(nestling2020$daysOfSum))

# Summary stats for hatch date by year for the nestling growth dataset
aggregate(as.numeric(daysOfSum) ~ year, FUN = mean, data = nestling)
aggregate(as.numeric(daysOfSum) ~ year, FUN = sd, data = nestling)





