季度时间序列月度拆解后匹配月度预测因子时间索引的实现问题
季度拆解月度序列与月度预测变量的时间匹配实现
基础场景
- 待处理的季度更新指标时间序列原始结构:
Quarter Indicator 2010-1 11 2010-2 14 2010-3 15 2010-4 12 2011-1 11 2011-2 18 2011-3 15 2011-4 19 2012-1 14 2012-2 15 2012-3 18 2012-4 16
- 当前已实现的季度转月度拆解代码:
z <- read.zoo(data, FUN = function(x) as.yearqtr(x, "%Y-%q")) ind_month <- zooreg(na.approx(c(t(cbind(z, NA, NA)))), start = as.yearmon(start(z)), freq = 12) new_data <- fortify.zoo(ind_month)
- 配套的月度频次预测变量(示例含2个变量)结构:
Predictor1 Predictor2 12 5 14 4 11 8 7 2 9 6 0 9 15 11 2 6 6 8 12 9 11 14 9 16 4 12 5 3 6 5 2 3 7 8 0 11 3 16 2 18 5 15 6 18 4 16 7 22 3 17 2 9 2 18 7 16 6 14 2 13 5 17 4 12 9 9 6 18 2 6 9 17 4 15 6 13 0 17
由于季度数据需累计满3个月才完成更新,预测变量为月度频次发布,因此预测变量表的时间跨度通常长于拆解后的月度指标序列。
核心目标
- 完成季度数据的月度拆解后,让生成的月度序列时间长度与预测变量表完全匹配;超出原季度拆解覆盖范围的指标值以NA补全,该部分缺失值即为待预测的目标值。
- 适配预测变量表每月新增1行最新观测的更新节奏,实现拆解月度序列的时间索引随预测变量表自动同步拓展。经校验,第一个长度匹配问题解决后,后续仅需在新增数据上重跑全流程代码,即可满足自动同步的需求。
可复现实现代码
# 加载依赖包 library(zoo) library(forecast) # 1. 读取原始季度指标数据 qtr_data <- read.table(text = "Quarter Indicator 2010-1 11 2010-2 14 2010-3 15 2010-4 12 2011-1 11 2011-2 18 2011-3 15 2011-4 19 2012-1 14 2012-2 15 2012-3 18 2012-4 16", header = TRUE) # 2. 执行季度到月度的尺度拆解 z <- read.zoo(qtr_data, FUN = function(x) as.yearqtr(x, "%Y-%q")) ind_month <- zooreg( na.approx(c(t(cbind(z, NA, NA)))), start = as.yearmon(start(z)), freq = 12 ) # 3. 读取月度预测变量数据 monthly_pred <- read.table(text = "Predictor1 Predictor2 12 5 14 4 11 8 7 2 9 6 0 9 15 11 2 6 6 8 12 9 11 14 9 16 4 12 5 3 6 5 2 3 7 8 0 11 3 16 2 18 5 15 6 18 4 16 7 22 3 17 2 9 2 18 7 16 6 14 2 13 5 17 4 12 9 9 6 18 2 6 9 17 4 15 6 13 0 17", header = TRUE) # 4. 生成和预测变量行数完全匹配的月度时间索引 match_index <- seq( from = start(ind_month), by = 1/12, length.out = nrow(monthly_pred) ) # 5. 对齐月度指标序列,超出原覆盖范围的位置自动填充NA ind_month_aligned <- merge( ind_month, zoo(, match_index), all = c(TRUE, TRUE) ) # 截取到匹配索引的完整长度 ind_month_aligned <- window( ind_month_aligned, index(match_index)[1], index(match_index)[length(index(match_index))] ) # 6. 合并生成最终建模数据集 final_dataset <- data.frame( Month = as.Date(match_index), Indicator = coredata(ind_month_aligned), monthly_pred )
实现效果说明:最终生成的数据集长度与预测变量表完全一致,原季度拆解覆盖的月份保留插值得到的Indicator值,超出覆盖范围的Indicator位置自动填充NA。后续每月预测变量新增1行观测后,无需手动调整序列参数,直接重跑全流程代码即可自动延长时间索引,完成长度匹配。
内容的提问来源于stack exchange,提问作者Tamimi
相关产品推荐
相关产品推荐

