考虑一个随机的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,只考虑了一个时间序列)。
有人可以帮我吗?
答案 0 :(得分:3)
如果我们要为每一列创建时间序列,请使用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)
})
答案 1 :(得分:1)
@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创建