Sander Van der Zeeuw
Sander Van der Zeeuw

Reputation: 1092

For loop assigns variable while i want to plot something with qplot (R)

So i have the following for loop:

for (Count in 1:19){
  png(paste0(colnames(fdd$rawCounts)[Count], ".pdf"))
  qplot(y = log2(fdd$rawCounts[,Count]), main = colnames(fdd$rawCounts)[Count])
  dev.off()
}

Which should simply plot some count data which i put a head from here:

structure(c(11L, 3L, 12L, 8L, 15L, 2L, 5L, 2L, 8L, 7L, 6L, 10L, 
6L, 1L, 7L, 4L, 2L, 1L, 3L, 0L, 4L, 4L, 2L, 5L, 8L, 0L, 13L, 
4L, 10L, 7L, 2L, 1L, 2L, 4L, 7L, 7L, 14L, 4L, 25L, 17L, 14L, 
16L, 4L, 2L, 5L, 5L, 5L, 2L, 9L, 5L, 11L, 8L, 1L, 4L, 10L, 8L, 
8L, 7L, 9L, 5L, 9L, 15L, 14L, 11L, 16L, 8L, 11L, 4L, 3L, 6L, 
3L, 0L, 6L, 3L, 4L, 6L, 1L, 4L, 11L, 11L, 12L, 6L, 2L, 6L, 7L, 
9L, 22L, 8L, 13L, 7L, 6L, 1L, 4L, 5L, 6L, 2L, 4L, 2L, 6L, 7L, 
3L, 2L, 6L, 3L, 3L, 2L, 5L, 5L, 9L, 2L, 6L, 5L, 4L, 2L), .Dim = c(6L, 
19L), .Dimnames = structure(list(feature = c("chr10:100000001-100000500", 
"chr10:10000001-10000500", "chr10:1000001-1000500", "chr10:100000501-100001000", 
"chr10:100001-100500", "chr10:100001001-100001500"), sample = c("K562_FAIRE_Acla_4hr_1", 
"K562_FAIRE_Acla_4hr_2", "K562_FAIRE_Daun_4hr_1", "K562_FAIRE_Daun_4hr_2", 
"K562_FAIRE_Etop_4hr_1", "K562_FAIRE_Etop_4hr_2", "K562_FAIRE_untreated", 
"FAIRE.seq_K562_2MethylDoxo_A", "FAIRE.seq_K562_2MethylDoxo_B", 
"FAIRE.seq_K562_Ctr_A", "FAIRE.seq_K562_Ctr_B", "FAIRE.seq_K562_Doxo_10uM_4hrs_A", 
"FAIRE.seq_K562_Doxo_10uM_4hrs_B", "FAIRE.seq_K562_Epirubicin_A", 
"FAIRE.seq_K562_Epirubicin_B", "FAIRE.seq_K562_MTX_40uM_4hrs_A", 
"FAIRE.seq_K562_MTX_40uM_4hrs_B", "FAIRE.seq_K562_MTX_5uM_4hrs_A", 
"FAIRE.seq_K562_MTX_5uM_4hrs_B")), .Names = c("feature", "sample"
)))

Now if i try to plot the data it gives me a variable called Count and the value is 19L. While i expect 19 plots to be drawn. Why is this happening?

Thanks!

Upvotes: 0

Views: 42

Answers (1)

lmo
lmo

Reputation: 38500

This works for me:

for (Count in 1:19){
  pdf(paste0(colnames(df)[Count], ".pdf"))
  print(qplot(y = log2(df[, Count]), main = colnames(df)[Count]))
  dev.off()
}

A couple of changes:

  • I read in your data as df. It turns out to be a matrix, so I adjusted the subsetting accordingly.
  • I also wrapped the qplot function in a print function which forces the figure to be created.
  • Finally, I switched the png function to pdf as that seemed like the files you were trying to create based on the paste0 result.

Upvotes: 3

Related Questions