I once did a blog on combining graphis with external programs and received a terrific comment from a reader (-click here-) on implementing this entirely within R with ghostscript as seen below. I have been using this a bit lately and am wanting to share it with others. I’d like to modify it to make the function more intuitive and detecting the ghostscript type is one mod I’d like to do but can’t. The unix vs. windows is easy via .Platform. The sticking point is the windows 32 vs. 64 that I struggle with.
How can I use R to detect which ghostscript version (gswin32c or gswin64c) is running? Merely looking at the computer’s specifications isn’t good enough because I run gswin32c on a Win 64 machine. The idea is to remove the os argument entirely or set it to NULL and have the function try to access this information.
mergePDF <- function(infiles, outfile, os = "UNIX") {
version <- switch(os,
UNIX = "gs",
Win32 = "gswin32c",
Win64 = "gswin64c")
pre = " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="
system(paste(paste(version, pre, outfile, sep = ""), infiles, collapse = " "))
}
pdf("file1.pdf", width = 10, height = 8)
plot(1:10, col="red", pch = 19)
dev.off()
pdf("file2.pdf", width = 16, height = 8)
plot(1:10)
dev.off()
mergePDF("file1.pdf file2.pdf", "mergefromR.pdf", "Win32")
Tyler, dude. Have I been demoted from being a Stack Ove-R-flow peer to a “reader” of your blog? Or is that a promotion 😉
This feels a little hackish to me, but should get the job done. Add this as the first few lines of the function and remove the os argument:
I’ve used the
-versionswitch so that R doesn’t try to load Ghostscript unnecessarily.On my Ubuntu system, when I run this,
osreturns, as expected,UNIX, and on my Windows system where I have the 32-bit version of Ghostscript installed, it returnsWin32. Try it out on your 64-bit machine running the 32-bit GS and let me know how it works.Update
After reading the help pages for
system()andsystem2(), I learned aboutSys.which(), which seems to be exactly what you’re looking for. Here it is in action on my Ubuntu system:Thus, OS specification can be skipped entirely in the
mergePDF()function:You may want to do some error checking. If the length of
gsversionis > 1 or is 0, for instance, you may want to stop the function and prompt the user to either install Ghostscript or to verify their Ghostscript version.