如何使用动态回归模型对分组数据进行预测?

时间:2020-07-22 14:05:42

标签: r time-series forecasting arima

我正在尝试使用分组数据同时将回归(具有ARIMA错误的回归)到几个ts预测有雾。

我是整理数据的新手,所以...基本上,我正在重现带有多元ts和多元模型的示例(https://cran.rstudio.com/web/packages/sweep/vignettes/SW01_Forecasting_Time_Series_Groups.html)。

这是一个可复制的示例:

library(tidyverse); library(tidyquant)
library(timetk); library(sweep)
library(forecast)
library(tsibble)
library(fpp3)

# using package data
bike_sales

# grouping data 
monthly_qty_by_cat2 <- bike_sales %>%
  mutate(order.month = as_date(as.yearmon(order.date))) %>%
  group_by(category.secondary, order.month) %>%
  summarise(total.qty = sum(quantity), price.m = mean(price))

# using nest 
monthly_qty_by_cat2_nest <- monthly_qty_by_cat2 %>%
  group_by(category.secondary) %>%
  nest()
monthly_qty_by_cat2_nest

# Forecasting Workflow
# Step 1: Coerce to a ts object class
monthly_qty_by_cat2_ts <- monthly_qty_by_cat2_nest %>%
  mutate(data.ts = map(.x       = data, 
                       .f       = tk_ts, 
                       select   = -order.month,  # take off date 
                       start    = 2011, 
                       freq     = 12))


# Step 2: modeling an ARIMA(y ~ x)
# make a function to map
modeloARIMA_reg <- function(y,x) {
  result <- ARIMA(y ~ x)
  return(list(result))}

# map the function 
monthly_qty_by_cat2_fit <- monthly_qty_by_cat2_ts %>%
  mutate(fit.arima = map(data.ts, modeloARIMA_reg))
monthly_qty_by_cat2_fit

在这里,我不知道地图是否在y(因变量)中使用了正确的变量,但我一直尝试尝试预测并出现错误

# Step 3: Forecasting the model
monthly_qty_by_cat2_fcast <- monthly_qty_by_cat2_fit %>%
  mutate(fcast.ets = map(fit.arima, forecast))

# this give me this error
# Erro: Problem with `mutate()` input `fcast.arima`.
# x argumento não-numérico para operador binário
# i Input `fcast.arima` is `map(fit.arima, forecast)`.
# i The error occured in group 1: category.secondary = "Cross Country Race".
# Run `rlang::last_error()` to see where the error occurred.
# Além disso: Warning message:
#   In mean.default(x, na.rm = TRUE) :
#   argument is not numeric or logical: returning NA

出现两个问题:

我不知道如何输入每组自变量(x)的均值;

以及如何将这些新数据声明为预测参数。

PS:不需要小标题或嵌套结果,我只需要点预测和CI(total.qty lo.95 hi.95)

1 个答案:

答案 0 :(得分:0)

好吧,这段代码为我解决了这个问题。 这样就可以对每个时间序列(分组小摆幅)进行一次预测,并使用这些时间序列的平均值作为预测中的未来数据 欢迎任何评论。

func found(code: String) {
    print(code)
    // convert JSON to object
    do {
        let qrMessage = try JSONDecoder().decode(QrMessage.self, from: code.data(using: .utf8)!)
        print("QrMessage object - device name: " + qrMessage.pcName)
        
    }
    catch let error {
        print(error)
        _ = navigationController?.popViewController(animated: true)
        // call ShowInvalidQrToast() from the new VC that is now on top of the ViewController stack
    }

这可以为我解决问题。 这样就可以对每个组时间序列进行一次预测,并使用这些组时间序列的平均值作为预测中的未来数据 欢迎任何评论。