2
votes

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){
setwd("graphics")
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
oh also the first ifelse works, it's the second where the error occurredDan

2 Answers

5
votes

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)
}
2
votes

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)
}