0

I came across this taken from here:

library(ggplot2)

p <- ggplot(iris, aes(x = Species, y = Sepal.Length))
colors <- c("black", "red", "green")
 
for(color in colors){
 
   final.plot <- p + geom_boxplot(color = color)
 
  pdf(paste0(color, ".pdf"))
  print(final.plot)
  dev.off()
}

It produces several pdfs. Can one also append several plots, tables, heading to one pdf inside such a loop? I have not found anything useful yet and do not think that knitr, rmarkdown etc. are appropriate for this use case?

Thanks.

cs0815
  • 16,751
  • 45
  • 136
  • 299

1 Answers1

2

If I understand you correctly, this is really straightforward, just place pdfand dev.off outside the loop:

library(ggplot2)

p <- ggplot(iris, aes(x = Species, y = Sepal.Length))
colors <- c("black", "red", "green")

pdf("all_figures.pdf")
for(color in colors){
  final.plot <- p + geom_boxplot(color = color)
  print(final.plot)
}

dev.off()
tpetzoldt
  • 5,338
  • 2
  • 12
  • 29
  • thanks so that easy. I guess headings and tables can be easily dynamically added that way? Would you aggress that rmarkdown + knitr + pandoc would not be appropriate here? – cs0815 Jun 09 '21 at 09:24
  • 2
    Yes, headings and tables can also be added. For more complex combinations, I would definitely recommend to use Rmarkdown + knitr + pandoc. RStudio provides a clear and simple workflow and great flexibility. – tpetzoldt Jun 09 '21 at 09:52
  • Thanks - currently look at package pander, which appears very useful https://stackoverflow.com/questions/51158486/create-sections-through-a-loop-with-knitr/51159788 – cs0815 Jun 09 '21 at 09:56