user3476463
user3476463

Reputation: 4575

Return Model with lowest value from list

I have the code below which I think creates every combination for a set of parameters with given ranges, then creates all Arima models for those order parameter combinations, then creates forecasts for all the models, and then calculates the mape, (which is an error measure), for each of the forecasts.

I'm curious if I've used lapply correctly to forecast the models and to calculate the mape for each model? I haven't used lapply that much.

For the final step I would like to return the model or order parameters which creates the forecast with the lowest mape. If anyone can suggest how to do that, or point out a similar example I would be grateful.

Code:

library("fpp")

## Partition Data
tsTrain <- window(hsales,end=1989.99)
tsTest <- window(hsales,start=1990)

## Set Ranges for parameters
pvar<-1:10
dvar<-1:2
qvar<-1:7

## Create all combinations of parameters
OrderGrid<-expand.grid(pvar,dvar,qvar)

## Create model for each combination of parameters
aFit <- function(a,b,c) {Arima(tsTrain, order=c(a,b,c),method="ML")}
ModFit <- do.call(Vectorize(aFit, SIMPLIFY=FALSE), unname(OrderGrid))

## Forecast Models
funcCast<-function(x){forecast(x,h=71)$mean}
ModCast<-lapply(ModFit,funcCast)

## Calculate Mape for Models
ModAcc<-function(x){accuracy(x,tsTest)[1,5]}
TestAcc<-lapply(ModCast,ModAcc)

Upvotes: 0

Views: 48

Answers (1)

Buggy
Buggy

Reputation: 2100

Here's how you can return your model

Acc_res<-do.call(rbind,TestAcc)
res_num <- which(Acc_res==min(Acc_res))
res_model<-ModFit[[res_num]]
class(res_model)

Let me know if that is what you need. Last line is just for verifying that it is indeed the right class.

Upvotes: 1

Related Questions