I'd like to write a function that takes a filename and produces a .pdf file on a *nix platform and a .wmf on a windows platform with that filename and width of 6 inches height 4.

graph <- function(filename){
ext <- ifelse(.Platform$OS.type == "unix", "pdf", "wmf")
name <- paste(filename, ext, sep=".")
ifelse(.Platform$OS.type == "unix", pdf(name, width=6, height=4), wmf(name, width=6, height=4))

That's my attempt but I'm getting this error

Error in ans[test & !nas] <- rep(yes, length.out = length(ans))[test & : replacement has length zero

any ideas? I feel like I'm overlooking something.

+2  A: 

I think the issue is that ifelse returns a value, not do whatever is in the arguments. I've learned this the hard way before: ifelse != shorthand if, ifelse = vectorized if. From the help page:

ifelse(test, yes, no)

'ifelse' returns a value with the same shape as 'test' which is filled with elements selected from either 'yes' or 'no' depending on whether the element of 'test' is 'TRUE' or 'FALSE'.

So just use something like:

if (.Platform$OS.type == "unix") {
  pdf(name, width=6, height=4) 
} else {
  wmf(name, width=6, height=4)
i knew i was overlooking, thanks much
+4  A: 

Here's a somewhat more polished version of your function. Improvements:

  • doesn't mess with your working directory
  • avoids the duplicated if statement by looking up the device function from the extension


graph <- function(filename) {
  ext <- if(.Platform$OS.type == "unix") "pdf" else "wmf"
  dev <- match.fun(ext)
  path <- paste("graphics/", filename, ".", ext, sep = "")

  dev(path, width = 6, height = 4)
I don't think this works. On my Windows installation, match.fun("pdf") works, but match.fun("wmf") fails. Where is the wmf() function? It's not in grDevices...
Actually, it might be called `win.metafile`
it is win.metafile, i should have edited that, my bad