在R中使用时间序列预测多个时序数据

4
考虑一个随机数据框:
```R d <- data.frame(replicate(10,sample(0:1,1000,rep=TRUE))) ```
我想将每一行视为一个唯一的时间序列(在这种情况下是十年)。因此,首先需要将数据转换为时间序列。我尝试了以下代码:
```R d1 <- ts(d, start=2000, end=2009) ```
但是,这段代码认为时间序列是100年的长时间序列。在本例中,我想要1,000个独立的10年时间序列。
然后,我想要预测每一个1,000个时间序列(假设1年)。使用以下代码:
```R fit <- tslm(d1~trend) fcast <- forecast(fit, h=1) plot(fcast) ```
我得到了一个预测结果(因为在我的数据集 d1 中只考虑了一个时间序列)。
谁能帮我解决这个问题?
2个回答

4

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

enter image description here


太好了。谢谢!但是,当我运行它时,我遇到了“Error in plot.new() : figure margins too large”的错误。我先运行了我的数据集d,然后运行了你的代码。我做错了什么吗? - Michael
@Michael 你可能是在使用Rstudio吧?只需要增加绘图窗口大小即可。 - akrun
一个新手问题:但是我该怎么做呢? - Michael
@Michael 我想用光标拉伸绘图窗口。此外,在较小的窗口中,您可以更改 par(mfrow = c(2, 2)),即每行2个图,总共4个图。 - akrun
1
当然。我把它拉到了错误的方向。现在它可以工作了。非常感谢! :-) - Michael
显示剩余5条评论

2
@akrun展示了如何使用基本R和forecast包来完成这个任务。
以下是使用新的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)

创建于2019年10月11日,使用reprex包(v0.3.0)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接