如何用R语言fpp3包确定数据集整体的趋势与季节性?
在fpp3中分析时间序列的趋势与季节性(以us_gasoline为例)
1. 获取逐行的趋势与季节性数值
你使用的STL()分解方法已经能输出每个时间点的趋势和季节性数值,components()返回的结果里包含核心列:
trend:对应每个时间点的趋势值seasonal:对应每个时间点的季节性波动值season_adjust:去除季节性后的序列(原始值-季节性)remainder:分解后的残差项
可以通过以下代码提取并可视化这些成分:
library(tidyverse) library(fpp3) # 执行STL分解并提取成分 gas_components <- us_gasoline %>% model(STL(Barrels)) %>% components() # 查看前6行的成分数据 head(gas_components) # 可视化原始序列、趋势、去季节性序列 gas_components %>% autoplot(Barrels, colour = "gray", alpha = 0.7) + autolayer(trend, colour = "#E63946", linewidth = 1.2) + autolayer(season_adjust, colour = "#457B9D", linewidth = 0.8) + labs(title = "美国汽油销量的STL分解", y = "桶数", x = "日期") + theme_minimal()
2. 确定整个数据集的季节性周期
方法1:直接查看时间序列频率
us_gasoline是月度时间序列,通过时间索引的频率可直接判断:
# 提取时间列并查看频率(返回12表示月度,即年度周期) us_gasoline %>% pull(Date) %>% frequency()
返回值为12,说明季节性周期是12个月(年度)。
方法2:从季节性成分图判断
观察季节性成分的波动规律,看是否以固定周期重复:
gas_components %>% autoplot(seasonal) + labs(title = "汽油销量的季节性成分", y = "季节性波动值", x = "日期") + theme_minimal()
从图中能看到每年的波动模式基本一致,验证了年度季节性。
方法3:用ACF图辅助验证
自相关函数(ACF)图中,滞后阶数为12、24等处出现显著峰值,说明存在年度季节性:
us_gasoline %>% ACF(Barrels) %>% autoplot() + labs(title = "汽油销量的自相关图", x = "滞后阶数") + theme_minimal()
3. 处理多个趋势/季节性的情况
多个季节性的处理
如果数据存在多个季节性周期(比如日度数据有每日、每周、年度季节性),可以使用TBATS模型,它原生支持多季节性分解:
# 示例:对多季节性数据执行TBATS分解(us_gasoline为单季节性,仅作语法演示) multi_season_components <- us_gasoline %>% model(TBATS(Barrels)) %>% components() # 查看多季节性成分 multi_season_components
多个趋势阶段的处理
如果数据存在趋势突变(比如某时间点后趋势斜率改变),可以通过以下步骤检测并分段计算趋势:
library(segmented) # 拟合初始线性趋势模型 gas_trend_model <- us_gasoline %>% model(TSLM(Barrels ~ trend())) %>% augment() # 检测趋势断点(npsi指定断点数量,这里设为1) seg_fit <- segmented(lm(Barrels ~ .trend, data = gas_trend_model), seg.Z = ~.trend, npsi = 1) # 查看断点位置 seg_fit$psi # 提取分段趋势并可视化 gas_trend_model <- gas_trend_model %>% mutate(segmented_trend = predict(seg_fit)) gas_trend_model %>% autoplot(Barrels, colour = "gray") + autolayer(segmented_trend, colour = "#E63946", linewidth = 1.2) + labs(title = "汽油销量的分段趋势", y = "桶数") + theme_minimal()
内容的提问来源于stack exchange,提问作者Russ Conte
相关产品推荐
相关产品推荐

