Last updated: 2020-03-17

Checks: 6 0

Knit directory: m6AQTL_reproducibleDocument/

This reproducible R Markdown analysis was created with workflowr (version 1.3.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20200317) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Untracked files:
    Untracked:  analysis/Re-analysis_of_Wang_2015_cell.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


There are no past versions. Publish this analysis with wflow_publish() to start tracking its development.


library(MeRIPtools)
library(BSgenome.Hsapiens.UCSC.hg19)

LCLs <- readRDS( "~/m6AQTL/peakcalling/MeRIPtools/jointPeak_threshold5_MeRIP.RDS")
newLCLs <- LCLs

allChr.est <-   readRDS("~/m6AQTL/m6A_QTL_results/linear_model/m6AQTL.m6APeak_logOR_GC.IP.adjusted_qqnorm.15PCs.fastQTL.nominals.rds")
lead_m6AQTL <- readRDS("~/m6AQTL/m6A_QTL_results/linear_model/lead.m6AQTL.m6APeak_logOR_GC.IP.adjusted_qqnorm.15PCs.fastQTL.nominals.rds")

permutation_m6AQTL <-  readRDS("~/m6AQTL/m6A_QTL_results/linear_model/m6AQTL.m6APeak_logOR_GC.IP.adjusted_qqnorm.15PCs.fastQTL.permutations.rds")

reported_m6AQTL <- lead_m6AQTL[lead_m6AQTL$PEAK %in% permutation_m6AQTL[permutation_m6AQTL$qvalue<0.1,"PEAK"], ]
load("~/m6AQTL/m6AQTL_analysis/data/permutationData.RData")
m6Amonster::qqplot.pvalue(list("cis-test" = allChr.est$pvalue, "permutation1" = permutedRun1$pvalue,"permutation2" = permutedRun2$pvalue,"permutation3" = permutedRun3$pvalue,"permutation4" = permutedRun4$pvalue,"permutation5" = permutedRun5$pvalue), pointSize = 1.5,legendSize = 3)+theme(axis.title = element_text(size = 16,face = "bold"),axis.text =  element_text(size = 14,face = "bold"), legend.title = element_blank(),legend.text =  element_text(size = 14,face = "bold"),axis.line = element_line(size = 1) )+scale_color_manual(values = c("#000000", "#0072B2","#E69F00", "#56B4E9","#F0E442","#D55E00") )

Effect size distribution of m^6AQTL (ePeak level FDR10%)

cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

ggplot(data = reported_m6AQTL, aes(x = beta) )+geom_histogram(col=I("black"),bins = 100)+theme_bw()+theme(axis.title =  element_text(size = 20, face = "bold"),axis.text = element_text(size = 15, face = "bold", color = "black"),  axis.line = element_line(color = "black",size = 0.8), axis.ticks = element_line(color = "black",size = 0.8))+xlab("Effect sizes") 

Volcano plot

VolcData <- allChr.est[,c("beta","pvalue","qvalue")]
VolcData$sig <- ifelse(paste(allChr.est$PEAK,allChr.est$SNP) %in% paste(reported_m6AQTL$PEAK,reported_m6AQTL$SNP),"FDR<0.1","Non-sig")

cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

ggplot(VolcData, aes(x = beta, y = -log10(pvalue)) )+ geom_point(size = 0.5, color =  "gray")+geom_point(data = VolcData[VolcData$sig == "FDR<0.1",],aes(x = beta, y = -log10(pvalue)), color = "#0072B2",size = 0.6 )+theme_bw()+theme(axis.title =  element_text(size = 20, face = "bold"),axis.text = element_text(size = 20, face = "bold", color = "black"),  axis.line = element_line(color = "black",size = 0.8), axis.ticks = element_line(color = "black",size = 0.8))+xlab("Effect sizes") + scale_x_continuous(limits = c(-2.5,2.5))

Spatial distribution of m^6AQTL(2MB window)

m6AQTL_2mb.sig <-foreach(chr = 1:22, .combine = rbind )%do%{
  tmpChr <- readRDS(paste0( "~/m6AQTL/m6A_QTL_results/linear_model/fastQTL_cis_2MBwindow/m6APeak_logOR_GC.IP.adjusted_qqnorm/m6AQTL.m6APeak_logOR_GC.IP.adjusted_qqnorm.chr",chr,".2e6bp.15PCs.fastQTL.nominals.rds") )
  
  tmpChr.sig <- dplyr::filter(tmpChr, pvalue < 1e-4)
  tmpChr.sig[,c("PEAK","SNP","DIST","pvalue")]
} 

ggplot(dplyr::filter(m6AQTL_2mb.sig,abs(DIST)<1000000 & pvalue < 1e-5 ) )+geom_point(aes(x= DIST, y = -(log10(pvalue)-log10(max(m6AQTL_2mb.sig$pvalue)))*7e-7),size = 0.3,colour =  "#0072B2")+geom_density(aes(x = DIST), size = 1 )+xlab("Distance from the peak with respect to transcript strand (bp)")+ylab("Density")+ scale_y_continuous(expand = c(0,0), sec.axis = sec_axis(trans = ~./7e-7 -log10(max(m6AQTL_2mb.sig$pvalue)), name = "-log10(p)",breaks = round(seq(-log10(max(m6AQTL_2mb.sig$pvalue)),25,length.out = 6))))+ggtitle(bquote('Distribution of lead '~m^6~'A QTLs relative to'~m^6~'A QTLs relative to '~m^6~'A peak'))+theme_classic()+theme(plot.title = element_text(hjust = 0.5, face = "bold"),axis.title = element_text(face = "bold",size = 16), axis.text = element_text(face = "bold",size = 15, colour = "black"), axis.text.y.right = element_text(face = "bold",size = 15, colour = "#0072B2"),axis.title.y.right = element_text(face = "bold",size = 16, colour =  "#0072B2"), axis.line = element_line(size = 0.75),axis.ticks = element_line(size = 0.75), axis.line.y.right = element_line(colour =  "#0072B2"), axis.ticks.y.right = element_line(colour =  "#0072B2") )+scale_x_continuous(breaks = seq(-1e6,1e6,2e5),labels =  paste(seq(-1e6,1e6,2e5)/1000, "Kb" ), expand = c(0.01,0.01))

ecdf(abs(m6AQTL_2mb.sig$DIST) )

ggplot(dplyr::filter(m6AQTL_2mb.sig, pvalue <1e-5 ), aes( abs(DIST) ) )+stat_ecdf(geom = "step", size = 1, color = "#D55E00")+stat_ecdf(dplyr::filter(m6AQTL_2mb.sig, pvalue <1e-4 ), mapping = aes( abs(DIST) ),geom = "step", size = 1, color =  "#0072B2" )+stat_ecdf(dplyr::filter(m6AQTL_2mb.sig, pvalue <1e-6 ), mapping = aes( abs(DIST) ),geom = "step", size = 1, color = "#CC79A7"  )+geom_hline(yintercept = 1, lty=2,size = 0.7)+ylab("Cumulative proportion")+xlab("Distance from the peak")+theme_classic()+theme(plot.title = element_text(hjust = 0.5, face = "bold"),axis.title = element_text(face = "bold",size = 18), axis.text = element_text(face = "bold",size = 15, colour = "black"), axis.line = element_line(size = 0.8,colour = "black"),axis.ticks = element_line(size = 0.75), axis.line.y.right = element_line(colour =  "#0072B2"), axis.ticks.y.right = element_line(colour =  "#0072B2") )+scale_y_continuous(expand = c(0,0))+scale_x_continuous(breaks = seq(0,1.8e6,2e5),labels =  paste(seq(0,1.8e6,2e5)/1000, "Kb" ), expand = c(0.01,0.01))

Genomic annotation of \(m^{6}A\)QTLs

all associated SNPs

library(ChIPseeker)
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene::TxDb.Hsapiens.UCSC.hg19.knownGene
sig.qtl.gr <- GRanges(seqnames = unlist( lapply(strsplit(as.character(sig.qtl$SNP),split =":"),function(x){x[1]}) ),
                      IRanges(as.numeric(unlist( lapply(strsplit(as.character(sig.qtl$SNP),split =":"),function(x){x[2]}))),
                              as.numeric(unlist( lapply(strsplit(as.character(sig.qtl$SNP),split =":"),function(x){x[2]}))) ) )
m6Aqtl_anno <- annotatePeak(peak = sig.qtl.gr,TxDb = txdb, genomicAnnotationPriority = c("5UTR", "3UTR", "Exon", "Intron","Promoter", "Downstream", "Intergenic") )
plotAnnoPie(m6Aqtl_anno)

lead SNPs

reported_QTL.gr <- GRanges(seqnames = unlist( lapply(strsplit(as.character(reported_m6AQTL$SNP),split =":"),function(x){x[1]}) ),
                      IRanges(as.numeric(unlist( lapply(strsplit(as.character(reported_m6AQTL$SNP),split =":"),function(x){x[2]}))),
                              as.numeric(unlist( lapply(strsplit(as.character(reported_m6AQTL$SNP),split =":"),function(x){x[2]}))) ) )
m6Aqtl_lead_anno <- ChIPseeker::annotatePeak(peak = reported_QTL.gr,TxDb = txdb, genomicAnnotationPriority = c("5UTR", "3UTR", "Exon", "Intron","Promoter", "Downstream", "Intergenic") )

tmp <- rbind( m6Aqtl_lead_anno@annoStat[c(1,2),], 
             data.frame( Feature = "CDS", Frequency = sum(m6Aqtl_lead_anno@annoStat[c(3:4),"Frequency"])),
             data.frame( Feature = "Intron", Frequency = sum(m6Aqtl_lead_anno@annoStat[c(5:6),"Frequency"])),
             data.frame( Feature = "Intergenic", Frequency = sum(m6Aqtl_lead_anno@annoStat[c(7:8),"Frequency"]))
             )

m6Aqtl_lead_anno@annoStat <- tmp

plotAnnoPie(m6Aqtl_lead_anno)

all tested SNPs

testedSNPs <- unique( as.character(allChr.est$SNP) )
testedSNPs.gr <-  GRanges(seqnames = unlist( lapply(strsplit(testedSNPs,split =":"),function(x){x[1]}) ),
                      IRanges(as.numeric(unlist( lapply(strsplit(testedSNPs,split =":"),function(x){x[2]}))),
                              as.numeric(unlist( lapply(strsplit(testedSNPs,split =":"),function(x){x[2]}))) ) )

testedSNPs_anno <- ChIPseeker::annotatePeak(peak = testedSNPs.gr,TxDb = txdb, genomicAnnotationPriority = c("5UTR", "3UTR", "Exon", "Intron","Promoter", "Downstream", "Intergenic") )

tmp <- rbind( testedSNPs_anno@annoStat[c(1,2),], 
             data.frame( Feature = "CDS", Frequency = sum(testedSNPs_anno@annoStat[c(3:4),"Frequency"])),
             data.frame( Feature = "Intron", Frequency = sum(testedSNPs_anno@annoStat[c(5:6),"Frequency"])),
             data.frame( Feature = "Intergenic", Frequency = sum(testedSNPs_anno@annoStat[c(7:8),"Frequency"]))
             )
testedSNPs_anno@annoStat <- tmp
saveRDS(testedSNPs_anno, file = "~/m6AQTL/m6A_QTL_results/linear_model/annotateAllSNPs.RDS")
SNP.Map <- read.table(gzfile("~/m6AQTL/m6A_QTL_results/linear_model/annotation/snp.map.gz"), sep = "\t", header = T)
annot3 <- read.table(gzfile("~/m6AQTL/m6A_QTL_results/linear_model/annotation/annot3.gz"), sep = "\t", header = T)

SNP.gr <- GRanges(seqnames = SNP.Map$CHROM,ranges = IRanges(start = SNP.Map$POS,end = SNP.Map$POS ) )

fiveUTR.flag <- unique( queryHits(findOverlaps(SNP.gr,testedSNPs_anno@anno[grep("5' UTR",testedSNPs_anno@anno$annotation)]))  )
threeUTR.flag <- unique( queryHits(findOverlaps(SNP.gr,testedSNPs_anno@anno[grep("3' UTR",testedSNPs_anno@anno$annotation)]))  )
Intergenic.flag <- unique( queryHits(findOverlaps(SNP.gr,testedSNPs_anno@anno[c(grep("Intergenic",testedSNPs_anno@anno$annotation),grep("Downstream",testedSNPs_anno@anno$annotation) )]))  )
Exon.flag <- unique( queryHits(findOverlaps(SNP.gr,testedSNPs_anno@anno[grep("Exon",testedSNPs_anno@anno$annotation)]))  )
Intron.flag <- unique( queryHits(findOverlaps(SNP.gr,testedSNPs_anno@anno[grep("Intron",testedSNPs_anno@anno$annotation)]))  )

annot <- data.frame(SNP = SNP.Map$ID , annotation_d = 0)
annot$annotation_d[fiveUTR.flag] <- 1
annot$annotation_d[threeUTR.flag] <- 2
annot$annotation_d[Exon.flag] <- 3
annot$annotation_d[Intron.flag] <- 4

annot <- cbind(annot,annot3$H3K27me3_d)

write.table(annot,"~/m6AQTL/m6A_QTL_results/linear_model/annotation/GenomicAnnotation", sep = "\t", col.names = T,row.names = F,quote = F )
system("gzip ~/m6AQTL/m6A_QTL_results/linear_model/annotation/GenomicAnnotation")

system(paste0("torus -d /home/zijiezhang/m6AQTL/m6A_QTL_results/linear_model/annotation/allChr.summary.gz  -smap /home/zijiezhang/m6AQTL/m6A_QTL_results/linear_model/annotation/snp.map.gz -gmap /home/zijiezhang/m6AQTL/m6A_QTL_results/linear_model/annotation/gene.map.gz -annot /home/zijiezhang/m6AQTL/m6A_QTL_results/linear_model/annotation/GenomicAnnotation.gz  -est > /home/zijiezhang/m6AQTL/m6A_QTL_results/linear_model/annotation/m6AQTL.AnnotationEnrich.est"))
torus.enrich <- read.table("~/m6AQTL/m6A_QTL_results/linear_model/annotation/m6AQTL.AnnotationEnrich.est", sep = "\t")[-c(1),]
torus.enrich <- gsub("\\s+", "\t", sapply(torus.enrich,trimws))
torus.enrich <- do.call(rbind.data.frame, strsplit(torus.enrich, split = "\t") )
torus.enrich[,-c(1)] <- apply(torus.enrich[,-c(1)],2, function(x) as.numeric(as.character(x)) )

colnames(torus.enrich) <- c("feature","LogOddRatio","CI05","CI95")
torus.enrich$feature <- factor( c( "5' UTR","3' UTR", "CDS", "Intron", "Intergenic\nrepressive" ))
torus.enrich$feature <- factor( c( "5' UTR","3' UTR", "CDS", "Intron" , "Intergenic\nrepressive"), levels = torus.enrich[order(torus.enrich$LogOddRatio),"feature"] )

ggplot(torus.enrich,aes(x = LogOddRatio/log(2), y = feature ))+geom_point(size = 2)+ xlab("Log2 enrichment")+
  geom_errorbarh(aes(xmin = CI05/log(2), xmax = CI95/log(2), height = 0.3),size = 0.8)+ 
  theme_bw()  + ylab("Features")+
  geom_vline(xintercept = 0,linetype="dotted", colour = "red")+theme(axis.ticks = element_blank(),  
                     panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"), axis.text = element_text(face="bold",size = 23, colour = "black"),axis.text.y = element_text(angle = 10),axis.title.x = element_text(face="bold",size = 20) , axis.title.y = element_blank())+coord_cartesian(xlim=c(-9,6))

Plot example m6A-QTL

\(m^{6}A\)-QTL

LCLs <- PrepCoveragePlot(LCLs)
LCLs <- normalizeLibrary(LCLs)
plotSNPpeakPairs(LCLs,genotypeFile =  "~/m6AQTL/variant_data/sixtySample_hg19/Imputed.sixty.hg19.chr11.vcf.gz",SNPID = "rs1045405",
                 geneName = "PSMD13",
                 libraryType = "opposite",
                 center = mean, ZoomIn = NULL,adjustExprLevel = F)+ scale_y_continuous(expand = c(0.02, 0))
print(lead_m6AQTL[1,])

ZoomIn

plotSNPpeakPairs(LCLs,genotypeFile =  "~/m6AQTL/variant_data/sixtySample_hg19/Imputed.sixty.hg19.chr11.vcf.gz",SNPID = "rs1045405",
                 geneName = "PSMD13",
                 libraryType = "opposite",
                 center = mean, ZoomIn = c(251769,252984),adjustExprLevel = F)+scale_y_continuous(expand = c(0.02, 0))

Box plot for peak enrichment

.genotypeDosage <- function(x){
  split <- sapply(x,strsplit,"[|]")
  return( suppressWarnings( unlist(lapply(split,function(x){sum(as.integer(x),na.rm = T)})) ) )
}

.getGenotype <- function(vcf.gz, SNPID){
  tmp <- system2(command = "zcat", args = paste0(vcf.gz," |grep -w '",SNPID,"' |cat"),stdout = T)
  if(length(tmp)>1){cat("Please note there are more than one locus associated with this SNPID in the vcf file! The first one was used!\n")}
  geno <- strsplit(tmp,split = "\t")[[1]]
  return(geno)
}

wflow_newLCLs <- MeRIPtools::filter(LCLs, !apply(extractInput(LCLs), 1, function(x) any(x == 0 )) )
T0 <- colSums(counts(newLCLs)[,1:length(newLCLs@samplenames)] )
T1 <- colSums(counts(newLCLs)[,(length(newLCLs@samplenames)+1) : (2*length(newLCLs@samplenames)) ] )
##filter out peaks with OR < 1
enrichFlag <- apply( t( t(extractIP(newLCLs))/T1 )/ t( t( extractInput(newLCLs) )/T0 ),1,function(x){sum(x>1)> newLCLs@jointPeak_threshold})
newLCLs <-  MeRIPtools::filter(newLCLs, enrichFlag )

library(BSgenome.Hsapiens.UCSC.hg19)
library(stringr)
dLCLs <- MeRIPtools::filter(newLCLs, !apply(extractInput(newLCLs), 1, function(x) any(x == 0 )) )
T0 <- colSums(counts(dLCLs)[,1:length(dLCLs@samplenames)] )
T1 <- colSums(counts(dLCLs)[,(length(dLCLs@samplenames)+1) : (2*length(dLCLs@samplenames)) ] )
##filter out peaks with OR < 1
enrichFlag <- apply( t( t(extractIP(dLCLs))/T1 )/ t( t( extractInput(dLCLs) )/T0 ),1,function(x){sum(x>1)> dLCLs@jointPeak_threshold})
dLCLs <-  MeRIPtools::filter(dLCLs, enrichFlag )
OR <- t( apply(extractIP(dLCLs),1, MeRIPtools:::.noZero)/T1 )/ t( t( extractInput(dLCLs) )/T0 )
colnames(OR) <- dLCLs@samplenames
logOR <- log(OR)
  
logOR.id <- which( rowMeans(logOR) < quantile( rowMeans(logOR), 0.95 ) & rowMeans(logOR) > quantile( rowMeans(logOR), 0.05) )# remove two tails
K_IPe_ij <- apply(logOR[logOR.id,], 2, function(x){
  
  fit <- lm(y~m, data = data.frame(y = x, m=rowMeans(logOR)[logOR.id] ))
  y.est <- predict(fit, newdata =  data.frame(m = rowMeans(logOR)))
  return( y.est - rowMeans(logOR) )
  })

## GC bias
peak.gr <- MeRIPtools:::.peakToGRangesList( jointPeak(dLCLs))
#registerDoParallel( 30 )
peakGC <- foreach( i = 1:length(peak.gr), .combine = c)%dopar%{
  peakSeq <- paste( getSeq( BSgenome.Hsapiens.UCSC.hg19 , peak.gr[[i]] ,as.character =T ) , collapse = "")
  sum( str_count(peakSeq, c("G","g","C","c"))  )/nchar(peakSeq)
  }
peakGC_l <- round(peakGC,digits = 2)
peakGC_l[which(peakGC_l<0.2)] <-median(peakGC_l[which(peakGC_l<0.2)] ) # combine some bins at low GC due to low number of peaks
peakGC_l[which(peakGC_l>0.84)] <-median(peakGC_l[which(peakGC_l>0.84)] ) # combine some bins at high GC due to low number of peaks
l <- sort(unique(peakGC_l))
y <- (log( OR ) - K_IPe_ij )
colnames(y) <- dLCLs@samplenames
b.l <- tapply(rowMeans( y ), peakGC_l ,  median) 
bil <- apply( y, 2, tapply, peakGC_l, median )
bi. <- apply(  y , 2, median )
b.. <- median(  y )
Fil <- as.data.frame( as.matrix(bil) - as.vector(b.l) ) - ( bi. - b.. )
Fij <- foreach( ii = 1:length(dLCLs@samplenames), .combine = cbind)%dopar%{
  GC_fit <- lm(Fil[,ii] ~ poly(l,4) )
  predict(GC_fit, newdata = data.frame(l = peakGC) )
}
colnames(Fij) <- dLCLs@samplenames

Y_logOR <- log(OR) - K_IPe_ij - Fij
geno <- .getGenotype(vcf.gz = "~/m6AQTL/variant_data/sixtySample_hg19/Imputed.sixty.hg19.chr11.vcf.gz", SNPID = "rs1045405")
dosage_geno <- .genotypeDosage(geno[-c(1:9)])
dosage_geno <- gsub("0",paste0(geno[4],geno[4]),as.character(dosage_geno))
dosage_geno <- gsub("1",paste0(geno[4],geno[5]),as.character(dosage_geno))
dosage_geno <- gsub("2",paste0(geno[5],geno[5]),as.character(dosage_geno))


Y_logOR_PSMD13 <- data.frame(geno = factor(dosage_geno, levels = c("TT","TC","CC")), logOR = Y_logOR[match("chr11:251869-252934_PSMD13_+", paste0(jointPeak(dLCLs)$chr,":",jointPeak(dLCLs)$start,"-",jointPeak(dLCLs)$end,"_",jointPeak(dLCLs)$name,"_",jointPeak(dLCLs)$strand) ),] )

ggplot(Y_logOR_PSMD13)+geom_boxplot(aes(x = geno, y = logOR, color = geno))+ylab("Peak Log Enrichment")+theme_bw()+theme(text = element_text(face = "bold", size = 18, colour = "black"), axis.title.x = element_blank(), axis.text = element_text(face = "bold", size = 18, colour = "black"), axis.line = element_line(color = "black",size = 0.8), axis.ticks = element_line(color = "black",size = 0.8))+scale_color_manual(values = c("#F37B59","#00BE6C","#529EFF") )

m6AQTL and eQTL distance

eQTL <- readRDS("~/m6AQTL/other_phenotypes/Pickrell_expression/eQTL_summaryStats.RDS")

permute_eQTL <- foreach(chr = 1:22, .combine = rbind )%dopar%{
  tmpChr <- read.table(gzfile( paste0("~/m6AQTL/other_phenotypes/Pickrell_expression/permutation.chr",chr,".txt.gz") ), col.names = c("Gene","NumGeneTested","shape1","shape2","dummy","SNPID","DISTANCE","pvalue","beta","pvalue_permute","pvalue_fit") )
}
permute_eQTL$fdr <- qvalue::qvalue(permute_eQTL$pvalue_fit)$qvalue

saveRDS(permute_eQTL, file = "~/m6AQTL/other_phenotypes/Pickrell_expression/eQTL_permutation.RDS")
m6AQTL <- readRDS("~/m6AQTL/m6A_QTL_results/linear_model/m6AQTL.m6APeak_logOR_GC.IP.adjusted_qqnorm.15PCs.fastQTL.nominals.rds")
permutation_m6AQTL <-  readRDS("~/m6AQTL/m6A_QTL_results/linear_model/m6AQTL.m6APeak_logOR_GC.IP.adjusted_qqnorm.15PCs.fastQTL.permutations.rds")

GTF <- rtracklayer::import("~/Database/genome/GRCh37/GRCh37.gencode.v27.gtf", format = "gtf")
EnsToSymb <- data.frame(ENSG = GTF$gene_id[ !duplicated(GTF$gene_id) ], Symb = GTF$gene_name[ !duplicated(GTF$gene_id) ] )
EnsToSymb$ENSG <- unlist( lapply( strsplit( as.character(EnsToSymb$ENSG), "[.]" ), function(x) x[1] )  )

eQTL <- readRDS("~/m6AQTL/other_phenotypes/Pickrell_expression/eQTL_summaryStats.RDS")
permutation_eQTL <- readRDS( "~/m6AQTL/other_phenotypes/Pickrell_expression/eQTL_permutation.RDS")
eQTL$GENE <- unlist( lapply( strsplit( as.character(eQTL$GENE), "[.]" ), function(x) x[1] )  )
permutation_eQTL$Gene <-  unlist( lapply( strsplit( as.character(permutation_eQTL$Gene), "[.]" ), function(x) x[1] )  )
eQTL <- eQTL[order(eQTL$pvalue, decreasing = FALSE),]
eQTL_lead <- eQTL[!duplicated(eQTL$Gene),]

eQTL$Gene <- EnsToSymb[match(eQTL$GENE,EnsToSymb$ENSG),"Symb"]
permutation_eQTL$GeneSymbol <- EnsToSymb[match(permutation_eQTL$Gene,EnsToSymb$ENSG),"Symb"]

ePeaks <- permutation_m6AQTL[permutation_m6AQTL$qvalue<0.1,]
eGenes <- eQTL_lead[eQTL_lead$Gene %in% permutation_eQTL[permutation_eQTL$fdr<0.1,"GeneSymbol"], ]

commonGenes <- intersect(ePeaks$GENE, eGenes$Gene )
commonGenes <- commonGenes[!is.na(commonGenes)]

e_m6A_QTL_distance <- foreach(gene = commonGenes, .combine = rbind)%do%{
  m6AQTLsnp <- as.character( ePeaks[ePeaks$GENE %in% gene,"SNP"] )
  eQTLsnp <- as.character( eGenes[eGenes$Gene %in% gene,"SNP"] )
  distance <- abs( as.numeric( strsplit(m6AQTLsnp, ":")[[1]][2] ) - as.numeric( strsplit(eQTLsnp, ":")[[1]][2] ) )
  
  data.frame(gene = gene, m6AQTL = m6AQTLsnp, eQTL = eQTLsnp, distance = distance)
}

e_m6A_QTL_distance$distance <- as.numeric( gsub(0,1,e_m6A_QTL_distance$distance) )

ggplot(dplyr::filter(e_m6A_QTL_distance, distance < 1e5), aes( x = distance  ))+geom_histogram(col=I("black") )+theme_bw()+theme(axis.title =  element_text(size = 20),axis.text = element_text(size = 15, color = "black"),  axis.line = element_line(color = "black",size = 0.8), axis.ticks = element_line(color = "black",size = 0.8), panel.border = element_blank(), panel.grid = element_blank())+xlab("log10(Distance)")

ggplot(dplyr::filter(e_m6A_QTL_distance, distance < 1e5  ), aes( x = log10(distance ) ))+geom_histogram(col=I("black") )+theme_bw()+theme(axis.title =  element_text(size = 20),axis.text = element_text(size = 15, color = "black"),  axis.line = element_line(color = "black",size = 0.8), axis.ticks = element_line(color = "black",size = 0.8), panel.border = element_blank(), panel.grid = element_blank())+xlab("log10(Distance)")
library(Vennerable)

Vcommon <- Venn(list("ePeak Genes"= ePeaks$GENE,"eGenes"= eGenes$Gene ) )
plot(Vcommon,doWeights=TRUE)

sessionInfo()
R version 3.5.3 (2019-03-11)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 17.10

Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] workflowr_1.3.0 Rcpp_1.0.1      digest_0.6.18   rprojroot_1.3-2
 [5] backports_1.1.4 git2r_0.25.2    magrittr_1.5    evaluate_0.13  
 [9] stringi_1.4.3   fs_1.3.0        rmarkdown_1.12  tools_3.5.3    
[13] stringr_1.4.0   glue_1.3.1      xfun_0.6        yaml_2.2.0     
[17] compiler_3.5.3  htmltools_0.3.6 knitr_1.22