首页 > 解决方案 > 使用 R 预测多个时间序列

问题描述

考虑一个随机的data.frame:

d <- data.frame(replicate(10,sample(0:1,1000,rep=TRUE)))

我想将每一行视为一个独特的时间序列(在这种情况下为十年)。所以首先,我需要将数据转换为时间序列。我尝试了以下代码:

d1 <- ts(d, start=2000, end=2009)

但是,我认为这段代码将时间序列视为 100 年的一个长时间序列。就我而言,我想要 10 年的 1000 个独特的时间序列。

然后我想预测每 1,000 个时间序列(比如说 1 年)。通过使用以下代码:

fit <- tslm(d1~trend) fcast <- forecast(fit, h=1) plot(fcast)

我得到一个预测(因为我在我的数据集 d1 中只考虑一个时间序列)。

谁能帮我这个?

标签: rtime-seriesforecast

解决方案


如果我们正在寻找为每一列创建时间序列,然后遍历数据集的列lapply并创建它

library(forecast)
lst1 <- lapply(d, ts, start = 2000, end = 2009)
#If we want to split by `row`
#lst1 <- lapply(asplit(as.matrix(d), 1), ts, start = 2000, end = 2009)
par(mfrow = c(5, 2))
lapply(lst1, function(x) {
        fit <- tslm(x ~ trend)
        fcast <- forecast(fit, h = 1)
        plot(fcast)
   })

在此处输入图像描述


推荐阅读