# Show me the pdf already

February 1, 2013
By

(This article was first published on Will Lowe » R, and kindly contributed to R-bloggers)

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.

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?

To leave a comment for the author, please follow the link and comment on his blog: Will Lowe » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...