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?