Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract forecast from predict in R?

Tags:

r

predict

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?

like image 826
deb Avatar asked Feb 17 '23 02:02

deb


2 Answers

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
like image 100
agstudy Avatar answered Feb 24 '23 15:02

agstudy


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.

like image 26
asb Avatar answered Feb 24 '23 16:02

asb