I am trying to build a loop for() to draw & save a ggplot for a list of genes in a dataset. My initial code is the following:
for(i in genelist){
  plot <- ggplot() +
           geom_density(data = mydata, aes(x=log2(i)), fill="pink", alpha = 0.5) +
           xlab(paste("log2 ", i))
  ggsave(plot, filename = paste("plot_",i ,".png"))
  }
genelist is a chr vector.
mydata is a dataframe where colnames are names of genes, rownames are patients barcodes and matrix is count values.
I obtained the following error:
Saving 11.3 x 5.98 in image Error in log2(i) : non-numeric argument to mathematical function
Since the error seems to come from the plot saving, I tried the code without:
for(i in genelist){
  plot <- ggplot() +
           geom_density(data = mydata, aes(x=log2(i)), fill="pink", alpha = 0.5) +
           xlab(paste("log2 ", i))
   }
The loop went to the end without error (i = my last gene in genelist) but when I tried to display the plot:
Error in log2(i) : non-numeric argument to mathematical function
What am I doing wrong?
 
    