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?

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