1

Quite a few of my functions accept file argument (which defaults to NULL) which sets the graphics output file. E.g., foo() will plot to the screen, and foo(file="bar.png") will write the plot to file "bar.png".

They have this code snippet in them:

  if (!is.null(file)) {
    cat("*** writing",file,"\n")
    do.call(tools::file_ext(file),list(file = file)) # set the device
    on.exit(dev.off())
  }

I wish I could create a function which would replace these 5 lines, but, alas, I cannot because on.exit would reset the graphics device too early.

What do people do in such a situation?

4

1 回答 1

0

这种重复最好通过创建一个函数来处理,该函数接受一个代码块并在一个特殊的上下文中对其进行评估。例如,您可以编写:

capture_png <- function(file, code) {
  if (!is.null(file)) {
    message("writing ", file)
    png(file)
    on.exit(dev.off())
  }
  code
}

capture_png(NULL, plot(1:10))
capture_png("test.png", plot(1:10))
于 2013-08-09T22:30:48.797 回答