I have a list of model objects called allAR1
. For each model object, I need to use the tsdiag
function to produce the diagnostics plot and then save that plot to a folder.
I am trying to use a combination of jpeg(), lapply and dev.off() to apply tsdiag
to each model and then save the resulting plot as an image file. The problem is that this only seems to save the diagnostic plot for the first model in the allAR1
list, whereas I would like to save the diagnostic plots for all models in allAR1
.
Here is my code and a reproducible example:
library(tseries)
data(nino)
nino = list(nino3 = nino3, nino4 = nino3.4)
ar <- function(dat, idx, order, m) {
paes = arima(dat, order = order)
bic = paes$loglik + m*log(length(dat))
res = residuals(paes)
all = list(paes = paes,
bic = bic,
res = res)
assign(idx, all)
return(all)
}
allAR1 = mapply(ar, dat = nino, idx = names(nino),
MoreArgs = list(order = c(1,0,0), m = 1),
SIMPLIFY = F)
allpaes = lapply(allpaes, function(x) x$paes)
jpeg(sprintf("C:/Users/owner/Documents/%s.jpeg", names(nino)))
lapply(allAR1, tsdiag, gof.lag = 1000)
dev.off()
I have also tried lapply(allAR1, function(x) {jpeg(sprintf("C:/Users/owner/Documents/%s.jpeg", names(nino))); tsdiag(x$paes, 1000); dev.off()})
. However, this gives me the same result as the code above.
Any help would be greatly appreciated as I am not sure where I am going wrong.
Here's a code snippet to get you started:
library(tseries)
#from tsdiag help page
fit <- arima(lh, c(1,0,0))
#make an arbitrary list of model fits
models <- list(m1 = fit, m2 = fit)
lapply(1:length(models), function(x){
jpeg(paste0(names(models)[x], ".jpeg"))
tsdiag(models[[x]])
dev.off()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With