这可以通过使用
purrr
包中的
lists
和
map
函数来完成。
让我们构建一些数据:
library(tidyverse)
set.seed(123)
tb1 <- tibble(
ds = seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day"),
y = sample(365)
)
tb2 <- tibble(
ds = seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day"),
y = sample(365)
)
ts_list <- list(tb1, tb2)
构建和预测:
library(prophet)
m_list <- map(ts_list, prophet)
future_list <- map(m_list, make_future_dataframe, periods = 40)
forecast_list <- map2(m_list, future_list, predict)
head(forecast_list[[1]]$yhat)
[1] 179.5214 198.2375 182.7478 173.5096 163.1173 214.7773
head(forecast_list[[2]]$yhat)
[1] 172.5096 155.8796 184.4423 133.0349 169.7688 135.2990
更新(仅输入部分,构建和预测部分相同):
基于OP的请求,我创建了一个新的示例,基本上您需要将所有内容再次放入列表对象中:
set.seed(123)
tb1 <- tibble(
ds = seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day"),
productA = sample(365),
productB = sample(365)
)
head(tb1)
ds productA productB
<date> <int> <int>
1 2018-01-01 105 287
2 2018-01-02 287 71
3 2018-01-03 149 7
4 2018-01-04 320 148
5 2018-01-05 340 175
6 2018-01-06 17 152
ts_list <- tb1 %>%
gather("type", "y", -ds) %>%
split(.$type)
ts_list <- lapply(ts_list, function(x) { x["type"] <- NULL; x })