
#Export multiple files with for loop in r how to
This code is a good building block for automatically saving to a folder inside a loop, but we still need to know how to dynamically create file names at which to save our plots. To save a scatter plot of the vectors x versus y to the location described above, run these three lines: Jpeg(file = “C://R//SAVEHERE//myplot.jpeg”)Īfter running the plotting object, you need to be sure to turn off the plotting device you created (with the jpeg() command). For example, this code will save the next plotting object to a jpeg file called myplot.jpeg located at “C://R//SAVEHERE” For our purposes, jpeg() takes a path argument that allows us to save (at the location of our choosing via the path) output to a plotting window. The first command you need to know is jpeg() (Alternatively, bmp(), png() or tiff(), depending on your file-type preferences) paired with dev.off(). I’ll start by describing several building-block commands and then at the end I’ll put together a loop that does it all (by way of contrived example). How then can you automatically save plots to a folder without spending too much time? That’s today’s task. This manual-saving method becomes impractical quickly. If you don’t believe me, imagine that you have 1000 plots instead of 26. Even with RStudio, if you produce the plots inside the loop, you still need to save each one individually. It’s no problem if you just produce the plot inside your dreaded loop in RStudio because it keeps all of your plots in the pane. RStudio has a nice feature in that it saves all of your plots in the plotting pane. Just imagine, what if something went wrong and you need to produce the whole set of plots again? You’ll spend too much of your time saving plots and not enough time thinking about whether they are the right plots. The last thing you want to do in this situation is: (1) produce each plot one-by-one, (2) right click on each singly-produced plot to save, (3) give the plot a unique name, and (4) repeat. Furthermore, the loop goes on for a while (say through the 26-letters of the alphabet). Not only do you want to see the plot, but you would like to save each plot for a presentation, report or paper. At each iteration inside the loop, you want to construct a plot. Suppose you’re working on a problem that involves a loop for calculations.
