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