建立和扩展预测功能

时间:2019-04-17 12:58:59

标签: r for-loop

此代码使用预测包进行预测。此代码的最终输出是使用snaive方法预测的三个列表(SNAIVE_PIT,SNAIVE_CIT和SNAIVE_VAT)。

#CODE
library(forecast)
        # Making data frame
      DATA_SET<-data.frame(
        PIT=seq(1, 48, by = 2),
        CIT=seq(1, 24, by = 1),
        VAT=seq(1, 94, by = 4)
      )
     View(DATA_SET)

      # FOR LOOP
     for(i in 1:ncol(DATA_SET)){
        # Build a ts for this column
        timeseries <- ts(DATA_SET[,i], start=c(2016,1), frequency = 12)
        # Build a foreacst based on the ts
        forecast <- snaive(timeseries,h=5)
           # rename the forecast according to the original variable name
        colname <- colnames(DATA_SET)[i]
        forecastName <- paste("SNAIVE_",colname," <- forecast",sep="")
        eval(parse(text = forecastName))
      }

但是编码并不以上述代码结尾。也就是说,我必须用一些其他东西来扩展此代码。

首先,如何将这一行添加到上面的代码中(FOR LOOP部分)?

#NEW CODE 1
SNAIVE_ALL<-mapply(SNAIVE_PIT, SNAIVE_CIT,SNAIVE_VAT, FUN=list, SIMPLIFY=FALSE)

第二,如何将这一行放入上面的代码中(FOR LOOP部分)?

#NEW CODE 2
   SNAIVE_PIT_ACCURANCY<-accuracy(SNAIVE_PIT)
    SNAIVE_CIT_ACCURANCY<-accuracy(SNAIVE_CIT)
     SNAIVE_VAT_ACCURANCY<-accuracy(SNAIVE_VAT)

  SNAIVE_ACCURANCY<-rbind(SNAIVE_PIT_ACCURANCY,SNAIVE_CIT_ACCURANCY,SNAIVE_VAT_ACCURANCY)

任何人都可以帮助我使用此代码吗?

1 个答案:

答案 0 :(得分:0)

我个人认为您是以完全错误的方式执行此操作的,R代码并不是要一直生成和合并列表,您可以以功能性方式进行所有这些操作,首先您需要考虑一下列表结构会的。

我推荐以下结构

每个数据集都是一个列表,每个列表都接收一个生成两个列表(预测和准确性)的函数。

让我们的代码。

# I recommend spliting this function but I am lazy

prediction_funtion <- function(x) {
  x <- ts(x, start=c(2016,1), frequency = 12)
  model <- snaive(x)
  forecasts_results <- forecast(model,5)
  accuracy_results <- accuracy(model)
  return(list(forecast = forecasts_results,accuracy =accuracy_results))
}

map(list_df,prediction_funtion)