stevec
stevec

Reputation: 52967

Writing a file from inside a function in R

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

Upvotes: 1

Views: 433

Answers (1)

Bob Zimmermann
Bob Zimmermann

Reputation: 993

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.

Upvotes: 2

Related Questions