• This code makes and compares multiple generalized linear models of the experiment data with jellyfish bimass vs. Ditrichocoryceaus anglicus density.
  • A best fit model is chosen, and the results are visualized.
  • Link to report here: https://rpubs.com/HailaSchultz/exp_GLM-Ditrichocorycaeus

load packages

library(MASS)
library(ggplot2)
library(ggeffects)
library(dplyr)
library(scales)

Set up data

Read database into R. If current database changes, just change the path

Database <- read.csv("/Users/hailaschultz/Dropbox/Other studies/Aurelia project/Data Analysis/data/current_data/Final_Aurelia_Database_Jan11_2023.csv")

Add control tanks

First, read in the file that designates different samples to tanks with jellies other, tanks with zero jellies sampled at the beginning of the experiment remove, and tanks with zero jellies sampled at the end of the experiment zero

Control_tanks <- read.csv("/Users/hailaschultz/Dropbox/Other studies/Aurelia project/Data Analysis/data/current_data/Control_Tanks.csv")

Add control tank data to the database file

Database$Control_info <- Control_tanks$c1[match(Database$Sample.Code, Control_tanks$Sample.Code)]

Subset data

Subset to trials with large jellies where the number of jellies in the tanks was manipulated

Exp_numb_trials<- subset(Database, Trial.Type=='Number')
Exp_numb_large<-subset(Exp_numb_trials,Jelly.Size=="Large")

remove aug 22 2019 - the jellies we used for this experiment were younger/smaller than the other experiments, so I decided to omit it from analysis

Exp_sub<-subset(Exp_numb_large,Sample.Date!="08/22/2019")

remove tanks sampled at the beginning of experiment - we decided not to use these tanks because they were different than the tanks with zero jellies sampled at the end of the experiment and didn’t add anything beneficial

Exp_sub<-subset(Exp_sub,Control_info!="remove")

Prepare data

#convert sample year to a factor
Exp_sub$Sample.Year<- as.factor(Exp_sub$Sample.Year)
#Rename Vars (get the dots out)
Exp_sub$Jelly.Mass<-Exp_sub$Jelly.Mass..g.
Exp_sub$Density<-Exp_sub$Density....m3.
#calculate jelly density
Exp_sub$Jelly.Density<-Exp_sub$Jelly.Mass/Exp_sub$Vol.Filtered..m3.
#add 1 to jelly  density for analyses that prohibit zeroes
Exp_sub$Jelly.Density <-Exp_sub$Jelly.Density
colnames(Exp_sub)
##  [1] "BugSampleID"          "Project"              "Sample.Code"         
##  [4] "Sampling.Group"       "Station"              "Site"                
##  [7] "Site.Name"            "Basin"                "Sub.Basin"           
## [10] "Latitude"             "Longitude"            "Sample.Date"         
## [13] "Sample.Year"          "Sample.Month"         "Sample.Time"         
## [16] "Tow.Type"             "Mesh.Size"            "Station.Depth..m."   
## [19] "Flow.meter..revs."    "Broad.Group"          "Mid.Level.Group"     
## [22] "X1st.Word.Taxa"       "Genus.species"        "Life.History.Stage"  
## [25] "Total.Ct"             "Density....m3."       "Vol.Filtered..m3."   
## [28] "Jelly.Mass..g."       "Number.of.Jellies"    "Trial.Time"          
## [31] "Trial.Type"           "Jelly.Size"           "Jelly.Density....m3."
## [34] "Jelly.Density..g.m3." "Location"             "Control_info"        
## [37] "Jelly.Mass"           "Density"              "Jelly.Density"

Subset data to Ditrichocorycaeus and add multiple entries per tank:The mean of jelly density is taken because this should be the same number for all taxa in each tank.

Ditrichocorycaeus<-subset(Exp_sub, Genus.species == "DITRICHOCORYCAEUS ANGLICUS")
Ditrichocorycaeus <- Ditrichocorycaeus %>%
  group_by(Sample.Code, Station,Sample.Date,Sample.Year,Control_info) %>%
  summarise(
    CopDensity = sum(Density),
    Jelly.Density = mean(Jelly.Density))

Control geometric means

Calculate the geometric mean of the zero-jelly tanks to use as a control.

Ditrichocorycaeus$Control_info_combined <- paste(Ditrichocorycaeus$Sample.Date, Ditrichocorycaeus$Control_info)
Ditrichocorycaeus2<- Ditrichocorycaeus %>%
  group_by(Control_info,Control_info_combined,Sample.Date) %>%
  summarise(
    ave = exp(mean(log(CopDensity))))
Ditrichocorycaeus3<-subset(Ditrichocorycaeus2,Control_info=="zero")
# match the geometric mean of zero jelly tanks to each experiment
Ditrichocorycaeus$Control<- Ditrichocorycaeus3$ave[match(Ditrichocorycaeus$Sample.Date, Ditrichocorycaeus3$Sample.Date)]

Examine Data

Histograms of Jellyfish Density and Copepod Density

hist(Ditrichocorycaeus$CopDensity) 

hist(Ditrichocorycaeus$Jelly.Density) 

lograrithmic distribution for both

See if years are different

boxplot(CopDensity~Sample.Year, data=Ditrichocorycaeus)

variability for 2019 was higher than 2020

Plot Jellyfish Density against zooplankton density

ggplot(Ditrichocorycaeus, aes(x=Jelly.Density, y=CopDensity)) + geom_point(aes(colour=Sample.Date))

Family Options

Negative Binomial Distribution

#round to integers
Ditrichocorycaeus$CopDensity_round<-round(as.numeric(Ditrichocorycaeus$CopDensity), 0)
Ditrichocorycaeus$Control_round<-round(as.numeric(Ditrichocorycaeus$Control), 0)
#run model
Ditrichocorycaeus_model1 <- glm.nb(CopDensity_round~Jelly.Density, data = Ditrichocorycaeus)
summary(Ditrichocorycaeus_model1)
## 
## Call:
## glm.nb(formula = CopDensity_round ~ Jelly.Density, data = Ditrichocorycaeus, 
##     init.theta = 1.052170618, link = log)
## 
## Coefficients:
##                 Estimate Std. Error z value Pr(>|z|)    
## (Intercept)   10.8046151  0.1645473  65.663  < 2e-16 ***
## Jelly.Density -0.0001963  0.0000655  -2.997  0.00273 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for Negative Binomial(1.0522) family taken to be 1)
## 
##     Null deviance: 85.609  on 64  degrees of freedom
## Residual deviance: 74.596  on 63  degrees of freedom
## AIC: 1497
## 
## Number of Fisher Scoring iterations: 1
## 
## 
##               Theta:  1.052 
##           Std. Err.:  0.163 
## 
##  2 x log-likelihood:  -1491.021
plot(Ditrichocorycaeus_model1)

## Gaussian distribution

Ditrichocorycaeus_model2<-glm(CopDensity~Jelly.Density, data= Ditrichocorycaeus, family="gaussian")
summary(Ditrichocorycaeus_model2)
## 
## Call:
## glm(formula = CopDensity ~ Jelly.Density, family = "gaussian", 
##     data = Ditrichocorycaeus)
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   52422.845   7053.542   7.432 3.52e-10 ***
## Jelly.Density    -8.345      2.808  -2.972  0.00418 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 1746460262)
## 
##     Null deviance: 1.2546e+11  on 64  degrees of freedom
## Residual deviance: 1.1003e+11  on 63  degrees of freedom
## AIC: 1571.7
## 
## Number of Fisher Scoring iterations: 2
plot(Ditrichocorycaeus_model2)

Gamma distribution

Ditrichocorycaeus_model3<-glm(CopDensity~Jelly.Density, data= Ditrichocorycaeus, family="Gamma")
summary(Ditrichocorycaeus_model3)
## 
## Call:
## glm(formula = CopDensity ~ Jelly.Density, family = "Gamma", data = Ditrichocorycaeus)
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   1.683e-05  3.246e-06   5.185 2.43e-06 ***
## Jelly.Density 9.741e-09  2.884e-09   3.378  0.00126 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for Gamma family taken to be 0.9565288)
## 
##     Null deviance: 81.370  on 64  degrees of freedom
## Residual deviance: 66.381  on 63  degrees of freedom
## AIC: 1492.8
## 
## Number of Fisher Scoring iterations: 6
plot(Ditrichocorycaeus_model3)

Gamma is the best so far - move forward with it

Add other parameters

Ditrichocorycaeus anglicus Final Model

DitrichocorycaeusMod<-glm(CopDensity~Jelly.Density+offset(log(Control)), data= Ditrichocorycaeus, family="Gamma"(link="log"))
summary(DitrichocorycaeusMod)
## 
## Call:
## glm(formula = CopDensity ~ Jelly.Density + offset(log(Control)), 
##     family = Gamma(link = "log"), data = Ditrichocorycaeus)
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   -4.515e-02  5.084e-02  -0.888    0.378    
## Jelly.Density -2.499e-04  2.024e-05 -12.352   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for Gamma family taken to be 0.09073167)
## 
##     Null deviance: 18.9831  on 64  degrees of freedom
## Residual deviance:  5.9979  on 63  degrees of freedom
## AIC: 1326.8
## 
## Number of Fisher Scoring iterations: 6
plot(DitrichocorycaeusMod)

extract rate of change estimates with confidence intervals

exp(coef(DitrichocorycaeusMod))                
##   (Intercept) Jelly.Density 
##     0.9558585     0.9997501
exp(confint(DitrichocorycaeusMod, level=.95))  
##                   2.5 %    97.5 %
## (Intercept)   0.8688314 1.0542655
## Jelly.Density 0.9997135 0.9997877
#get rate of change (1-exp(coefficient))
1-0.9997501
## [1] 0.0002499

Calculate rate of change

a<-exp(-2.499e-04)
a
## [1] 0.9997501
b<-a-1
c<-b*100
c
## [1] -0.02498688

Use predict function to predict model values

predictditrichocorycaeus<-ggpredict(
  DitrichocorycaeusMod,
  terms=c("Jelly.Density"),
  ci.lvl = 0.95,
  type = "fe",
  typical = "mean",
  condition = NULL,
  back.transform = TRUE,
  ppd = FALSE,
  vcov.fun = NULL,
  vcov.type = NULL,
  vcov.args = NULL,
  interval = "confidence")

Plot with original values

DitrichocorycaeusPlot<-plot(predictditrichocorycaeus,add.data = TRUE,dot.size=1.5,dot.alpha=0.65)+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(), axis.line = element_line(colour = "black"))+theme_classic() +
  scale_x_continuous(breaks=seq(0,7500,1500),expand = c(0, 20), limits = c(-10, 7500)) + 
  scale_y_continuous(breaks=seq(0,200000,50000),expand = c(0, 20), limits = c(-10, 200000))+
  geom_line(size=1.5) +
  geom_ribbon( aes(ymin = conf.low, ymax = conf.high), alpha = .15)+ xlab(bquote('Jellyfish Biomass ( g /' ~m^3~ ')'))+ 
  ylab(expression(italic('D. anglicus') ~ plain('Density') ~ plain('( # /' ~ m^3 ~ ')')))+
  theme(axis.text=element_text(size=15,colour="black"),
        legend.position=c(0.87, 0.8),
        legend.text=element_text(size=15,colour="black"),
        legend.title=element_text(size=15,colour="black"),
        axis.title=element_text(size=15,colour="black"),
        axis.line = element_line(colour = "black"))+theme(plot.title = element_blank())+
  theme(plot.margin=margin(0.7, 0.7, 0.7, 0.7, unit = "cm"))
DitrichocorycaeusPlot

save plot

setwd("/Users/hailaschultz/Dropbox/Other studies/Aurelia project/Data Analysis/output")
ggsave(filename = "Exp_GLM_Ditrichocorycaeus.png", plot = DitrichocorycaeusPlot, width = 6, height = 5, device='png', dpi=700)

Plot without original values

DitrichocorycaeusPlot_nodata<-plot(predictditrichocorycaeus)+xlab('Jellyfish Biomass ( g /' ~m^3~ ')')+
  ylab(bquote('Copepod Density ( individuals /'~m^3~')'))+ 
  theme(axis.line = element_line(colour = "black"))+theme_classic() +
  geom_line(size=1) +
  geom_ribbon( aes(ymin = conf.low, ymax = conf.high, color = NULL),
               alpha = .15,show.legend=FALSE) +
  scale_x_continuous(breaks=seq(0,7500,1500),expand = c(0, 20), limits = c(-10, 7500)) + 
  scale_y_continuous(breaks=seq(0,60000,10000),expand = c(0, 20), limits = c(-10, 60000))+
  theme(axis.text=element_text(size=8,colour="black"),
        axis.title=element_text(size=10),
        plot.title=element_blank())+
  theme(legend.position='none')+
  theme(plot.margin=margin(0.5, 0.5, 0.5, 0.5, unit = "cm"))
DitrichocorycaeusPlot_nodata

save plot

setwd("/Users/hailaschultz/Dropbox/Other studies/Aurelia project/Data Analysis/output")
ggsave(filename = "Exp_GLM_Ditrichocorycaeus_nodata.png", plot = DitrichocorycaeusPlot_nodata, width = 6, height = 5, device='png', dpi=700)