How to extract a forecast from a forecast in R?

I am running a VAR across a time series with multiple locations. Suppose that 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 predictions pred$fcst$loc1[,1] etc. But suppose I want to write a function for this that takes location names as an input variable (for example, LOC=c("loc1","loc2","loc3")) . How can i do this?

+4
source share
2 answers

You can use lapply as follows:

  lapply(predict(pp)$fcst[LOC],'[',,1) 

For instance:

 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 
+5
source

How about using:

 locs <- sapply(pred$fcst[LOC], function (k) k[ , 1]) 

The idea is that pred$fcst is a named list. You put the names you want in the LOC . Now we can collect the elements whose names are in the LOC , and then extract the first column from each in the locs .

+3
source

Source: https://habr.com/ru/post/1488377/


All Articles