plotResiduals(res7d, form = rots$day)
plotResiduals(res7d, form = rots$species)
citation('mgcv')
summary(m7d)
### Analysis of data for "Salinization and the toxic alga Prymnesium parvum suppress freshwater rotifers across experimental scales"
rm(list = ls()) # clean global environment
library(ggplot2)
library(ggbreak)
library(ggthemes)
library(dplyr)
library(tidyr)
library(glmmTMB)    #mixed models with zero inflation and overdispersion
library(splines)
library(DHARMa)    #simulation-based residual diagnostics
library(performance)
library(lme4)
library(viridis)
library(scales)
# Load your data
setwd("/Users/margie/Documents/IGB/Aquacosm/for publication/for FRED")
rotifers <- read.csv("meso_rotifers.csv")
# adjust the reference (controls); also treatments as factors and new columns for log salinity and abundance
rots <- rotifers %>%
mutate(
count = as.integer(count),
tp = relevel(factor(tp), ref = "L"),
salinity = as.numeric(salinity),
species = as.factor(species),
mesocosm = as.factor(mesocosm),
day = as.integer(day),
log_abundance = log(abundance + 1),
log_salinity = log(salinity))
# check proportion of zeros overall and by factor
mean(rots$count == 0) #38% zeros is very high, may need zero inflation model
# By species
with(rots, tapply(count == 0, species, mean)) #its about equal per species; 34% for Keratella and 41% for lepadella
# By salinity
with(rots, tapply(count == 0, salinity, mean)) #most zeros in 5ppt but still quite many in 0.05ppt
# By TP
with(rots, tapply(count == 0, tp, mean)) #zeros pretty equal between TP treatments
#summary of non-zero counts
summary(rots$count[rots$count > 0]) #of the values greater than zero... looks like there is an upper outlier
with(rots[rots$count > 0, ], tapply(count, species, summary)) #outlier is in lepadella
#summary table of averages
avg_sum <- rots %>%
group_by(salinity, day, species) %>%
summarise(mean_abun = mean(abundance))
#visualize data distriubtion
ggplot(rots, aes(day, count, colour = species)) + #looks like species diverge over time
geom_point(alpha = 0.5) +
geom_smooth(se = FALSE) +
scale_y_log10()
ggplot(rots, aes(as.factor(salinity), count)) + #species have similar repsonse to salinity and decrease with increasing salinity
geom_boxplot() +
facet_wrap(~ species) +
scale_y_log10()
ggplot(rots, aes(tp, count)) + #species have similar response to TP and not much difference between TP treatments
geom_boxplot() +
facet_wrap(~ species) +
scale_y_log10()
#try full model first, tp has no effect or interaction
m1 <- lmer(
log_abundance ~ species * log_salinity * tp * day +
(1 | mesocosm),
data = rots
)
summary(m1)
#simplify model with no tp interaction
m2 <- lmer(
log_abundance ~ species * log_salinity * day + tp +
(1 | mesocosm),
data = rots
)
summary(m2)
anova(m1, m2) #m1 is not better than m2 and AIC lower in m2
#tp still doesn't add to model so let's try without tp
m3 <- lmer(
log_abundance ~ species * log_salinity * day +
(1 | mesocosm),
data = rots
)
summary(m3)
anova(m2, m3)
sim <- simulateResiduals(m3)
plot(sim)
m4 <- glmmTMB(
abundance ~ species * log_salinity * day + tp +
(1 | mesocosm),
ziformula = ~1,
family = nbinom2,
data = rots
) #warning because abundance is not non-integer but neg binomial needs integer
summary(m4)
#corrected model using integer count corrected with offset for sample volume
#zero inflation is still present but didn't improve the model when added
#dispersion and uniformity though are not sig
rots <- rots[-164, ]
m5 <- glmmTMB(
count ~ species * log_salinity * day + tp +
offset(log(volume_ml)) +
(1 | mesocosm),
family = nbinom2,
data = rots
)
summary(m5)
r2(m5)
res <- simulateResiduals(m5)
plot(res)
testDispersion(res)
testZeroInflation(res)
testUniformity(res)
m5_slope <- glmmTMB(
count ~ species * log_salinity * day + tp +
offset(log(volume_ml)) +
(1 + day | mesocosm),
family = nbinom2,
data = rots)
anova(m5, m5_slope) # basically the same
## add splines so that fit cam be flexible across day
m6 <- glmmTMB(
count ~ species * ns(log_salinity, df = 2) * ns(day, df = 3) + tp +
offset(log(volume_ml)) +
(1 | mesocosm),
family = nbinom2,
data = rots
)
anova(m5, m6)
res6 <- simulateResiduals(m6)
plot(res6)
testZeroInflation(res6)
library(mgcv)
# add smooth for day
m7a <- gam(count ~ species + tp + log_salinity +
s(day, k = 5) + s(mesocosm, bs = "re") + offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7a)
# let day curve dif by species
m7b <- gam(count ~ species + tp + log_salinity +
s(day, by = species, k = 5) + s(mesocosm, bs = "re") +
offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7b)
anova.gam(m7a, m7b, test = "Chisq")
# let salinity be smooth
m7c <- gam(count ~ species + tp +
s(day, by = species, k = 7) + s(mesocosm, bs = "re") +
s(log_salinity, by = species, k = 4) +
offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7c)
anova.gam(m7a, m7b, m7c, test = "Chisq")
gam.check(m7c)
# but actually the pattern over time also varies by salinity
m7d <- gam(
count ~ species + tp +
te(day, log_salinity, by = species, k = c(5, 4)) +
s(mesocosm, bs = "re") +
offset(log(volume_ml)),
family = nb(),
data = rots,
method = "REML"
)
anova.gam(m7c, m7d, test = "Chisq")
gam.check(m7d)
summary(m7d)
res7d <- simulateResiduals(m7d)
plot(res7d)
testZeroInflation(res7d)
testDispersion(res7d)
plotResiduals(res7d, form = rots$day)
plotResiduals(res7d, form = rots$species)
### 3. plot predicted data ###
newdat <- expand.grid(
log_salinity = seq(min(rots$log_salinity), max(rots$log_salinity), length.out = 100),
species = levels(rots$species),
tp = "L",
day = c(7, 21, 35),
volume_ml = mean(rots$volume_ml)
)
newdat$mesocosm <- factor(rots$mesocosm[1], levels = levels(rots$mesocosm))
# predict
pred <- predict(m7d, newdata = newdat, type = "link", se.fit = T, exclude = "s(mescosm)")
newdat$pred <- exp(pred$fit) +1
newdat$lwr <- exp(pred$fit - 1.96 * pred$se.fit) + 1
newdat$upr <- exp(pred$fit + 1.96 * pred$se.fit) + 1
# Select only 3 representative days for predictions
pred_lines <- newdat %>% filter(day %in% c(7, 21, 35))
pred_lines$day_linetype <- factor(pred_lines$day, levels = c(7, 21, 35),
labels = c("Day 7", "Day 21", "Day 35"))
# plot raw data points and add 3 predicted lines for 3 representative days
ggplot() +
geom_jitter(data = rots, aes(x = log_salinity, y = abundance+1, color = day),
width = 0.2, alpha = 1, size = 2) +
geom_line(data = pred_lines, aes(x = log_salinity, y = pred,
linetype = day_linetype, color = day), size = 2) +
geom_ribbon(data = pred_lines, aes(x = log_salinity, ymin = lwr, ymax = upr,
fill = day_linetype, group = day_linetype), alpha = 0.2) +
scale_y_log10() +
scale_color_gradient() +
scale_fill_manual(values = c('#203654', '#43709F', '#6DAEF0')) +
guides(fill = "none") +
facet_wrap(~ species, labeller = labeller(species = c(
"Keratella" = "italic('K. cochlearis')",
"Lepadella" = "italic('L. patella')"),
.default = label_parsed)) +
labs(x = "Salinity (ppt log scale)", y = expression(Rotifers~L^{-1}~"(log scale)"), linetype = '', color = 'Day') +
theme_few(17) +
theme(strip.text = element_text(size = 16),
legend.key.width = unit(2, "line"),
legend.key.size = unit(0.4, "cm"))
sal_vals <- c(0.05, 0.2, 1, 5)
newdat <- expand.grid(
log_salinity = log(sal_vals),
species = levels(rots$species),
tp = "L",
day = seq(min(rots$day), max(rots$day), length.out = 100),
volume_ml = mean(rots$volume_ml))
newdat$mesocosm <- factor(rots$mesocosm[1], levels = levels(rots$mesocosm))
# predict
pred <- predict(m7d, newdata = newdat, type = "link", se.fit = T, exclude = "s(mescosm)")
newdat$pred <- exp(pred$fit)
newdat$pred_plus <- newdat$pred + 1
newdat$lwr <- exp(pred$fit - 1.96 * pred$se.fit)
newdat$upr <- exp(pred$fit + 1.96 * pred$se.fit)
#make four lines for salinity
newdat$salinity_f <- factor(exp(newdat$log_salinity),
levels = sal_vals,
labels = c("0.05", "0.2", "1", "5"))
ggplot() +
geom_jitter(data = rots, aes(x = day, y = abundance, color = as.factor(salinity)),
width = 0.2, alpha = 1, size = 2) +
geom_line(data = newdat, aes(x = day, y = pred,
color = salinity_f, group = salinity_f), size = 2) +
geom_ribbon(data = newdat, aes(x = day, ymin = lwr, ymax = upr, fill = salinity_f, group = salinity_f),
alpha = 0.15) +
scale_y_break(c(400, 1400), scales = 0.1, space = 0.1) +   # break axis
scale_y_continuous(breaks = c(0, 100, 200, 300, 400, 1500),
limits = c(0, 1500)) + # specify ticks manually
scale_color_manual(values = c('black', '#DA3A55', '#50CA3D', '#0889E2')) +
scale_fill_manual(values = c('black', '#DA3A55', '#50CA3D', '#0889E2')) +
guides(fill = "none") +
facet_wrap(~ species, labeller = labeller(species = c(
"Keratella" = "italic('K. cochlearis')",
"Lepadella" = "italic('L. patella')"),
.default = label_parsed)) +
labs(x = "Day", y = expression(Rotifers~L^{-1}~""), color = 'Salinity (ppt)') +
theme_few(17) +
theme(strip.text = element_text(size = 16),
axis.title.x = element_text(hjust = 0.42))
rotifers <- read.csv("meso_rotifers.csv")
# adjust the reference (controls); also treatments as factors and new columns for log salinity and abundance
rots <- rotifers %>%
mutate(
count = as.integer(count),
tp = relevel(factor(tp), ref = "L"),
salinity = as.numeric(salinity),
species = as.factor(species),
mesocosm = as.factor(mesocosm),
day = as.integer(day),
log_abundance = log(abundance + 1),
log_salinity = log(salinity))
#try full model first, tp has no effect or interaction
m1 <- lmer(
log_abundance ~ species * log_salinity * tp * day +
(1 | mesocosm),
data = rots
)
summary(m1)
#simplify model with no tp interaction
m2 <- lmer(
log_abundance ~ species * log_salinity * day + tp +
(1 | mesocosm),
data = rots
)
summary(m2)
anova(m1, m2) #m1 is not better than m2 and AIC lower in m2
#tp still doesn't add to model so let's try without tp
m3 <- lmer(
log_abundance ~ species * log_salinity * day +
(1 | mesocosm),
data = rots
)
summary(m3)
anova(m2, m3)
sim <- simulateResiduals(m3)
plot(sim)
m4 <- glmmTMB(
abundance ~ species * log_salinity * day + tp +
(1 | mesocosm),
ziformula = ~1,
family = nbinom2,
data = rots
) #warning because abundance is not non-integer but neg binomial needs integer
summary(m4)
m5 <- glmmTMB(
count ~ species * log_salinity * day + tp +
offset(log(volume_ml)) +
(1 | mesocosm),
family = nbinom2,
data = rots
)
summary(m5)
r2(m5)
res <- simulateResiduals(m5)
plot(res)
testDispersion(res)
testZeroInflation(res)
testUniformity(res)
m5_slope <- glmmTMB(
count ~ species * log_salinity * day + tp +
offset(log(volume_ml)) +
(1 + day | mesocosm),
family = nbinom2,
data = rots)
anova(m5, m5_slope) # basically the same
## add splines so that fit cam be flexible across day
m6 <- glmmTMB(
count ~ species * ns(log_salinity, df = 2) * ns(day, df = 3) + tp +
offset(log(volume_ml)) +
(1 | mesocosm),
family = nbinom2,
data = rots
)
anova(m5, m6)
res6 <- simulateResiduals(m6)
plot(res6)
testZeroInflation(res6)
library(mgcv)
# add smooth for day
m7a <- gam(count ~ species + tp + log_salinity +
s(day, k = 5) + s(mesocosm, bs = "re") + offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7a)
# let day curve dif by species
m7b <- gam(count ~ species + tp + log_salinity +
s(day, by = species, k = 5) + s(mesocosm, bs = "re") +
offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7b)
anova.gam(m7a, m7b, test = "Chisq")
# let salinity be smooth
m7c <- gam(count ~ species + tp +
s(day, by = species, k = 7) + s(mesocosm, bs = "re") +
s(log_salinity, by = species, k = 4) +
offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7c)
anova.gam(m7a, m7b, m7c, test = "Chisq")
gam.check(m7c)
# but actually the pattern over time also varies by salinity
m7d <- gam(
count ~ species + tp +
te(day, log_salinity, by = species, k = c(5, 4)) +
s(mesocosm, bs = "re") +
offset(log(volume_ml)),
family = nb(),
data = rots,
method = "REML"
)
anova.gam(m7c, m7d, test = "Chisq")
gam.check(m7d)
summary(m7d)
res7d <- simulateResiduals(m7d)
plot(res7d)
testZeroInflation(res7d)
testDispersion(res7d)
plotResiduals(res7d, form = rots$day)
plotResiduals(res7d, form = rots$species)
summary(m7d)
res7d <- simulateResiduals(m7d)
plot(res7d)
testZeroInflation(res7d)
testDispersion(res7d)
plotResiduals(res7d, form = rots$day)
plotResiduals(res7d, form = rots$species)
### 3. plot predicted data ###
newdat <- expand.grid(
log_salinity = seq(min(rots$log_salinity), max(rots$log_salinity), length.out = 100),
species = levels(rots$species),
tp = "L",
day = c(7, 21, 35),
volume_ml = mean(rots$volume_ml)
)
newdat$mesocosm <- factor(rots$mesocosm[1], levels = levels(rots$mesocosm))
# predict
pred <- predict(m7d, newdata = newdat, type = "link", se.fit = T, exclude = "s(mescosm)")
newdat$pred <- exp(pred$fit) +1
newdat$lwr <- exp(pred$fit - 1.96 * pred$se.fit) + 1
newdat$upr <- exp(pred$fit + 1.96 * pred$se.fit) + 1
# Select only 3 representative days for predictions
pred_lines <- newdat %>% filter(day %in% c(7, 21, 35))
pred_lines$day_linetype <- factor(pred_lines$day, levels = c(7, 21, 35),
labels = c("Day 7", "Day 21", "Day 35"))
# plot raw data points and add 3 predicted lines for 3 representative days
ggplot() +
geom_jitter(data = rots, aes(x = log_salinity, y = abundance+1, color = day),
width = 0.2, alpha = 1, size = 2) +
geom_line(data = pred_lines, aes(x = log_salinity, y = pred,
linetype = day_linetype, color = day), size = 2) +
geom_ribbon(data = pred_lines, aes(x = log_salinity, ymin = lwr, ymax = upr,
fill = day_linetype, group = day_linetype), alpha = 0.2) +
scale_y_log10() +
scale_color_gradient() +
scale_fill_manual(values = c('#203654', '#43709F', '#6DAEF0')) +
guides(fill = "none") +
facet_wrap(~ species, labeller = labeller(species = c(
"Keratella" = "italic('K. cochlearis')",
"Lepadella" = "italic('L. patella')"),
.default = label_parsed)) +
labs(x = "Salinity (ppt log scale)", y = expression(Rotifers~L^{-1}~"(log scale)"), linetype = '', color = 'Day') +
theme_few(17) +
theme(strip.text = element_text(size = 16),
legend.key.width = unit(2, "line"),
legend.key.size = unit(0.4, "cm"))
sal_vals <- c(0.05, 0.2, 1, 5)
newdat <- expand.grid(
log_salinity = log(sal_vals),
species = levels(rots$species),
tp = "L",
day = seq(min(rots$day), max(rots$day), length.out = 100),
volume_ml = mean(rots$volume_ml))
newdat$mesocosm <- factor(rots$mesocosm[1], levels = levels(rots$mesocosm))
# predict
pred <- predict(m7d, newdata = newdat, type = "link", se.fit = T, exclude = "s(mescosm)")
newdat$pred <- exp(pred$fit)
newdat$pred_plus <- newdat$pred + 1
newdat$lwr <- exp(pred$fit - 1.96 * pred$se.fit)
newdat$upr <- exp(pred$fit + 1.96 * pred$se.fit)
#make four lines for salinity
newdat$salinity_f <- factor(exp(newdat$log_salinity),
levels = sal_vals,
labels = c("0.05", "0.2", "1", "5"))
ggplot() +
geom_jitter(data = rots, aes(x = day, y = abundance, color = as.factor(salinity)),
width = 0.2, alpha = 1, size = 2) +
geom_line(data = newdat, aes(x = day, y = pred,
color = salinity_f, group = salinity_f), size = 2) +
geom_ribbon(data = newdat, aes(x = day, ymin = lwr, ymax = upr, fill = salinity_f, group = salinity_f),
alpha = 0.15) +
scale_y_break(c(400, 1400), scales = 0.1, space = 0.1) +   # break axis
scale_y_continuous(breaks = c(0, 100, 200, 300, 400, 1500),
limits = c(0, 1500)) + # specify ticks manually
scale_color_manual(values = c('black', '#DA3A55', '#50CA3D', '#0889E2')) +
scale_fill_manual(values = c('black', '#DA3A55', '#50CA3D', '#0889E2')) +
guides(fill = "none") +
facet_wrap(~ species, labeller = labeller(species = c(
"Keratella" = "italic('K. cochlearis')",
"Lepadella" = "italic('L. patella')"),
.default = label_parsed)) +
labs(x = "Day", y = expression(Rotifers~L^{-1}~""), color = 'Salinity (ppt)') +
theme_few(17) +
theme(strip.text = element_text(size = 16),
axis.title.x = element_text(hjust = 0.42))
summary(m7d)
# but actually the pattern over time also varies by salinity
m7d <- gam(
count ~ species + tp +
te(day, log_salinity, by = species, k = c(5, 4)) +
s(mesocosm, bs = "re") +
offset(log(volume_ml)),
family = nb(),
data = rots,
method = "REML"
)
anova.gam(m7c, m7d, test = "Chisq")
gam.check(m7d)
summary(m7d)
res7d <- simulateResiduals(m7d)
plot(res7d)
testZeroInflation(res7d)
testDispersion(res7d)
plotResiduals(res7d, form = rots$day)
plotResiduals(res7d, form = rots$species)
### 3. plot predicted data ###
newdat <- expand.grid(
log_salinity = seq(min(rots$log_salinity), max(rots$log_salinity), length.out = 100),
species = levels(rots$species),
tp = "L",
day = c(7, 21, 35),
volume_ml = mean(rots$volume_ml)
)
newdat$mesocosm <- factor(rots$mesocosm[1], levels = levels(rots$mesocosm))
# predict
pred <- predict(m7d, newdata = newdat, type = "link", se.fit = T, exclude = "s(mescosm)")
newdat$pred <- exp(pred$fit) +1
newdat$lwr <- exp(pred$fit - 1.96 * pred$se.fit) + 1
newdat$upr <- exp(pred$fit + 1.96 * pred$se.fit) + 1
# Select only 3 representative days for predictions
pred_lines <- newdat %>% filter(day %in% c(7, 21, 35))
pred_lines$day_linetype <- factor(pred_lines$day, levels = c(7, 21, 35),
labels = c("Day 7", "Day 21", "Day 35"))
# plot raw data points and add 3 predicted lines for 3 representative days
ggplot() +
geom_jitter(data = rots, aes(x = log_salinity, y = abundance+1, color = day),
width = 0.2, alpha = 1, size = 2) +
geom_line(data = pred_lines, aes(x = log_salinity, y = pred,
linetype = day_linetype, color = day), size = 2) +
geom_ribbon(data = pred_lines, aes(x = log_salinity, ymin = lwr, ymax = upr,
fill = day_linetype, group = day_linetype), alpha = 0.2) +
scale_y_log10() +
scale_color_gradient() +
scale_fill_manual(values = c('#203654', '#43709F', '#6DAEF0')) +
guides(fill = "none") +
facet_wrap(~ species, labeller = labeller(species = c(
"Keratella" = "italic('K. cochlearis')",
"Lepadella" = "italic('L. patella')"),
.default = label_parsed)) +
labs(x = "Salinity (ppt log scale)", y = expression(Rotifers~L^{-1}~"(log scale)"), linetype = '', color = 'Day') +
theme_few(17) +
theme(strip.text = element_text(size = 16),
legend.key.width = unit(2, "line"),
legend.key.size = unit(0.4, "cm"))
