2

Drafting a manuscript I must do a Figure with 2 panes (A and B). I have 2 distinct R codes that produce 2 distinct pdf files.

Is there an R function that can take the pdf files and collapse them into one single pdf?

I sake of tidy code I'd like to keep single codes that produce a single figure separately.

Thank all!

Example:

code_1.R

> x <- 1:10
> 
> pdf(file="A.pdf") plot(x) dev.off()

code_2.R

> x <- 20:10
> 
> pdf(file="B.pdf") plot(x) dev.off()

I wish to know if exists a R function that can read directly A.pdf and B.pdf and create a file.

jay.sf
  • 60,139
  • 8
  • 53
  • 110

2 Answers2

2

No need to merge, you can directly do

pdf(file="AB.pdf") 
lapply(list(x, y), plot)
dev.off()

which produces a single .pdf with one page for each plot.

If you already have .pdf files and are on Linux, better use the command line:

convert pdf_1.pdf pdf_2.pdf merged.pdf

Data:

x <- 1:10; y <- 20:10
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • Thank you @jay-sf. I have quite extensive argument list for each plot (colors, grouping, x-axis, y-axis, xlab, ylab, cex etc...). This is the reason why I keep the code separate for each figure: it is easily readable and when I must edit something it is straightforward. Each .R file is almost 20 lines of custom settings. – Alessandro Brozzi Jul 25 '23 at 11:39
  • 2
    Just use `source()` on separate files if you want the plot source in separate files. Store one plot in `x`, the other in `y`, and then follow @jay.sf's suggestion. Or use RMarkdown or a different document preparation system that runs the code when it produces the document, and it will include the plots whereever you want. – user2554330 Jul 25 '23 at 11:42
  • 1
    @AlessandroBrozzi Not a big problem, using `Map` you can specify parameters individually for each plot. – jay.sf Jul 25 '23 at 11:43
  • `pdf(file="AB.pdf")` `par(mfrow=c(2,2))` `source("figureA.R")` `source(".figureB.R")` `dev.off()` – Alessandro Brozzi Jul 25 '23 at 11:59
1

You can use qpdf to combine pdf's.

pdf(file="A.pdf"); plot(1:10); dev.off()
pdf(file="B.pdf"); plot(20:10); dev.off()

library(qpdf)
pdf_combine(c("A.pdf", "B.pdf"), output = "AB.pdf")
GKi
  • 37,245
  • 2
  • 26
  • 48
  • Thank you @GKi! This is extremely useful when plots must go sequentially in new pages. My issue was related in combine A.pdf and B.pdf aside in a single file. `par(mfrow=c(2,1)` looks to do the job. Again qpdf is extremely useful as well. – Alessandro Brozzi Jul 25 '23 at 12:38
  • 1
    Maybe https://stackoverflow.com/questions/74660260/r-pdftools-combine-multiple-pages-into-a-single-page is what you wanted? – GKi Jul 25 '23 at 12:58