Here's a bit of refactoring of your myFunc()
function that may fit your needs.
plot_holt_forecast <- function(ts, key = "key-value", pair = "pair-value", outdir = getwd()) {
library(ggplot2)
ncol_time_series <- ncol(ts)
for (index in seq_len(ncol_time_series)) {
holt_forecast <- holt(ts[, index], h = 5, damped = TRUE)
holt_plot <- autoplot(holt_forecast) +
ggtitle(paste(key, pair, index, sep = " - "))
outfile <- sprintf("%s_%s_%03d.pdf", key, pair, index)
ggsave(filename = file.path(outdir, outfile), holt_plot)
}
}
I assumed that you want to iterate over each of the columns of ts
. So for each column in ts
, the function applies holt()
to get the holt_forecast
and then uses autoplot()
to create a ggplot. Rather than printing the plot, it is assigned to the variable holt_plot
.
Then, the function uses key
, pair
, and index
(the column number) to create a unique filename for the plot, which is saved into the working directory as a pdf.
If you need to change the output format, you can replace ".pdf"
with ".png"
or similar, and you can also add options to ggsave()
to change settings like output dimensions, such as width = 10
and height = 8
to get a 10x8in plot. Look at the help page for ?ggsave
for more ideas there.
So if you run the following on ts
data with 10 columns, you'll end up with 10 files saved to your working directory.
plot_holt_forecast(ts, "key1", "pair1")
# key1_pair1_001.pdf
# key1_pair1_002.pdf
# ...