如何从R语言forecast列表中提取Point Forecast值?
提取forecast列表中所有元素的Point Forecast值
从你提供的forecast对象结构来看,每个元素里的Point Forecast对应的就是对象中的mean时间序列字段。下面是几种简单的方法来提取所有89个元素的这个值:
方法1:基础R实现
不需要额外安装包,用lapply遍历列表即可:
# 提取所有Point Forecast,得到一个包含时间序列的列表 point_forecasts_list <- lapply(forecasts, function(forecast_obj) forecast_obj$mean) # 如果需要转换成纯数值向量(每个预测值是单个数值,更方便后续使用) point_forecasts_vector <- unlist(lapply(forecasts, function(forecast_obj) as.numeric(forecast_obj$mean)))
方法2:用purrr包简化代码
如果你习惯用tidyverse风格的代码,purrr包的函数会更简洁:
library(purrr) # 提取为时间序列列表 point_forecasts_list <- map(forecasts, ~ .x$mean) # 直接转换成数值向量 point_forecasts_vector <- map_dbl(forecasts, ~ as.numeric(.x$mean))
小说明
之所以用as.numeric,是因为mean字段是一个长度为1的时间序列对象(从你给的str输出能看到mean : Time-Series [1:1]),转换成数值后就得到了纯粹的预测数值,避免时间序列属性对后续操作的影响。
内容的提问来源于stack exchange,提问作者Davide Lorino
相关产品推荐
相关产品推荐

