1

I want to write a file from inside a function in R. When I place working code inside a function, I do not get any error, however no file is created

A minimal example


# Make a simple plot 

plot(1:15) # make plot
p <- recordPlot() # assign plot
p # view plot


# Write the plot to a file (this works)

filename <- "myfile.png"
png(filename)
p
dev.off()


# Move the same code inside a function and call it

write_file <- function(my_plot) {
  filename <- "myfile.png"
  png(filename)
  my_plot
  dev.off()

}

write_file(p) 
# Nothing errors, but no file is created

What I've tried so far

I thought maybe the function can't access the plot object. But it seems to be able to call it from within the function, so it seems like that isn't the issue (although I'm not 100% sure)


plot.new() # clears plot area
function_access_plot <- function(plot_object) {
  plot_object
}
function_access_plot(p)
# This successfully displays the plot
stevec
  • 41,291
  • 27
  • 223
  • 311
  • Do you want a [temporary](https://stat.ethz.ch/R-manual/R-devel/library/base/html/tempfile.html) file? I'm not sure if you just want to save your plot or to store it in a temporary file. [This post](https://stackoverflow.com/questions/7144118/how-to-save-a-plot-as-image-on-the-disk) could help you if you want to save the plot into disk though. – patL Feb 14 '19 at 10:55
  • @patL `tempfile` just gives the file a random name in a certain directory. But the problem persists irrespective of what the file is named and where it is saved to. – stevec Feb 14 '19 at 10:58
  • 1
    @patL I will edit the question to remove tempfile, as it's an unnecessary complication that distracts from the crux of the question, which is why doesn't a file save when done from inside a function – stevec Feb 14 '19 at 11:00

1 Answers1

2

Barring preemption, the tempfile suggested can be written to, but you never write to it because simply stating the value returned from recordPlot() will not write to the current device. If you modify your function as so:

write_file <- function(my_plot) {
  filename <- "myfile.png"
  png(filename)
  replayPlot(my_plot)
  dev.off()
}

it works for me.

Bob Zimmermann
  • 938
  • 7
  • 11