I am running VAR on a time series with multiple locations. Suppose loc1, loc2 and loc3 are the column names of the time series data.
fitVAR = VAR(data,p=order,type = "both", ic = "AIC")
pred = predict(fitVAR,n.ahead = L)
I know that I can get the forecasts by pred$fcst$loc1[,1]
etc. But suppose I want to write a function to do this which takes location names as a input variable(eg, LOC=c("loc1","loc2","loc3"))
. How can I do that?
You can use lapply
like this:
lapply(predict(pp)$fcst[LOC],'[',,1)
For example:
data(Canada)
fit <- VAR(Canada, p = 2, type = "none")
LOC <- c('e','U')
lapply(predict(fit)$fcst[LOC],'[',,'fcst')
lapply(predict(fit)$fcst[LOC],'[',,1)
$e
[1] 962.3490 962.7852 963.1305 963.4016 963.6116 963.7742
963.9023 964.0081 964.1026 964.1954
$U
[1] 6.764097 6.751969 6.804301 6.900299 7.030548 7.184748
7.353441 7.528150 7.701521 7.867432
How about using:
locs <- sapply(pred$fcst[LOC], function (k) k[ , 1])
The idea is that pred$fcst
is a named list. You have put the names you want in LOC
. Now we can collect the elements whose names are in LOC
and then extract the first column from each into locs
.
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