---
title: "Influence of isolation on the resilience of tank bromeliad ecosystems to drought in a Neotropical rainforest"
Author: "Marie Séguigne"
output: html_document
date: '2024-03-18'
---


```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

###Packages to load
```{r}
setwd("C:/Users/mseguigne/Desktop/Resilience_Task 3/Resilience_Task3_R")
library(readxl)
library(ggplot2)
library(ggfortify)
library(SciViews)
library(mvabund)
library(performance)
library(piecewiseSEM)
library(raster)
library(dplyr)
library(tidyverse)
```

### I) Organizing dataset
#### I.1) General dataset
```{r}
rawdata2021 <-  read_excel("C:/Users/mseguigne/Desktop/Resilience_Task 3/Resilience_Task3_R/Data_2021.xlsx")
options( "digits"=12, "scipen"=0) #pour bien garder tous les chiffres apres la virgules

rawdata2021$treatment = as.factor(rawdata2021$treatment)
rawdata2021$N.brom = as.factor(rawdata2021$N.brom)
rawdata2021$time.after.T0 = as.factor(rawdata2021$time.after.T0)
rawdata2021$sampling.day2 = as.factor(rawdata2021$sampling.day2)
rawdata2021$ID = as.character(rawdata2021$ID)
rawdata2021$'mass.loss.%' = as.numeric(rawdata2021$'mass.loss.%')
rawdata2021$'FPOM (ml)'= as.numeric(rawdata2021$'FPOM (ml)')
rawdata2021$lat = as.numeric(rawdata2021$lat)
rawdata2021$long = as.numeric(rawdata2021$long)
rawdata2021$Diam = as.numeric(rawdata2021$Diam)
rawdata2021$Vmax = as.numeric(rawdata2021$Vmax)
rawdata2021$NL = as.numeric(rawdata2021$NL)
rawdata2021$Vactual = as.numeric(rawdata2021$Vactual)
rawdata2021$dry.bromeliad.days = as.numeric(rawdata2021$dry.bromeliad.days)

colnames(rawdata2021)[1] <- "ID"
colnames(rawdata2021)[20] <- "mass_loss"
colnames(rawdata2021)[6] <- "time"
colnames(rawdata2021)[27] <- "FPOM"

ID <- dplyr::select(rawdata2021, ID)
ID_time <- dplyr::select(rawdata2021, ID, time)
```

#### I.2) Invertebrates density by group
```{r}
density <- read.table("inv_by_stages.csv", header = FALSE, sep= ";", encoding="UTF-8")
density <- density[c(1:36),]
colnames(density) <- density[1,]
density <- density[c(-1,-6,-26,-27,-29,-31,-32,-35,-36),]
density$grp <- c("collector", "scraper", "scraper", "scraper", "collector", "mesopredator", "mesopredator", "mesopredator",
                 "filter feeder","filter feeder","filter feeder","filter feeder","filter feeder","filter feeder","filter feeder",
                 "filter feeder","filter feeder", "predator", "predator", "mesopredator", "shredder", "shredder", "shredder",
                "predator", "leaf piercer", "collector", "filter feeder")
density <- density[,c(147,1,2,3:146)]
density <- density[,c(-2)]
density$grp <- as.factor(density$grp)
density[,c(2:146)] <- lapply(density[,c(2:146)], as.numeric)

shredder <- subset(density, grp == "shredder")
shredder <- shredder[,2]*shredder[,3:146]
shredder <- apply(shredder, 2, sum)
shredder <- as.data.frame(shredder)
shredder <- cbind(ID, shredder)
rawdata2021 <- merge(rawdata2021, shredder, by = "ID")
rm(shredder)

predator <- subset(density, grp == "predator")
mesopredator <- subset(density, grp == "mesopredator")
predator <- rbind(predator, mesopredator) #to work with one group for predator and mesopredator 
predator <- predator[,2]*predator[,3:146]
predator <- apply(predator, 2, sum)
predator <- as.data.frame(predator)
predator <- cbind(ID, predator)
rawdata2021 <- merge(rawdata2021, predator, by = "ID")
rm(predator, mesopredator)

scraper <- subset(density, grp == "scraper")
scraper <- scraper[,2]*scraper[,3:146]
scraper <- apply(scraper, 2, sum)
scraper <- as.data.frame(scraper)
scraper <- cbind(ID, scraper)
rawdata2021 <- merge(rawdata2021, scraper, by = "ID")
rm(scraper)

collector <- subset(density, grp == "collector")
collector <- collector[,2]*collector[,3:146]
collector <- apply(collector, 2, sum)
collector <- as.data.frame(collector)
collector <- cbind(ID, collector)
rawdata2021 <- merge(rawdata2021, collector, by = "ID")
rm(collector)

filter <- subset(density, grp == "filter feeder")
filter <- filter[,2]*filter[,3:146]
filter <- apply(filter, 2, sum)
filter <- as.data.frame(filter)
filter <- cbind(ID, filter)
rawdata2021 <- merge(rawdata2021, filter, by ="ID")
rm(filter)
```


#### I.3) Microorganisms 
```{r}
microorg <- read.table("microorg.csv", header = TRUE, sep= ";", encoding="UTF-8")
options( "digits"=12, "scipen"=0) 

microorg[,c(5:7)] <- lapply(microorg[,c(5:6)], as.numeric)
colnames(microorg)[1] <- "ID"
colnames(microorg)[5] <- "Attached_bact"
colnames(microorg)[6] <- "Ergosterol"
microorg <- microorg[,c(-2:-4,-7)]
rawdata2021 <- merge(rawdata2021, microorg)

rm(microorg)

#Estimating bacteria biomass
bact_biovol = (4/3)*pi*(0.4^3) #We consider a bacteria as a sphere with a diameter = 0.8µm, so a radius of 0.4µm
rawdata2021$bact_biomass <- ((rawdata2021$Attached_bact)*bact_biovol*(4*10^(-7)))/10 #To express in µgDW
#rawdata2_count$bact_biomass <- ((rawdata2_count$Attached_bact)*bact_biovol*0.4)/10 #To express in pgDW
rm(bact_biovol)
```

#### I.4) Decomposition rate, distances, and final df
Based on the initial formula elaborated by Olson (1963): 
mt/m0 = e^(-kt)
With: 
- m0 the initial mass, 
- mt the mass after decomposition, 
- t the time in day 
- k the decomposition rate

We calculate k as follow: 
k = -(ln(mt/m0))/t

```{r}
T7 <- subset(rawdata2021, time == "7")
T7$rateA <- (-ln(T7$leafA.Tf/T7$leafA.T0))/7
T7$rateB <- (-ln(T7$leafB.Tf/T7$leafB.T0))/7
T7$rate_total <- (-ln(T7$leaf.final/T7$leaf.initial))/7

T15 <- subset(rawdata2021, time == "15")
T15$rateA <- (-ln(T15$leafA.Tf/T15$leafA.T0))/15
T15$rateB <- (-ln(T15$leafB.Tf/T15$leafB.T0))/15
T15$rate_total <- (-ln(T15$leaf.final/T15$leaf.initial))/15

T60 <- subset(rawdata2021, time == "60")
T60$rateA <- (-ln(T60$leafA.Tf/T60$leafA.T0))/60
T60$rateB <- (-ln(T60$leafB.Tf/T60$leafB.T0))/60
T60$rate_total <- (-ln(T60$leaf.final/T60$leaf.initial))/60

rawdata2021 <- rbind(T7, T15, T60)
rm(T7, T15, T60)

plot <- ggplot(rawdata2021, aes(x = time, y = rate_total, color = treatment)) + 
  geom_boxplot() + 
  facet_grid(~ N.brom)+
  xlab("time") + ylab("rate mass loss k ")

ggsave(plot = plot, filename = paste0('decompo_rate','.jpg'), device = "jpg", path = "C:/Users/mseguigne/Desktop/Resilience_Task 3/Plots", width = 7, height = 6, units = "in") #save the 
```

Average distance among groups of bromeliads
```{r}
coord <- rawdata2021
coord <- dplyr::select(coord, N.brom, lat, long)

coord2 = cbind(coord[coord$N.brom == "1",]  %>% 
             dplyr::select(-N.brom) %>% 
             dplyr::rename(x1 = lat,
                    y1 = long),
           coord[coord$N.brom == "3",]  %>% 
             dplyr::select(-N.brom) %>% 
             dplyr::rename(x3 = lat,
                    y3 = long), 
           coord[coord$N.brom == "6",]  %>% 
             dplyr::select(-N.brom) %>% 
             dplyr::rename(x6 = lat,
                    y6 = long))

v = c()

for(i in 1:nrow(coord2)){
  
  dist = raster::pointDistance(lonlat = T,
                               p1 = c(coord2$x1[i],coord2$y1[i]),
                               p2 = c(coord2$x3[i],coord2$y3[i]),
                               p3 = c(coord2$x6[i],coord2$y6[i]))
  
  v = c(v,dist)
  
}
coord2$dist = v
mean(coord2$dist)
rm(coord)
```

Final dataframes 
```{r}
#take off tank bromeliad with 0 everywhere (brom number 72)
rawdata2021 <- rawdata2021[-grep("72", rawdata2021$ID),]
ID <- ID[-grep("72", ID$ID),]
density <- density[,-111]
```

### III) Analyses
#### III.1) Spatial autocorrelation test 
Spatial autocorrelation test
```{r}
envir <- dplyr::select(rawdata2021, ID, dry.bromeliad.days, NL, Vactual)
envir <- as.matrix(envir)
row.names(envir) <- envir[,1]
envir <- envir[,-1]
envir <- as.data.frame(envir)
envir[,c(1:3)] <- lapply(envir[,c(1:3)], as.numeric)
envir <- as.data.frame(envir)

coord <- dplyr::select(rawdata2021, ID, lat, long)
coord <- coord[-120,-1]

invertebrate <- read.table("inv_by_species.csv", header = FALSE, sep= ";", encoding="UTF-8")
invertebrate <- invertebrate[,-1]
colnames(invertebrate)<- invertebrate[1,]
invertebrate <- invertebrate[-1,]
rownames(invertebrate) <- invertebrate[,1]
invertebrate <- invertebrate[,-1]
invertebrate <- invertebrate[,-109]#take off brom 72
invertebrate <- t(invertebrate)
invertebrate <- as.data.frame(invertebrate)

##Partial Mantel test for spatial autocorrelation
inv_hellinger <- vegan::decostand(invertebrate, method = "hellinger") #Lets transform abundance data (Y) using the Hellinger-transform method (Borcard, Gillet, and Legendre 2011; Legendre and Gallagher 2001).

spedist<-vegan::vegdist(inv_hellinger, method="bray") #Distance matrix of species abundance data
envdist<-vegan::vegdist(envir, method="bray") 
geodist <- vegan::vegdist(coord, method="euclidian")
set.seed(123)
vegan::mantel.partial(spedist, envdist, geodist, method="pearson", permutations=999)

rm(spedist, envdist, geodist, coord, invertebrate, envir, inv_hellinger)
```

#### III.2) Invertebrate community structure
Vizualising data
```{r}
invertebrate <- read.table("inv_by_species.csv", header = FALSE, sep= ";", encoding="UTF-8", )
invertebrate<- invertebrate[,-1]
row.names(invertebrate) <- invertebrate[,1]
invertebrate <- invertebrate[,-1]
invertebrate <- t(invertebrate)
row.names(invertebrate) <- invertebrate[,1]
invertebrate <- as.data.frame(invertebrate)
invertebrate <- invertebrate[-109,c(-14, -16:-19,-21: -23)]#take off  species that appeared in less than 3 brom + take off brom 72 
IDbis <- ID[-109,]
colnames(invertebrate)[1] <- "ID"
invertebrate <- merge(IDbis, invertebrate, by = "ID")

envir <- dplyr::select(rawdata2021, ID, treatment, N.brom, time, NL, dry.bromeliad.days, Vactual)
envir[,5:7] <- scale(envir[,5:7])

#create a df combining species and environemental data by ID to make sure invertebrate values are related to the right explanatory variables
mva <- merge(envir, invertebrate, by = "ID")
row.names(mva) <- mva[,1]

#Abundance boxplot per species
#mva2 <- mva[,c(1,9:23)]
#mva2 <- reshape2::melt(mva2, id = "ID")
#svg("sp_abund.svg")
#ggplot(mva2, aes(x = variable, y = value)) + 
#  geom_boxplot() + coord_flip() + xlab("")+ ylab("Abundance")
#dev.off()

mva <- mva[,c(-1)]

#create the mvabund object based only on species abundance 
inv_spp <- mvabund(mva[,7:20])

#check mean var in general 
svg("meanvar.svg", width = 5, height = 5)
mvabund::meanvar.plot(inv_spp, legend = TRUE)
dev.off()

#creating a df only with explanatory variables
mva <- mva[,c(-7:-20)]

#check mean var based on treatments
svg("meanvar_treatment.svg", width = 5, height = 5)
mvabund::meanvar.plot(inv_spp~ mva$treatment, legend = TRUE)
dev.off()

svg("meanvar_N.brom.svg", width = 5, height = 5)
mvabund::meanvar.plot(inv_spp~ mva$N.brom, legend = TRUE)
dev.off()

svg("meanvar_time.svg", width = 5, height = 5)
mvabund::meanvar.plot(inv_spp~ mva$time, legend = TRUE)
dev.off()

#Using the traitglm function without adding any trait data to plot relationship between envir and species 
ftspp1=traitglm(inv_spp,mva[,c(1:5)],method="glm1path")
svg("sppVSenvir.svg")
  a = max(abs(ftspp1$fourth.corner) )
  colort = colorRampPalette(c("#0072B2","white", "#D55E00")) 
  plot.spp = lattice::levelplot(t(as.matrix(ftspp1$fourth.corner)), xlab="Environmental Variables",
  ylab="Species traits", col.regions=colort(100), at=seq(-a, a, length=100),
  scales = list( x= list(rot = 45)))
print(plot.spp)
dev.off

```

Questions:
1) Does treatment have an effect on assemblage ? Discrete explanatory variables
2) What are the indicator species? 
3) Which environmental variables are most strongly associated with an assemblage ? Continuous explanatory variables

Manyglm - model construction and selection based on best AIC
```{r}
#NULL model 
mod0 <- manyglm(inv_spp ~ 1, family = "negative binomial", data = mva)
AIC0 <- mod0$AICsum


##With 3 interactions
mod1 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time + NL + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC1 <- mod1$AICsum

mod2 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time + NL, family = "negative binomial", data = mva)
AIC2 <- mod2$AICsum

mod3 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC3 <- mod3$AICsum

mod4 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time + Vactual, family = "negative binomial", data = mva)
AIC4 <- mod4$AICsum

mod5 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time + NL + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC5 <- mod5$AICsum

mod6 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time + NL + Vactual, family = "negative binomial", data = mva)
AIC6 <- mod6$AICsum

mod7 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC7 <- mod7$AICsum

mod8 <- manyglm(inv_spp ~ treatment*N.brom + treatment*time + N.brom*time, family = "negative binomial", data = mva)
AIC8 <- mod8$AICsum


#treatment*Nbrom
mod9 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + NL + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC9 <- mod9$AICsum

mod10 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + NL, family = "negative binomial", data = mva)
AIC10 <- mod10$AICsum

mod11 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC11 <- mod11$AICsum

mod12 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + Vactual, family = "negative binomial", data = mva)
AIC12 <- mod12$AICsum

mod13 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + NL + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC13 <- mod13$AICsum

mod14 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + NL + Vactual, family = "negative binomial", data = mva)
AIC14 <- mod14$AICsum

mod15 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC15 <- mod15$AICsum

mod16 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom, family = "negative binomial", data = mva)
AIC16 <- mod16$AICsum


#treatment*time
mod17 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + NL + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC17 <- mod17$AICsum

mod18 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + NL, family = "negative binomial", data = mva)
AIC18 <- mod18$AICsum

mod19 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC19 <- mod19$AICsum

mod20 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + Vactual, family = "negative binomial", data = mva)
AIC20 <- mod20$AICsum

mod21 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + NL + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC21 <- mod21$AICsum

mod22 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + NL + Vactual, family = "negative binomial", data = mva)
AIC22 <- mod22$AICsum

mod23 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC23 <- mod23$AICsum

mod24 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time, family = "negative binomial", data = mva)
AIC24 <- mod24$AICsum


#Time*Nbrom
mod25 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time + NL + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC25 <- mod25$AICsum

mod26 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time + NL, family = "negative binomial", data = mva)
AIC26 <- mod26$AICsum

mod27 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC27 <- mod27$AICsum

mod28 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time + Vactual, family = "negative binomial", data = mva)
AIC28 <- mod28$AICsum

mod29 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time + NL + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC29 <- mod29$AICsum

mod30 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time + NL + Vactual, family = "negative binomial", data = mva)
AIC30 <- mod30$AICsum

mod31 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC31 <- mod31$AICsum

mod32 <- manyglm(inv_spp ~ treatment + N.brom + time + N.brom:time, family = "negative binomial", data = mva)
AIC32 <- mod32$AICsum


#treatment*Nbrom & treatment*time
mod33 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time + NL + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC33 <- mod33$AICsum

mod34 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time + NL, family = "negative binomial", data = mva)
AIC34<- mod34$AICsum

mod35 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC35 <- mod35$AICsum

mod36 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time + Vactual, family = "negative binomial", data = mva)
AIC36 <- mod36$AICsum

mod37 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time + NL + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC37 <- mod37$AICsum

mod38 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time + NL + Vactual, family = "negative binomial", data = mva)
AIC38 <- mod38$AICsum

mod39 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC39 <- mod39$AICsum

mod40 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + treatment:time, family = "negative binomial", data = mva)
AIC40 <- mod40$AICsum


#treatment*Nbrom & Nbrom*time
mod41 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time + NL + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC41 <- mod41$AICsum

mod42 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time + NL, family = "negative binomial", data = mva)
AIC42<- mod42$AICsum

mod43 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC43 <- mod43$AICsum

mod44 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time + Vactual, family = "negative binomial", data = mva)
AIC44 <- mod44$AICsum

mod45 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time + NL + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC45 <- mod45$AICsum

mod46 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time + NL + Vactual, family = "negative binomial", data = mva)
AIC46 <- mod46$AICsum

mod47 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC47 <- mod47$AICsum

mod48 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:N.brom + N.brom:time, family = "negative binomial", data = mva)
AIC48 <- mod48$AICsum


#treatment*time & Nbrom*time
mod49 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time + NL + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC49 <- mod49$AICsum

mod50 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time + NL, family = "negative binomial", data = mva)
AIC50<- mod50$AICsum

mod51 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC51 <- mod51$AICsum

mod52 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time + Vactual, family = "negative binomial", data = mva)
AIC52 <- mod52$AICsum

mod53 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time + NL + dry.bromeliad.days, family = "negative binomial", data = mva)
AIC53 <- mod53$AICsum

mod54 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time + NL + Vactual, family = "negative binomial", data = mva)
AIC54 <- mod54$AICsum

mod55 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
AIC55 <- mod55$AICsum

mod56 <- manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + N.brom:time, family = "negative binomial", data = mva)
AIC56 <- mod56$AICsum


#Choosing best model with the AICsum by hand 

name <- c("mod0","mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8", "mod9", "mod10", "mod11", "mod12", "mod13", "mod14", "mod15", "mod16", "mod17", 
          "mod18","mod19", "mod20","mod21", "mod22", "mod23", "mod24", "mod25", "mod26", "mod27", "mod28", "mod29", "mod30", "mod31", "mod32", "mod33", "mod34", "mod35", "mod36", "mod37", "mod38", "mod39", "mod40", "mod41", "mod42", "mod43", "mod44", "mod45", "mod46", "mod47", "mod48", "mod49", "mod50", "mod51", "mod52", "mod53", "mod54", "mod55", "mod56")


AICclass <- c(AIC0, AIC1, AIC2, AIC3, AIC4, AIC5, AIC6, AIC7, AIC8, AIC9, AIC10, AIC11, AIC12, AIC13, AIC14, AIC15, AIC16, AIC17, AIC18, AIC19, AIC20, AIC21,
              AIC22, AIC23, AIC24, AIC25, AIC26, AIC27, AIC28, AIC29, AIC30, AIC31, AIC32, AIC33, AIC34, AIC35, AIC36, AIC37, AIC38, AIC39, AIC40, AIC41, AIC42, AIC43, AIC44, AIC45, AIC46, AIC47, AIC48, AIC49, AIC50, AIC51, AIC52, AIC53, AIC54, AIC55, AIC56)
AICclass <- cbind(name, AICclass)
AICclass <- as.data.frame(AICclass)

rm("mod0","mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8", "mod9", "mod10", "mod11", "mod12", "mod13", "mod14", "mod15", "mod16", "mod17", 
          "mod18","mod19", "mod20","mod21", "mod22", "mod23", "mod24",  "mod25", "mod26", "mod27", "mod28", "mod29", "mod30", "mod31", "mod32", "mod33", "mod34", "mod35", "mod36", "mod37", "mod38", "mod39", "mod40", "mod41", "mod42", "mod43", "mod44", "mod45", "mod46", "mod47", "mod48", "mod49", "mod50", "mod51", "mod52", "mod53", "mod54", "mod55", "mod56")
rm(AIC0, AIC1, AIC2, AIC3, AIC4, AIC5, AIC6, AIC7, AIC8, AIC9, AIC10, AIC11, AIC12, AIC13, AIC14, AIC15, AIC16, AIC17, AIC18, AIC19, AIC20, AIC21,
              AIC22, AIC23, AIC24, AIC25, AIC26, AIC27, AIC28, AIC29, AIC30, AIC31, AIC32, AIC33, AIC34, AIC35, AIC36, AIC37, AIC38, AIC39, AIC40, AIC41, AIC42, AIC43, AIC44, AIC45, AIC46, AIC47, AIC48, AIC49, AIC50, AIC51, AIC52, AIC53, AIC54, AIC55, AIC56)
rm(AICclass, name)

final_mod <-manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)
#residuals should look like a flat band and if model is appropriate, should have a standard normal distribution meaning 95% of residuals #should be between -2 and 2. 
plot.manyglm(final_mod) #OK
```

LR test and anova
```{r}

#Check every variable of final model with anova and Likelihood-ratio test
test1 <-manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + dry.bromeliad.days, family = "negative binomial", data = mva)

anova.manyglm(final_mod,test1,test = 'LR') #OK

test2 <-manyglm(inv_spp ~ treatment + N.brom + time + treatment:time + Vactual, family = "negative binomial", data = mva)

anova.manyglm(final_mod,test2,test = 'LR') #OK

test3 <- manyglm(inv_spp ~ treatment + N.brom + time + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)

anova.manyglm(final_mod,test3,test = 'LR') #OK

test4 <- manyglm(inv_spp ~ treatment + N.brom + dry.bromeliad.days + Vactual, family = "negative binomial", data = mva)

anova.manyglm(final_mod,test4,test = 'LR') #OK

test5 <-manyglm(inv_spp ~ N.brom + time  + Vactual + dry.bromeliad.days, family = "negative binomial", data = mva)

anova.manyglm(final_mod,test5,test = 'LR') #OK

test6 <-manyglm(inv_spp ~ treatment + time + treatment:time + Vactual + dry.bromeliad.days, family = "negative binomial", data = mva)

anova.manyglm(final_mod,test6,test = 'LR') #OK


rm(test1, test2, test3, test4, test5, test6)

#save final model
dfmvabund <- summary.manyglm(final_mod)
estimates <- dfmvabund$coefficients
estimates <- as.data.frame(estimates)
openxlsx::write.xlsx(estimates, file = "mvabund.xlsx", quote = FALSE,row.Names = T, col.Names = TRUE, rowNames = TRUE)

coef_per_sp<-as.data.frame(final_mod$coefficients)
sd_per_sp<-as.data.frame(final_mod$stderr.coefficients)

openxlsx::write.xlsx(x = signif(coef_per_sp,digits=2), file = "coef-per_sp.xlsx",
           rowNames = TRUE)

openxlsx::write.xlsx(x = signif(sd_per_sp,digits=2), file = "SD_per_sp.xlsx",
           rowNames = TRUE)


#save anova
anov_unadjusted <- anova.manyglm(final_mod, p.uni = "unadjusted",  nBoot=6000, test="LR")
anovdf_unadjusted <- anov_unadjusted$table
openxlsx::write.xlsx(anovdf_unadjusted, file = "anovmvabund_unadjusted.xlsx", quote = FALSE,row.Names = T, col.Names = TRUE, rowNames = TRUE)

coef_per_sp<-anov_unadjusted$coefficients
pval_per_sp<-anov_unadjusted$uni.p

pval_per_sp<-as.data.frame(anov_unadjusted$uni.p)
openxlsx::write.xlsx(x = signif(pval_per_sp,digits=2), file = "Pval_per_sp_unadjusted.xlsx",
          rowNames = TRUE)

coef_per_sp<-as.data.frame(anov_unadjusted$coefficients)
openxlsx::write.xlsx(x = signif(coef_per_sp,digits=2), file = "coef-per_sp.xlsx",
           rowNames = TRUE)


rm(coef_per_sp, sd_per_sp, pval_per_sp, dfmvabund, estimates, final_mod, anov_adjusted, anov_unadjusted, anovdf_adjusted, anovdf_unadjusted, mva, inv_spp, invertebrate, envir)

```


#### III.3) Invertebrate species richness and FFG
Species richness
```{r}
spe_rich <- rawdata2021

density2 <- read.table("C:/Users/mseguigne/Desktop/Resilience_Task 3/Resilience_Task3_R/inv_by_species.csv", header = FALSE, sep= ";", encoding="UTF-8")
colnames(density2) <- density2[1,]
density2 <- density2[-1,c(-1, -111)] #take off also brom 72
density2[,c(2:144)] <- lapply(density2[,c(2:144)], as.numeric)
density2 <- t(density2)
colnames(density2) <- density2[1,]
density2 <- density2[-1,]
density2 <- as.data.frame(density2)
density2[,c(1:22)] <- lapply(density2[,c(1:22)], as.numeric)
density2 <- cbind(ID, density2)
spe_rich <- merge(density2, spe_rich, by = "ID")

spe_rich <- spe_rich %>% 
  mutate(RS = rowSums(.[2:(23)] > 0)) %>% 
  group_by(ID) 

mod <- lm(RS ~ treatment+ time + N.brom + dry.bromeliad.days + NL + Vactual+ treatment*N.brom + treatment*time + N.brom*time,  data = spe_rich)
summary(mod)
step(mod)

mod2 <- lm(formula = RS ~ treatment + time + dry.bromeliad.days + Vactual + treatment:time, data = spe_rich)
summary(mod2)
plot(mod2)
anova(mod, mod2)
AIC(mod, mod2)

```

Shredders ~ .
```{r}
shred <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, shredder)
#see relationships
ggpairs(shred, aes(color = N.brom))

#see distribution
plotNormalHistogram(shred$shredder)
qqnorm(shred$shredder)
qqline(shred$shredder)

#Stepwise
mod1 <- lm(log(shredder+1) ~ treatment + time + N.brom + dry.bromeliad.days + NL + Vactual + treatment*N.brom + treatment*time + N.brom*time, data = shred)

summary(step(mod1, direction = "both"))

#Final mod 
mod2 <- lm(log(shredder + 1) ~ treatment + time, data = shred)
anova(mod2, mod1)
AIC(mod2, mod1)

check_model(mod2)
shapiro.test(mod2$residuals) 
lmtest::bptest(mod2) 
car::durbinWatsonTest(mod2) 
anova(mod2)
summary(mod2)
rm(mod2, mod1)
```
Predators ~ . 
```{r}
pred <- dplyr::select(rawdata2021, ID, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, predator)
#see relationships
ggpairs(pred, aes(color = N.brom))

#see distribution
plotNormalHistogram(pred$predator)
qqnorm(pred$predator)
qqline(pred$predator)

#Stepwise
mod1 <- lm(log(predator+1) ~ treatment + time + N.brom + dry.bromeliad.days + NL + Vactual + treatment*N.brom + treatment*time + N.brom*time, data = pred)

summary(step(mod1, direction = "both"))


mod2 <- lm(log(predator + 1) ~ treatment + time + N.brom + dry.bromeliad.days + NL + Vactual + treatment:N.brom + treatment:time, data = pred)
anova(mod2, mod1)
AIC(mod2, mod1)

check_model(mod2)
shapiro.test(mod2$residuals) 
lmtest::bptest(mod2) 
car::durbinWatsonTest(mod2) 
anova(mod2)
summary(mod2)
rm(mod2, mod1)
```
Scrapers ~ . 
```{r}
scrap <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, scraper)
#see relationships
ggpairs(scrap, aes(color = N.brom))

#see distribution
plotNormalHistogram(scrap$scraper)
qqnorm(scrap$scraper)
qqline(scrap$scraper)

#Stepwise
mod1 <- lm(log(scraper+1) ~ treatment + time + N.brom + dry.bromeliad.days + NL + Vactual + treatment*N.brom + treatment*time + N.brom*time, data = scrap)

summary(step(mod1, direction = "both"))

mod2 <- lm(log(scraper + 1) ~ dry.bromeliad.days + Vactual, data = scrap)
anova(mod2, mod1)
AIC(mod2, mod1)

check_model(mod2)
shapiro.test(mod2$residuals) 
lmtest::bptest(mod2) 
car::durbinWatsonTest(mod2) 
anova(mod2)
summary(mod2)
rm(mod2, mod1)
```
Collectors ~ . 
```{r}
collec <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, collector)
#see relationships
ggpairs(collec, aes(color = N.brom))

#see distribution
plotNormalHistogram(collec$collector)
qqnorm(collec$collector)
qqline(collec$collector)

#Stepwise
mod1 <- lm(log(collector+1) ~ treatment + time + N.brom + dry.bromeliad.days + NL + Vactual + treatment*N.brom + treatment*time + N.brom*time, data = collec)

summary(step(mod1, direction = "both"))

mod2 <- lm(log(collector + 1) ~ treatment + time + N.brom + Vactual + treatment:N.brom, data = collec)
anova(mod2, mod1)
AIC(mod2, mod1)

check_model(mod2)
shapiro.test(mod2$residuals) 
lmtest::bptest(mod2) 
car::durbinWatsonTest(mod2) 
anova(mod2)
summary(mod2)
rm(mod2, mod1)
```
Filter-feeders ~ . 
```{r}
fil <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, filter)
#see relationships
ggpairs(fil, aes(color = N.brom))

#see distribution
plotNormalHistogram(fil$filter)
qqnorm(fil$filter)
qqline(fil$filter)

#Stepwise
mod1 <- lm(log(filter+1) ~ treatment + time + N.brom + dry.bromeliad.days + NL + Vactual + treatment*N.brom + treatment*time + N.brom*time, data = fil)

summary(step(mod1, direction = "both"))

mod2 <- lm(log(filter + 1) ~ treatment + time + Vactual + treatment:time, data = fil)
anova(mod2, mod1)
AIC(mod2, mod1)

check_model(mod2)
shapiro.test(mod2$residuals) 
lmtest::bptest(mod2) 
car::durbinWatsonTest(mod2) 
anova(mod2)
summary(mod2)
rm(mod2, mod1)
```
Figure 1 
```{r}
cbPalette <- c("#56B4E9", "#E69F00")
shred <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, shredder)
pred <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, predator)
scrap <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, scraper)
collec <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, collector)
fil <- dplyr::select(rawdata2021, N.brom, treatment, time, water.depth.T0, Vactual, NL, Diam, dry.bromeliad.days, FPOM, filter)

#Individual plots
predator <- ggplot(pred,aes(y=predator,x=time, col = treatment))+
  facet_grid( ~ N.brom)+
  geom_point()+
  geom_boxplot(size = 0.8) +
  facet_wrap(~N.brom)+  
  theme(axis.title.y = element_blank(), axis.title.x = element_blank(), legend.position = "none", plot.title = element_text(face = "bold"),         axis.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 14))  + ggtitle('(a) Predators') + 
  scale_colour_manual(values=cbPalette)

shredder <- ggplot(shred,aes(y=shredder,x=time, col = treatment))+
  facet_grid( ~ N.brom)+
  geom_point()+
  geom_boxplot(size = 0.8) +
  facet_wrap(~N.brom)+  
  theme(axis.title.y = element_blank(), axis.title.x = element_blank(), legend.position = "none", plot.title = element_text(face = "bold"),         axis.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 14))  + ggtitle('(b) Shredders') + 
  scale_colour_manual(values=cbPalette)

scraper <- ggplot(scrap,aes(y=scraper,x=time, col = treatment))+
  facet_grid( ~ N.brom)+
  geom_point()+
  geom_boxplot(size = 0.8) +
  facet_wrap(~N.brom)+  
  theme(axis.title.y = element_blank(), axis.title.x = element_blank(), legend.position = "none", plot.title = element_text(face = "bold"),         axis.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 14))  + ggtitle('(c) Scrapers') + 
  scale_colour_manual(values=cbPalette)

col <- ggplot(collec,aes(y=collector,x=time, col = treatment))+
  facet_grid( ~ N.brom)+
  geom_point()+
  geom_boxplot(size = 0.8) +
  facet_wrap(~N.brom)+  
  theme(axis.title.y = element_blank(), axis.title.x = element_blank(), legend.position = "none", plot.title = element_text(face = "bold"),
        axis.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 14))  + ggtitle('(d) Collectors') + 
  scale_colour_manual(values=cbPalette)

filter <- ggplot(fil,aes(y=filter,x=time, col = treatment))+
  facet_grid( ~ N.brom)+
  geom_point()+
  geom_boxplot(size = 0.8) +
  facet_wrap(~N.brom)+  
  theme(legend.position = "none",axis.title.y = element_blank(), axis.title.x = element_blank(), 
        plot.title = element_text(face = "bold"), legend.title = element_text(face = "bold"), axis.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 14), legend.text = element_text(size = 14))  + ggtitle('(e) Filter-feeders') + labs(col = "Treatment") +
  scale_colour_manual(values=cbPalette) 


#Create function to extract legend 
get_only_legend <- function(plot) {
  plot_table <- ggplot_gtable(ggplot_build(plot))
  legend_plot <- which(sapply(plot_table$grobs, function(x) x$name) == "guide-box")
  legend <- plot_table$grobs[[legend_plot]]
  return(legend)
}

#create the plot used to extract legend
legend <- ggplot(fil,aes(y=filter,x=time, col = treatment))+
  facet_grid( ~ N.brom)+
  geom_point()+
  geom_boxplot(size = 0.8) +
  facet_wrap(~N.brom)+  
  theme(axis.title.y = element_blank(), axis.title.x = element_blank(), legend.position = "right",
        plot.title = element_text(face = "bold", size = 12), legend.title = element_text(face = "bold", size = 16), legend.text = element_text(size = 14))  + ggtitle('(e) Filter-feeders') + 
  labs(col = "Treatment") +
  scale_colour_manual(values=cbPalette) 
                           
#Extract legend
legend <- get_only_legend(legend)

#create plot
p <- cowplot::plot_grid(predator, shredder, scraper, col, filter, legend, align = "V", nrow = 2, ncol = 3) 

#Add common labbels 
y <-  grid::textGrob("FFG biomass (mg)", 
                   gp= grid::gpar(fontface="bold", fontsize = 16), rot=90) 
x <-  grid::textGrob("Time after rewetting (in days)",gp= grid::gpar(fontface="bold", fontsize = 16))

p <- gridExtra::grid.arrange(gridExtra::arrangeGrob(p, left = y, bottom = x))
                             
ggsave("Fig1.tiff", p, width = 35, height = 30, units = "cm")
rm(predator, shredder, scraper, col, filter, legend, get_only_legend, p, y, x, cbPalette, pred, shred, scrap, collec, fil)
```

#### III.4) Ecosystem functioning
```{r}
rawdataSEM <- rawdata2021
rawdataSEM$treatment <- as.character(rawdataSEM$treatment)
rawdataSEM$treatment[rawdataSEM$treatment == "drought"] <- "1"
rawdataSEM$treatment[rawdataSEM$treatment == "control"] <- "0"
rawdataSEM$treatment <- as.numeric(rawdataSEM$treatment)
rawdataSEM$time <- as.factor(as.character(rawdataSEM$time))
rawdataSEM$N.brom <- as.factor(as.character(rawdataSEM$N.brom))
rawdataSEM$detritivores <- rawdataSEM$shredder + rawdataSEM$scraper
rawdataSEM <- dplyr::select(rawdataSEM, N.brom, treatment, time, predator, detritivores, bact_biomass, Ergosterol, rate_total, NL, dry.bromeliad.days, Vactual)
rawdataSEM[,9:11] <- scale(rawdataSEM[,9:11])
```

T7
```{r}
rawdataSEM_7 <- subset(rawdataSEM, time == "7")
rawdataSEM_7 <- tidyr::drop_na(rawdataSEM_7)

#detritivores
detri1 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1), data = rawdataSEM_7)
detri2 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
detri3 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL, data = rawdataSEM_7)
detri4 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + dry.bromeliad.days, data = rawdataSEM_7)
detri5 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + Vactual, data = rawdataSEM_7)
detri6 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + dry.bromeliad.days, data = rawdataSEM_7)
detri7 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
detri8 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + Vactual, data = rawdataSEM_7)

mod <- list(detri1, detri2, detri3, detri4, detri5, detri6, detri7, detri8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(detri5)
summary(detri5)
rm(detri1, detri2, detri3, detri4, detri6, detri7, detri8, mod, selection, name)


#Predators
pred1 <- lm(log(predator +1) ~ treatment + N.brom, data = rawdataSEM_7)
pred2 <- lm(log(predator +1) ~ treatment + N.brom + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
pred3 <- lm(log(predator +1) ~ treatment + N.brom + NL, data = rawdataSEM_7)
pred4 <- lm(log(predator +1) ~ treatment + N.brom + dry.bromeliad.days, data = rawdataSEM_7)
pred5 <- lm(log(predator +1) ~ treatment + N.brom + Vactual, data = rawdataSEM_7)
pred6 <- lm(log(predator +1) ~ treatment + N.brom + NL + dry.bromeliad.days, data = rawdataSEM_7)
pred7 <- lm(log(predator +1) ~ treatment + N.brom + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
pred8 <- lm(log(predator +1) ~ treatment + N.brom + NL + Vactual, data = rawdataSEM_7)

mod <- list(pred1, pred2, pred3, pred4, pred5, pred6, pred7, pred8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(pred8)
summary(pred8)
rm(pred1, pred2, pred3, pred4, pred5, pred6, pred7, mod, selection, name)

#Bacteria
bact1 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1), data = rawdataSEM_7)
bact2 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
bact3 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL, data = rawdataSEM_7)
bact4 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days, data = rawdataSEM_7)
bact5 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + Vactual, data = rawdataSEM_7)
bact6 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days, data = rawdataSEM_7)
bact7 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
bact8 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + Vactual, data = rawdataSEM_7)

mod <- list(bact1, bact2, bact3, bact4, bact5, bact6, bact7, bact8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(bact1)
summary(bact4)
rm(bact1, bact2, bact3, bact5, bact6, bact7, bact8, mod, selection, name)

#Fungi
ergo1 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1), data = rawdataSEM_7)
ergo2 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
ergo3 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL, data = rawdataSEM_7)
ergo4 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days, data = rawdataSEM_7)
ergo5 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + Vactual, data = rawdataSEM_7)
ergo6 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days, data = rawdataSEM_7)
ergo7 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days + Vactual, data = rawdataSEM_7)
ergo8 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + Vactual, data = rawdataSEM_7)

mod <- list(ergo1, ergo2, ergo3, ergo4, ergo5, ergo6, ergo7, ergo8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(ergo1)
summary(ergo1)
rm(ergo2, ergo3, ergo4, ergo5, ergo6, ergo7, ergo8, mod, selection, name)

#Decomposition 
decomp1 <- lm(log(rate_total +1) ~ log(detritivores +1) + log(bact_biomass+1) + log(Ergosterol+1), data = rawdataSEM_7)

autoplot(decomp1)
summary(decomp1)


T7 <- psem(detri5, pred8, bact4, ergo1, decomp1,
                         Ergosterol %~~%bact_biomass)

T7_sum <- summary(T7)
T7_coef <- as.data.frame(T7_sum$coefficients)

rm(detri5, pred8, bact4, ergo1, decomp1, T7, T7_sum, T7_coef, rawdataSEM_7)
```

T15
```{r}
rawdataSEM_15 <- subset(rawdataSEM, time == "15")
rawdataSEM_15 <- tidyr::drop_na(rawdataSEM_15)

#detritivores
detri1 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1), data = rawdataSEM_15)
detri2 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
detri3 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL, data = rawdataSEM_15)
detri4 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + dry.bromeliad.days, data = rawdataSEM_15)
detri5 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + Vactual, data = rawdataSEM_15)
detri6 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + dry.bromeliad.days, data = rawdataSEM_15)
detri7 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
detri8 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + Vactual, data = rawdataSEM_15)

mod <- list(detri1, detri2, detri3, detri4, detri5, detri6, detri7, detri8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(detri4)
summary(detri4)
rm(detri1, detri2, detri3, detri5, detri6, detri7, detri8, mod, selection, name)


#Predators
pred1 <- lm(log(predator +1) ~ treatment + N.brom, data = rawdataSEM_15)
pred2 <- lm(log(predator +1) ~ treatment + N.brom + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
pred3 <- lm(log(predator +1) ~ treatment + N.brom + NL, data = rawdataSEM_15)
pred4 <- lm(log(predator +1) ~ treatment + N.brom + dry.bromeliad.days, data = rawdataSEM_15)
pred5 <- lm(log(predator +1) ~ treatment + N.brom + Vactual, data = rawdataSEM_15)
pred6 <- lm(log(predator +1) ~ treatment + N.brom + NL + dry.bromeliad.days, data = rawdataSEM_15)
pred7 <- lm(log(predator +1) ~ treatment + N.brom + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
pred8 <- lm(log(predator +1) ~ treatment + N.brom + NL + Vactual, data = rawdataSEM_15)

mod <- list(pred1, pred2, pred3, pred4, pred5, pred6, pred7, pred8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(pred5)
summary(pred5)
rm(pred1, pred2, pred3, pred4, pred6, pred7, pred8, mod, selection, name)

#Bacteria
bact1 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1), data = rawdataSEM_15)
bact2 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
bact3 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL, data = rawdataSEM_15)
bact4 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days, data = rawdataSEM_15)
bact5 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + Vactual, data = rawdataSEM_15)
bact6 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days, data = rawdataSEM_15)
bact7 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
bact8 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + Vactual, data = rawdataSEM_15)

mod <- list(bact1, bact2, bact3, bact4, bact5, bact6, bact7, bact8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(bact5)
summary(bact5)
rm(bact1, bact2, bact3, bact4, bact6, bact7, bact8, mod, selection, name)

#Fungi
ergo1 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1), data = rawdataSEM_15)
ergo2 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
ergo3 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL, data = rawdataSEM_15)
ergo4 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days, data = rawdataSEM_15)
ergo5 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + Vactual, data = rawdataSEM_15)
ergo6 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days, data = rawdataSEM_15)
ergo7 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days + Vactual, data = rawdataSEM_15)
ergo8 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + Vactual, data = rawdataSEM_15)

mod <- list(ergo1, ergo2, ergo3, ergo4, ergo5, ergo6, ergo7, ergo8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(ergo1)
summary(ergo1)
rm(ergo2, ergo3, ergo4, ergo5, ergo6, ergo7, ergo8, mod, selection, name)

#Decomposition 
decomp1 <- lm(log(rate_total +1) ~ log(detritivores +1) + log(bact_biomass+1) + log(Ergosterol+1), data = rawdataSEM_15)

autoplot(decomp1)
summary(decomp1)

T15 <- piecewiseSEM::psem(detri4, pred5, bact5, ergo1, decomp1,
                         Ergosterol %~~%bact_biomass)
T15_sum <- summary(T15)
T15_coef <- as.data.frame(T15_sum$coefficients)

emmeans::emmeans(pred5, pairwise ~ N.brom)

rm(detri4, pred5, bact5, ergo1, decomp1, T15, T15_sum, T15_coef, rawdataSEM_15)
```

T60
```{r}
rawdataSEM_60 <- subset(rawdataSEM, time == "60")
rawdataSEM_60 <- tidyr::drop_na(rawdataSEM_60)

#detritivores
detri1 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1), data = rawdataSEM_60)
detri2 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
detri3 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL, data = rawdataSEM_60)
detri4 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + dry.bromeliad.days, data = rawdataSEM_60)
detri5 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + Vactual, data = rawdataSEM_60)
detri6 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + dry.bromeliad.days, data = rawdataSEM_60)
detri7 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
detri8 <- lm(log(detritivores +1) ~ treatment + N.brom + log(predator+1) + NL + Vactual, data = rawdataSEM_60)

mod <- list(detri1, detri2, detri3, detri4, detri5, detri6, detri7, detri8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(detri4)
summary(detri4)
rm(detri1, detri2, detri3, detri5, detri6, detri7, detri8, mod, selection, name)


#Predators
pred1 <- lm(log(predator +1) ~ treatment + N.brom, data = rawdataSEM_60)
pred2 <- lm(log(predator +1) ~ treatment + N.brom + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
pred3 <- lm(log(predator +1) ~ treatment + N.brom + NL, data = rawdataSEM_60)
pred4 <- lm(log(predator +1) ~ treatment + N.brom + dry.bromeliad.days, data = rawdataSEM_60)
pred5 <- lm(log(predator +1) ~ treatment + N.brom + Vactual, data = rawdataSEM_60)
pred6 <- lm(log(predator +1) ~ treatment + N.brom + NL + dry.bromeliad.days, data = rawdataSEM_60)
pred7 <- lm(log(predator +1) ~ treatment + N.brom + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
pred8 <- lm(log(predator +1) ~ treatment + N.brom + NL + Vactual, data = rawdataSEM_60)

mod <- list(pred1, pred2, pred3, pred4, pred5, pred6, pred7, pred8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(pred7)
summary(pred7)
rm(pred1, pred2, pred3, pred4, pred5, pred6,  pred8, mod, selection, name)

#Bacteria
bact1 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1), data = rawdataSEM_60)
bact2 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
bact3 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL, data = rawdataSEM_60)
bact4 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days, data = rawdataSEM_60)
bact5 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + Vactual, data = rawdataSEM_60)
bact6 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days, data = rawdataSEM_60)
bact7 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
bact8 <- lm(log(bact_biomass +1) ~ treatment + N.brom + log(detritivores + 1) + NL + Vactual, data = rawdataSEM_60)

mod <- list(bact1, bact2, bact3, bact4, bact5, bact6, bact7, bact8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(bact1)
summary(bact1)
rm( bact2, bact3, bact4, bact5, bact6, bact7, bact8, mod, selection, name)

#Fungi
ergo1 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1), data = rawdataSEM_60)
ergo2 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
ergo3 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL, data = rawdataSEM_60)
ergo4 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days, data = rawdataSEM_60)
ergo5 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + Vactual, data = rawdataSEM_60)
ergo6 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + dry.bromeliad.days, data = rawdataSEM_60)
ergo7 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + dry.bromeliad.days + Vactual, data = rawdataSEM_60)
ergo8 <- lm(log(Ergosterol +1) ~ treatment + N.brom + log(detritivores + 1) + NL + Vactual, data = rawdataSEM_60)

mod <- list(ergo1, ergo2, ergo3, ergo4, ergo5, ergo6, ergo7, ergo8)
name <- c("mod1", "mod2","mod3", "mod4", "mod5", "mod6", "mod7", "mod8")
selection <- AICcmodavg::aictab(mod, modnames = name)

autoplot(ergo8)
summary(ergo8)
rm(ergo1, ergo2, ergo3, ergo4, ergo5, ergo6, ergo7, mod, selection, name)

#Decomposition 
decomp1 <- lm(log(rate_total +1) ~ log(detritivores +1) + log(bact_biomass+1) + log(Ergosterol+1), data = rawdataSEM_60)

autoplot(decomp1)
summary(decomp1)

T60 <- piecewiseSEM::psem(detri4, pred7, bact1, ergo8, decomp1,
                         Ergosterol %~~%bact_biomass)
T60_sum <- summary(T60)
T60_coef <- as.data.frame(T60_sum$coefficients)


rm(detri4, pred7, bact1, ergo8, decomp1, T60, T60_sum, T60_coef, rawdataSEM_60)
```

