#Bengtsson, Attermeyer, Catalán: "Interactive Effects on Organic Matter Processing
# from Soils to the Ocean: Are Priming Effects Relevant in Aquatic Ecosystems?"

#Meta-analysis priming effect

#Read file####
rm(list=ls(all=TRUE));graphics.off()
library(Rmisc); library(dplyr); library(reshape2); library(readr)
PE <- read_csv("N:/Dropbox/PRIMING/R_analysis/PE_metafinal.csv",        #change according to the address where data table is saved
col_types = cols(Nutrients = col_factor(levels = c("NO",
"YES")), `Position continuum` = col_factor(levels = c("0culture",
"3Lake", "1Stream", "2River", "4Marine")), material = col_factor(levels = c("water",
"sediment", "litter"))))
names(PE)[names(PE)== "Position continuum"]<- "Position_continuum"
names(PE)[names(PE)== "% PE"]<- "XPE"
PE$position <- as.numeric(substr(PE$Position_continuum,1,1))
PE$no_material <- as.numeric(PE$material)

PE_summ <- group_by(.data = PE,Citation, material,Position_continuum )
PE_summ <- summarise(PE_summ, SD_Control = sd(Control),
                        Control = mean(Control), SD_Treat =sd(Treat),
                        Treat= mean(Treat), n_Control = max (n_Cont),
                        n_Treat = max (n_Treat),n_rep_treat=mean(n_rep_Treat),
                        n_rep_Cont=mean(n_rep_Cont))
PE_summ$n_Control<-PE_summ$n_Control*PE_summ$n_rep_Cont
PE_summ$n_Treat<-PE_summ$n_Treat*PE_summ$n_rep_treat

##1.- Violin plots and summary by Position_ continuum and material####
#cut out outliers and culture study from data
PE_red<-PE[PE$Position_continuum!="0culture",]
PE_red<-PE_red[PE_red$XPE<700,]

library(vioplot); dev.off()
#palette(c("red","turquoise","green3","pink","purple2","salmon","firebrick","yellow","blue","cyan","orange","chartreuse4","black","grey75","darkgoldenrod2","indianred1","darkblue","green"))
library(RColorBrewer)
n <- 20
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
palette(col_vector)

par(mfrow=c(1,2))
plot(PE_red$XPE~jitter(PE_red$position), pch=20, ylim=c(-220, 220), xlim=c(0,5),type="n", xaxt="n", xlab="Aquatic ecosystem", ylab="Priming effect (%)")
vioplot(PE_red$XPE[PE_red$position=="1"],PE_red$XPE[PE_red$position=="2"],PE_red$XPE[PE_red$position=="3"],
        PE_red$XPE[PE_red$position=="4"],col="grey90", horizontal=FALSE, add=TRUE,lty=3, na.rm=T, drawRect=F)
points(PE_red$XPE~jitter(PE_red$position), pch=21, bg=(as.factor(PE_red$Citation)), ylim=c(-100, 200))
axis(side=1, at= c(1,2,3,4), labels=c("Stream", "River", "Lake" ,"Marine"))
abline(a=0, b=0, lty=2)
#plot percent priming by sample "material", i.e. water, sediment, biofilm etc.
plot(PE_red$XPE~jitter(PE_red$no_material), pch=20, ylim=c(-220, 220),xlim=c(0.5,5), type="n", xaxt="n", xlab="Sample material", ylab="Priming effect (%)")
vioplot(PE_red$XPE[PE_red$no_material=="1"],PE_red$XPE[PE_red$no_material=="2"],PE_red$XPE[PE_red$no_material=="3"],col="grey85", horizontal=FALSE,add=TRUE, lty=3, na.rm=T, drawRect=F)
points(PE_red$XPE~jitter(PE_red$no_material), pch=21, bg=(as.factor(PE_red$Citation)))
axis(side=1, at= c(1,2,3), labels=c("Water", "Sediment", "Litter"))
abline(a=0, b=0, lty=2)
par(xpd=NA)
legend(x=3.4,y=220, pch=20, col = 1:18,bty="n", legend=levels(as.factor(PE_red$Citation)), 
       cex=0.7, bg="white",inset=0,x.intersp=0.3)
#saved 7.25 x 10
dev.off()

#summary statistics by ecosystem
mat <- matrix(, nrow = 8, ncol = 7)
colnames(mat)<-c("Min.","1st Qu.","Median","Mean","3rd Qu.","Max.","Length")
rownames(mat)<-c("Stream","River","Lake","Marine","Water","Sediment","litter","Overall")
mat[1,1:6]<-summary((PE$XPE[PE$Position_continuum=="1Stream"]))[1:6]
mat[1,7]<-length(PE$XPE[PE$Position_continuum=="1Stream"])

mat[2,1:6]<-summary(PE$XPE[PE$Position_continuum=="2River"])[1:6]
mat[2,7]<-length(PE$XPE[PE$Position_continuum=="2River"])

mat[3,1:6]<-summary(PE$XPE[PE$Position_continuum=="3Lake"])[1:6]
mat[3,7]<-length(PE$XPE[PE$Position_continuum=="3Lake"])

mat[4,1:6]<-summary(PE$XPE[PE$Position_continuum=="4Marine"])[1:6]
mat[4,7]<-length(PE$XPE[PE$Position_continuum=="4Marine"])

#summary statistics by material
mat[5,1:6]<-summary(PE$XPE[(PE$material=="water")& (PE$Position_continuum!="0culture")]) #not including Bianchi et al. bacterial culture study
mat[5,7]<-length(PE$XPE[PE$material=="water"& PE$Citation!="Bianchi et al.2015"])

mat[6,1:6]<-summary(PE$XPE[PE$material=="sediment"])
mat[6,7]<-length(PE$XPE[PE$material=="sediment"])

mat[7,1:6]<-summary(PE$XPE[PE$material=="litter"])
mat[7,7]<-length(PE$XPE[PE$material=="litter"])

#summary overall
mat[8,1:6]<-summary(PE$XPE[PE$Position_continuum!="0culture"]) #not including Bianchi et al. bacterial culture study
mat[8,7]<-length(PE$XPE[PE$Position_continuum!="0culture"])

write.table(mat, "N:/Dropbox/PRIMING/R_analysis/Summary.txt", sep="\t")   #change to where you want it saved

##2.- Meta-analysis ##################
library (metafor)
dat<- PE_summ
dat_red<-dat[dat$Position_continuum !="0culture",]
###According to "Hillebrand and Gurevitch 2016, eLS" and based on the LRR:####
detach(dat);attach(dat)
dat$LRR<- log(Treat/Control) #log response ratio
dat$vlnR <- (SD_Treat^2/(n_Treat*Treat^2)+
               (SD_Control^2/(n_Control*Control^2))) #variance of the response
dat$wi <- 1/dat$vlnR #weigths
dat$wiLRR<-dat$LRR*dat$wi #weighted response
dat$SD<-sqrt(dat$vlnR); dat$CI.UB <- dat$LRR+1.96*dat$SD; dat$CI.LB<-dat$LRR-1.96*dat$SD
OE <- sum (dat$wiLRR, na.rm=T)/sum(dat$wi,na.rm=T) 
Ov <- 1/sum(dat$wi,na.rm=T); OSD<- sqrt(Ov);CI.UB <- OE+1.96*OSD;CI.LB<-OE-1.96*OSD;  
#Expressed in %PE:
round(c(estimate = (exp(OE)-1)*100, 
        SD = (exp(OSD)-1)*100, 
        ci.lb = (exp(CI.LB)-1)*100, 
        ci.ub = (exp(CI.UB)-1)*100), 4)


#differences across the continuum:
dat_red<-dat[dat$Position_continuum !="0culture",]
#dat_red<-dat_red[dat_red$Citation != "Hoffman and Briebler 2018",]
fit<-aov(LRR ~ Position_continuum,dat_red)
summary(fit)
TukeyHSD(fit,"Position_continuum" )
kruskal.test(LRR ~ Position_continuum,dat_red)

#forest plot:
library(ggplot2); library(rmeta)
par(mfrow=c(1,1))
metaplot(mn=dat$LRR,se=dat$SD,labels=dat$Citation,
         xlab="Log Response Ratio",boxsize=1,summn = OE)
points(x=OE, y=-19,pch=23, col="darkred",cex=2.5,bg="pink",lwd=2.5)



###Using package metafor, we get almost identical results:####
res <- rma(LRR, vlnR, data = dat)
res
confint(res)

#the result indicates that the estimated average LRR is equal to 0.1184 (95% CI: -0.0578 to 0.2946)
(exp(res$b)-1)*100; (exp(res$ci.lb)-1)*100;(exp(res$ci.ub)-1)*100 # so 1.12% [0.96, 1.31%], suggesting that the 
#possibility of having a PE effect is 12% larger than not having it. BUT 
#we cannot reject the null hypothesis of not having an effect (zval=1.3536, pval=0.1759).
#tau2 amount of heterogeneity in the true LRR
#I2 = how much of the variability in the effect size estimates can be attributed to heterogeneity among the true effects. 
#H2 = ratio of total variability to the amount of sampling variability. 
forest(res, slab = paste(dat$Citation,dat$Position_continuum, sep = ", "),
       xlim = c(-4, 4), at = log(c(0.25, 0.5, 1, 2,4)), 
       atransf = exp,cex = 0.95)
##test the influence of moderators:
dat$Position <-(dat$Position_continuum)
dat$material <-(dat$material)

res <- rma(dat$LRR, dat$vlnR, mods = cbind(dat$Position, dat$material), data = dat)
res
#So...neither position nor material have a significant influence on the LRR of PE. As 
# we cannot reject the H0 of B1=B2=0, the total amount of heterogeneity explained by these moderators is very low. 
#Moreover, the residual heterogeneity test is significant, thus other moderators not considered are influencing the priming effect value. 




##3.- Publication bias estimate:####
#Funnel plot (Bernd Weiss & jsakaluk in stackexchange.com):
#Store the meta-analytic estimate and its standard error from whatever model you run (substitute your own values)
estimate = OE
se = OSD

#Store a vector of values that spans the range from 0
#to the max value of impression (standard error) in your dataset.
#Make the increment (the final value) small enough (I choose 0.001)
#to ensure your whole range of data is captured
se.seq=seq(0, max(dat$SD,na.rm=T), 0.001)

#Now, compute vectors of the lower-limit and upper limit values for
#the 95% CI region, using the range of SE that you generated in the previous step, and the stored value of your meta-analytic estimate.
ll95 = estimate-(1.96*se.seq)
ul95 = estimate+(1.96*se.seq)

#You can do this for a 99% CI region too
ll99 = estimate-(3.29*se.seq)
ul99 = estimate+(3.29*se.seq)

#And finally, do the same thing except now calculating the confidence interval
#for your meta-analytic estimate based on the stored value of its standard error
meanll95 = estimate-(1.96*se)
meanul95 = estimate+(1.96*se)

#Now, smash all of those calculated values into one data frame (called 'dfCI').
#You might get a warning about '...row names were found from a short variable...'
#You can ignore it.
dfCI = data.frame(ll95, ul95, ll99, ul99, se.seq, estimate, meanll95, meanul95)

#Now we can actually make the funnel plot.
#Using your original data-frame, map standard error to your x-axis (for now) and Zr to your y-axis
fp = ggplot(aes(x = SD, y = LRR), data = dat) +
  #Add your data-points to the scatterplot
  geom_point(shape = 1) +
  #Give the x- and y- axes informative labels
  xlab('Standard Error') + ylab('LRR')+
  #Now using the 'dfCI' data-frame we created, plot dotted lines corresponding
  #to the lower and upper limits of your 95% CI region,
  #And dashed lines corresponding to your 99% CI region
  geom_line(aes(x = se.seq, y = ll95), linetype = 'dotted', data = dfCI) +
  geom_line(aes(x = se.seq, y = ul95), linetype = 'dotted', data = dfCI) +
  geom_line(aes(x = se.seq, y = ll99), linetype = 'dashed', data = dfCI) +
  geom_line(aes(x = se.seq, y = ul99), linetype = 'dashed', data = dfCI) +
  #Now plot dotted lines corresponding to the 95% CI of your meta-analytic estimate
  geom_segment(aes(x = min(se.seq), y = meanll95, xend = max(se.seq), yend = meanll95), linetype='dotted', data=dfCI) +
  geom_segment(aes(x = min(se.seq), y = meanul95, xend = max(se.seq), yend = meanul95), linetype='dotted', data=dfCI) +
  #Reverse the x-axis ordering (se) so that the tip of the funnel will appear
  #at the top of the figure once we swap the x- and y-axes...
  scale_x_reverse()+
  #Specify the range and interval for the tick-marks of the y-axis (Zr);
  #Choose values that work for you based on your data
  scale_y_continuous(breaks=seq(-1.25,2,0.5))+
  #And now we flip the axes so that SE is on y- and Zr is on x-
  coord_flip()+
  theme_bw()

#Call the pretty funnel plot
fp

#Saved 6x6

