r - How to call on.exit() from parent? -


quite few of functions accept file argument (which defaults null) sets graphics output file. e.g., foo() plot screen, , foo(file="bar.png") write plot file "bar.png".

they have code snippet in them:

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

i wish create function replace these 5 lines, but, alas, cannot because on.exit reset graphics device early.

what people in such situation?

this sort of repetition best dealt creating function takes code block , evaluates in special context. example, write:

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

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -