有没有办法使用 tidyverts 包按键创建时间序列交叉验证集?我似乎无法正确处理。以下是我尝试的代表。
该示例涉及为预测创建时间序列交叉验证(提前 1 步的切片)。键变量有 2 个不同的值,我希望有一个包含两个键的时间序列切片的 tsibble。当我尝试对两个 tsibble 进行行绑定时,出现错误。
library(dplyr)
library(tibble)
library(tsibble)
# helper function
create_cv_slices <- function(data, forecast_horizon) {
data %>%
dplyr::slice(1:(nrow(data) - forecast_horizon)) %>%
tsibble::stretch_tsibble(.init = nrow(data) - 2 * forecast_horizon, .step = 1)
}
# get data
raw_tsbl <- tibble::tribble(
~index, ~key, ~Revenue, ~Claims,
20160101, "series1", 11011836.1, 5386836.696,
20160201, "series1", 11042641.16, 9967325.715,
20160301, "series1", 11445687.52, 10947197.89,
20160401, "series1", 11252943.11, 6980431.415,
20160101, "series2", 12236155, 12526224,
20160201, "series2", 8675364, 9812904,
20160301, "series2", 10081130, 8423497,
20160401, "series2", 14840111, 8079813
) %>%
dplyr::mutate(index = tsibble::yearmonth(as.character(index))) %>%
tsibble::as_tsibble(index = index, key = key)
keys <- unique(raw_tsbl$key)
# split & combine
tbl1 = raw_tsbl %>%
dplyr::filter(key == keys[1]) %>%
create_cv_slices(., forecast_horizon = 1) %>%
tibble::as_tibble()
tbl2 = raw_tsbl %>%
dplyr::filter(key == keys[2]) %>%
create_cv_slices(., forecast_horizon = 1) %>%
tibble::as_tibble()
dplyr::bind_rows(tbl1, tbl2) %>%
tsibble::as_tsibble(index = index, key = key)
#> Error: A valid tsibble must have distinct rows identified by key and index.
#> Please use `duplicates()` to check the duplicated rows.
谢谢你。