使用 R 预测多个时间序列

Forecast multiple time-series in R using

考虑随机 data.frame:

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

我想将每一行视为一个独特的时间序列(在本例中为十年)。所以首先,我需要将数据转换为时间序列。我试过以下代码:

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

但是,我认为这段代码将时间序列视为一个长达 100 年的时间序列。在我的例子中,我想要 10 年的 1,000 个独特的时间序列。

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

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

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

谁能帮我解决这个问题?

如果我们要为每一列创建时间序列,则使用 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)
   })

@akrun 展示了如何使用基础 R 和预测包来做到这一点。

以下是如何使用专为处理此类事情而设计的新 fable 程序包来完成同样的事情。

library(tidyverse)
library(tsibble)
library(fable)

set.seed(1)
d <- data.frame(replicate(10, sample(0:1, 1000, rep = TRUE)))
# Transpose
d <- t(d)
colnames(d) <- paste("Series",seq(NCOL(d)))
# Convert to a tsibble
df <- d %>%
  as_tibble() %>%
  mutate(time = 1:10) %>%
  gather(key = "Series", value = "value", -time) %>%
  as_tsibble(index = time, key = Series)
df
#> # A tsibble: 10,000 x 3 [1]
#> # Key:       Series [1,000]
#>     time Series   value
#>    <int> <chr>    <int>
#>  1     1 Series 1     0
#>  2     2 Series 1     1
#>  3     3 Series 1     0
#>  4     4 Series 1     0
#>  5     5 Series 1     1
#>  6     6 Series 1     0
#>  7     7 Series 1     0
#>  8     8 Series 1     0
#>  9     9 Series 1     1
#> 10    10 Series 1     0
#> # … with 9,990 more rows
# Fit models
fit <- model(df, TSLM(value ~ trend()))
# Compute forecasts
fcast <- forecast(fit, h = 1)
# Plot forecasts for one series
fcast %>%
  filter(Series == "Series 1") %>%
  autoplot(df)

reprex package (v0.3.0)

于 2019-10-11 创建