使用nycflight13数据时,autolayer无法接收过滤后temp对象问题求助
问题解决:autolayer无法访问tsibble变量的原因及修复
错误原因
原代码中autolayer(meanf(temp, h=20))的写法不符合fpp3的语法规则:meanf()(fable包中的时序预测函数)需要先传入tsibble数据源,再指定要预测的变量,而不是直接引用变量名。管道传递的tsibble没有被meanf()感知到,导致temp变量找不到。
修复方案1:用.指代管道传递的数据源
直接在meanf()中用.代表前面管道传过来的过滤后tsibble,明确指定数据源和预测变量:
weather_tsbl %>% filter(origin == "EWR") %>% autoplot(temp) + autolayer(meanf(., temp, h=20), series="Mean", PI=FALSE)
修复方案2:遵循fpp3标准工作流(推荐)
先拟合模型、生成预测,再叠加到原始数据的图上,这种写法更清晰,也方便扩展多个模型:
# 过滤出EWR站点数据 ewr_weather <- weather_tsbl %>% filter(origin == "EWR") # 绘制原始数据 + 均值预测 ewr_weather %>% autoplot(temp) + autolayer(forecast(model(ewr_weather, MEAN(temp)), h=20), series="Mean", PI=FALSE)
扩展:添加朴素法、漂移法图层
如果要同时叠加多种预测模型,按同样逻辑扩展即可:
ewr_weather %>% autoplot(temp) + # 均值预测 autolayer(forecast(model(ewr_weather, MEAN(temp)), h=20), series="Mean", PI=FALSE) + # 朴素法预测 autolayer(forecast(model(ewr_weather, NAIVE(temp)), h=20), series="Naive", PI=FALSE) + # 漂移法预测 autolayer(forecast(model(ewr_weather, RW(temp ~ drift())), h=20), series="Drift", PI=FALSE) + labs(title = "EWR站点温度预测", y = "温度", x = "时间")
内容的提问来源于stack exchange,提问作者marano.on.ig
相关产品推荐
相关产品推荐

