Search code examples
rlapplyforecast

Extracting value from forecasting object


I am foresting with combination of data sets from fpp2 package and forecasting function from the forecast package. Output from this forecasting is object list with SNAIVE_MODELS_ALL.This object contain forecast from Consumption,Income,Production and Savings.

library(dplyr)
library(forecast)
library(fpp2)

MY_DATA<-uschange[,1:4]

# 1.FORECAST FUNCTION          
FORECASTING_FUNCTION_SNAIVE <- function(Z, hrz = 5) {
  timeseries <- msts(Z, start = 1970, seasonal.periods = 4)
  forecast <- snaive(timeseries, biasadj = TRUE, h =  hrz)
}     
FORECASTING_LIST_SNAIVE <- lapply(X = MY_DATA, FORECASTING_FUNCTION_SNAIVE)

# 2.FORECASTING
 SNAIVE_MODELS_ALL<-lapply(FORECASTING_LIST_SNAIVE,  forecast)  

So my intention is to extract only mean forecast values from all foretasted series(Consumption,Income,Production and Savings) of list of SNAIVE_MODELS_ALL. Actually paths of this values are :

SNAIVE_MODELS_ALL$Consumption$mean
SNAIVE_MODELS_ALL$Income$mean
SNAIVE_MODELS_ALL$Production$mean
SNAIVE_MODELS_ALL$Savings$mean

I try with this code, but I can't extract only mean values

test<-lapply(SNAIVE_MODELS_ALL,ts.union)

So can anybody help me how to resolve this problem and extract only mean value ?


Solution

  • You are almost there. If you do lapply on SNAIVE_MODELS_ALL, it iterates through every top level element of the list, e.g SNAIVE_MODELS_ALL[["Consumption"]]. So what's left is to call out the mean for every element.

    lapply(SNAIVE_MODELS_ALL,function(i)i$mean)
    # or lapply(SNAIVE_MODELS_ALL,"[[","mean")
    
    $Consumption
              Qtr1      Qtr2      Qtr3      Qtr4
    2016                               0.5616798
    2017 0.4046822 1.0477074 0.7295978 0.5616798
    
    $Income
              Qtr1      Qtr2      Qtr3      Qtr4
    2016                               0.7400626
    2017 0.5190254 0.7237208 0.6447008 0.7400626
    
    $Production
               Qtr1       Qtr2       Qtr3       Qtr4
    2016                                  -0.8455464
    2017 -0.4179305 -0.2033188  0.4749184 -0.8455464
    
    $Savings
               Qtr1       Qtr2       Qtr3       Qtr4
    2016                                   3.4827860
    2017  2.2365341 -2.7215011 -0.5728579  3.4827860