rm(list=ls())

library(foreign)
library(grid)
library(meta)

#Unadjusted:

meta<-read.table("Desktop/Meta_analysis_Unadjusted.txt", header=T)

Result<-matrix(NA, nrow(meta),7)

DF <- 12-1

for(i in 1:nrow(meta))
{
  Beta<-c(meta[i,2],meta[i,4],meta[i,6],meta[i,8],meta[i,10],meta[i,12],meta[i,14],meta[i,16],meta[i,18],meta[i,20],meta[i,22],meta[i,24])
  SE<-c(meta[i,3],meta[i,5],meta[i,7],meta[i,9],meta[i,11],meta[i,13],meta[i,15],meta[i,17],meta[i,19],meta[i,21],meta[i,23],meta[i,25])
  Out<-metagen(Beta,SE)

  Result[i,]<-c(Out$TE.fixed, Out$seTE.fixed, Out$pval.fixed, summary(Out)$I2$TE, pchisq(Out$Q,DF, lower.tail=F), Out$lower.fixed, Out$upper.fixed)
}

Result<-cbind(as.character(meta[,1]), Result)
colnames(Result)<-c("Metabolite","Meta_Beta","Meta_SE","Meta_Pvalue","I^2","Meta_Het_Pvalue","Lower 95% CI","Upper 95% CI")

write.table(Result, paste("Desktop/Results_meta_analysis_Unadjusted.txt",sep=""), col.names=T,row.names=F, sep="\t")

#Adjusted for 4 metabolites:

meta<-read.table("Desktop/Meta_analysis_Adjusted_4_metabolites.txt", header=T)

Result<-matrix(NA, nrow(meta),7)

DF <- 12-1

for(i in 1:nrow(meta))
{
  Beta<-c(meta[i,2],meta[i,4],meta[i,6],meta[i,8],meta[i,10],meta[i,12],meta[i,14],meta[i,16],meta[i,18],meta[i,20],meta[i,22],meta[i,24])
  SE<-c(meta[i,3],meta[i,5],meta[i,7],meta[i,9],meta[i,11],meta[i,13],meta[i,15],meta[i,17],meta[i,19],meta[i,21],meta[i,23],meta[i,25])
  Out<-metagen(Beta,SE)
  
  Result[i,]<-c(Out$TE.fixed, Out$seTE.fixed, Out$pval.fixed, summary(Out)$I2$TE, pchisq(Out$Q,DF, lower.tail=F), Out$lower.fixed, Out$upper.fixed)
}

Result<-cbind(as.character(meta[,1]), Result)
colnames(Result)<-c("Metabolite","Meta_Beta","Meta_SE","Meta_Pvalue","I^2","Meta_Het_Pvalue","Lower 95% CI","Upper 95% CI")

write.table(Result, paste("Desktop/Results_meta_analysis_Adjusted_4_metabolites.txt",sep=""), col.names=T,row.names=F, sep="\t")

#Adjusted for 14 metabolites (full model):

meta<-read.table("Desktop/Meta_analysis_Adjusted_Full_model.txt", header=T)

Result<-matrix(NA, nrow(meta),7)

DF <- 12-1

for(i in 1:nrow(meta))
{
  Beta<-c(meta[i,2],meta[i,4],meta[i,6],meta[i,8],meta[i,10],meta[i,12],meta[i,14],meta[i,16],meta[i,18],meta[i,20],meta[i,22],meta[i,24])
  SE<-c(meta[i,3],meta[i,5],meta[i,7],meta[i,9],meta[i,11],meta[i,13],meta[i,15],meta[i,17],meta[i,19],meta[i,21],meta[i,23],meta[i,25])
  Out<-metagen(Beta,SE)
  
  Result[i,]<-c(Out$TE.fixed, Out$seTE.fixed, Out$pval.fixed, summary(Out)$I2$TE, pchisq(Out$Q,DF, lower.tail=F), Out$lower.fixed, Out$upper.fixed)
}

Result<-cbind(as.character(meta[,1]), Result)
colnames(Result)<-c("Metabolite","Meta_Beta","Meta_SE","Meta_Pvalue","I^2","Meta_Het_Pvalue","Lower 95% CI","Upper 95% CI")

write.table(Result, paste("Desktop/Results_meta_analysis_Adjusted_Full_model.txt",sep=""), col.names=T,row.names=F, sep="\t")