【问题标题】:How can I turn my ts forecast into a dataframe with date values?如何将我的 ts 预测转换为具有日期值的数据框?
【发布时间】:2021-01-01 12:00:18
【问题描述】:

我正在使用 arima 开发一个需要导出到数据库的预测模型。我需要把我的预测变成一个数据框。我已经以一种精心设计的方式完成了这项工作,但我希望有一些更简单的方法,这样我就不必在其中硬编码日期了。

例如,为了获得预测,我正在创建一个“拟合”模型,然后运行 ​​fcst1 <- forecast(fit, 4) 以获得四个月的价值。

这是我打印预测时的结果格式:

         Point Forecast   Lo 80    Hi 80   Lo 95    Hi 95
Jan 2021       x
Feb 2021       x
Mar 2021       x
Apr 2021       x 

我只想要点预测,我知道我可以从 forecast$mean 中得到,但我也想要日期列。我还将多个预测(针对不同的细分市场)合并到一张表中,因此目前我可以通过以下方式获得结果:

months <- c('Jan-2021', 'Feb-2021', 'Mar-2021', 'Apr-2021')
forecasts <- as.data.frame(rbind(cbind(months, fcst1$mean, "Segment 1"), 
                            cbind(months, fcst2$mean, "Segment 2"),
                            cbind(months, fcst3$mean, "Segment 3"),
                            cbind(months, fcst4$mean, "Segment 4"),
                            cbind(months, fcst5$mean, "Segment 5"),
                            cbind(months, fcst6$mean, "Segment 6"),
                            cbind(months, fcst7$mean,"Segment 7")))

这将预测结果分为三列:月份、预测和细分。

    months       fcst$mean      "Segment"
1  Sep-2020           2        Segment 1
2  Oct-2020           1        Segment 1
3  Nov-2020           3        Segment 1
4  Dec-2020           2        Segment 1

但是,为了在未来可重复,如果我不必在几个月内进行硬编码,那将是理想的,并且它可以从预测中提取它(因为它已经存在了)。有没有办法从 ts 对象中提取日期作为数据框列?

rownames(fcst1) 返回为 null,我无法在互联网上找到答案。提前致谢!

*注意:日期为 yearmon 格式

【问题讨论】:

    标签: r dataframe time-series format arima


    【解决方案1】:

    如果对象已在全局环境中创建,请使用mget 获取list 中的值

    Forecast <- sapply(mget(ls(pattern = '^fcst\\d+$')), function(x) x$mean)
    

    现在,我们使用data.frame 来构造一个data.frame

    data.frame(months, Forecast, Segment = paste0("Segment", seq_along(Forecast))))
    

    要从forecast 对象自动获取月份,请使用index

    outlst <- lapply(mget(ls(pattern = '^fcst\\d+$')), function(x) 
            data.frame(months = index(x), Forecast = x$mean))
    do.call(rbind, Map(cbind, outlst, Segment = paste("Segment", seq_along(outlst))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-19
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多