Platformer graphics device

I would like to write a function that takes a filename and creates a .pdf file on * nix platform and .wmf on Windows platform with that filename and 6 inches wide 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))
}

      

This is my attempt but I am getting this error

An error in ans [test and! nas] <- rep (yes, length.out = length (ans)) [test and: replacement has length 0

any ideas? I feel like I am missing something.

+2


source to share


2 answers


I think the problem is that ifelse is returning a value and not doing everything in the arguments. I've learned this before: ifelse! = Shorthand if, ifelse = vectorized if. From the help page:

ifelse (test, yes, no)

'ifelse' returns a value with the same as "test", which is filled with items selected from "yes" or "no" depending on whether the item "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)
}

      

+2


source


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

  • doesn't work with your working directory
  • avoids duplicate if statement by looking at device function from 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)
}

      

+5


source







All Articles