question about R language 'for' loop
2
0
Entering edit mode
3.2 years ago

When I type in the following code, the resulting picture is blank

samples <- c("m5C","m6A","m7G")
group <- c("Control","Treatment")
for(sa in samples){
for(gr in group){
  genelist = bitr(geneID = metG.expr[[sa]][[gr]]$Symbol,fromType = "SYMBOL",toType = "ENTREZID",OrgDb = org.Dr.eg.db)
  kegg <- enrichKEGG(gene = genelist$ENTREZID,
                     keyType = "kegg",organism = "dre",
                     pvalueCutoff = 0.05,pAdjustMethod = "BH")
  png(paste("./exprProfile/enrich/",sa,".",gr,".kegg",".png",sep=""),width = 1500,height = 1000,res = 200)
  ggplot(kegg@result[c(1:10),],mapping = aes(x = Description,y = -log10(pvalue),fill = pvalue))+
    geom_bar(stat = "identity",show.legend = T)+ 
    coord_flip()+scale_fill_gradient2(high="blue",mid = "red")
  dev.off()
}}

but when i assign values to two variables 'sa' and 'gr'

sa<-"m5C"
gr<-"Control"

then run

genelist = bitr(geneID = metG.expr[[sa]][[gr]]$Symbol,fromType = "SYMBOL",toType = "ENTREZID",OrgDb = org.Dr.eg.db)
  kegg <- enrichKEGG(gene = genelist$ENTREZID,
                     keyType = "kegg",organism = "dre",
                     pvalueCutoff = 0.05,pAdjustMethod = "BH")
  png(paste("./exprProfile/enrich/",sa,".",gr,".kegg",".png",sep=""),width = 1500,height = 1000,res = 200)
  ggplot(kegg@result[c(1:10),],mapping = aes(x = Description,y = -log10(pvalue),fill = pvalue))+
    geom_bar(stat = "identity",show.legend = T)+ 
    coord_flip()+scale_fill_gradient2(high="blue",mid = "red")
  dev.off()

the picture is successfully produced,so i wonder what cause this situation and how i can fix that,thanks

RNA-Seq sequencing next-gen R gene • 769 views
ADD COMMENT
2
Entering edit mode
3.2 years ago

Within the for loop, save the plot to a variable, and then pass that variable to the print function while the graphics device is open. R usually won't plot in a for loop unless you do so.

Alternatively you can use the ggsave function instead which will work without any problems in loops.

ADD COMMENT
0
Entering edit mode

very useful advice,thank you very much

ADD REPLY
2
Entering edit mode
3.2 years ago
MatthewP ★ 1.4k

Use ggsave function to save ggplot picture.

ADD COMMENT
0
Entering edit mode

thank you very much.

ADD REPLY

Login before adding your answer.

Traffic: 2786 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6