我有一组传感器数据的数据框架
我的数据框架如下所示:
pressure datetime4.848374 2016-04-12 10:04:00 4.683901 2016-04-12 10:04:32 5.237860 2016-04-12 10:13:20
现在,我想应用ARIMA
来进行预测分析。
由于数据采样不均匀,我按小时对其进行了聚合,聚合后的数据如下所示:
datetime pressure"2016-04-19 00:00:00 BST" 5.581806"2016-04-19 01:00:00 BST" 4.769832"2016-04-19 02:00:00 BST" 4.769832 "2016-04-19 03:00:00 BST" 4.553711 "2016-04-19 04:00:00 BST" 6.285599 "2016-04-19 05:00:00 BST" 5.873414
每小时的压力数据如下图所示:
但是,我无法创建ts
对象,因为我不知道小时数据的频率应该设为多少。
回答:
你的问题已经在评论部分得到了回答,但为了再次强调,你应该将频率设为24,因为你要预测的是小时数据:
sensor = ts(hourlyPressure, frequency = 24)
关于你接下来提到的在图表中修正日期的问题,我们先从一些示例数据开始:
###用于预测的数字序列 hourlyPressure<-c(1:24, 12:36, 24:48, 36:60)###伴随的日期序列dates<-seq(as.POSIXct("2016-04-19 00:00:00"), as.POSIXct("2016-04-23 02:00:00"), by="hour")
现在我们可以将hourlyPressure数据设置为ts()对象(先暂时忽略日期)
sensor <- ts(hourlyPressure, frequency=24)
现在拟合你的ARIMA模型,在这个例子中,我将使用forecast包中的auto.arima函数,因为找到最佳的ARIMA模型并不是这里的重点(尽管使用auto.arima()是找到最适合你数据的ARIMA模型的一种相当稳健的方法):
###拟合传感器数据的ARIMA模型sensor_arima_fit<- auto.arima(sensor)
然后你可以通过在plot()函数中指定x值来绘制带有适当日期的数据
plot(y=sensor_arima_fit$x, x=dates)
更复杂一些的是,当我们预测数据并希望绘制原始数据和预测结果,并且日期正确时。
###现在使用上面拟合的ARIMA模型预测未来(假设是两天)forecast_sensor <- forecast(sensor_arima_fit, h = 48)
现在要绘制原始数据和预测结果,并确保日期正确,我们可以这样做:
###将h设为与上面相同h <- c(48)###计算预测值的日期forecasted_dates<-seq(dates[length(dates)]+(60*60)*(1), dates[length(dates)]+(60*60)*(h), by="hour")###现在绘制数据plot(y=c(forecast_sensor$x, forecast_sensor$mean), x=seq(as.POSIXct("2016-04-19 00:00:00"),as.POSIXct(forecasted_dates[length(forecasted_dates)]), by="hour"), xaxt="n", type="l", main="原始序列和预测的图表", xlab="日期", ylab="压力")###正确格式化的x轴axis.POSIXct(1, at=seq(as.POSIXct("2016-04-19 00:00:00"), as.POSIXct(forecasted_dates[length(forecasted_dates)]), by="hour"), format="%b %d", tick = FALSE)
这将绘制原始数据和预测结果,并且日期是正确的。然而,就像forecast包提供的那样,我们可能希望预测结果以蓝色显示。
###保持与之前相同的图表plot(y=c(forecast_sensor$x, forecast_sensor$mean), x=seq(as.POSIXct("2016-04-19 00:00:00"),as.POSIXct(forecasted_dates[length(forecasted_dates)]), by="hour"), xaxt="n", type="l", main="原始序列和预测的图表", xlab="日期", ylab="压力")axis.POSIXct(1, at=seq(as.POSIXct("2016-04-19 00:00:00"), as.POSIXct(forecasted_dates[length(forecasted_dates)]), by="hour"), format="%b %d", tick = FALSE)###这次,我们为预测结果添加不同颜色的线条lines(y=forecast_sensor$mean, x= forecasted_dates, col="blue")