Show me the pdf already
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
You’ve got a pdf file and you’d like to view it with whatever the system viewer is. As usual, that requires something special for Windows and something general for the rest of us. Here goes…
openPDF <- function(f) { os <- .Platform$OS.type if (os=="windows") shell.exec(normalizePath(f)) else { pdf <- getOption("pdfviewer", default='') if (nchar(pdf)==0) stop("The 'pdfviewer' option is not set. Use options(pdfviewer=...)") system2(pdf, args=c(f)) } }
There are three four small things to note, even in this little offering.
First, the getOption default value is set to a string of length 0 because despite a default NULL return value, the natural disjunction
if (is.null(pdf) || nchar(pdf)==0) ## null or empty
will not do the right thing.
Second, system2 is a nice robust function for whenever you feel the temptation to paste together a command line for system. In short system2, like paste0, is the function you'd hoped they'd written in the first place.
Third, the argument to shell.exec gets run through normalizePath to make a full path. That's because, according to the manual page "most applications [on Windows] interpret files relative to their working directory". This may seem a little strange. That's because it is.
Finally, a note to the unwary cross-platform R programmer: .Platform$OS.type returns 'unix' for unix, linux, and OSX machines. Consequently if you actually need to know whether you are on a Mac then you have to check that
Sys.info()["sysname"]=='Darwin'
is true.
Addendum
There are a confusing number of ways to figure out what the system pdf viewer might be. Above we used getOption("pdfviewer"), which calls options("pdfviewer"), which ultimately depends on the environment variable R_PDFVIEWER being set. You can see what this is set to directly with
Sys.getenv('R_PDFVIEWER')
So why are we using shell.exec for Windows if we can figure out a viewer from an environment variable? Because shell.exec uses Windows file extensions to choose an appropriate application to view things. Conceivably these might not be the same as what R is expecting. Or they might be. Who can tell with Windows?
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.