r - 如何在预测后保留 xts 时间序列数据中的日期

标签 r ggplot2 time-series xts

请考虑这个小数据集:

library(xts)
library(ggplot2)
library(forecast)

data <- data.frame(idDate = c("12-12-2012", "13-12-2012", "14-12-2012", "16-12-2012", "19-12-2012"), score= c(110, 120, 130, 200, 180))
date <- as.Date(as.character(data$idDate), "%d-%m-%Y")
score <- as.numeric(data$score)

myxts <- xts(score, date)
autoplot(myxts)

到目前为止,沿 x 轴的日期(索引)已保留,但只要我调用预测,沿 x 轴的日期就会转换为整数。见下文:

d.arima <- auto.arima(myxts)
d.forecast <- forecast(d.arima, level = c(95), h = 3)
d.forecast
autoplot(d.forecast)

问题: myxts 中的索引如何保存? 有没有办法告诉 forecastauto.arima 保留来自 myxts 的日期(索引)?

最佳答案

问题是您在两个不同的时间系统中工作:xts 是不规则的(使用不需要周期性的日期)而 forecast/ts 系统是规则的(使用均匀间隔的数字序列)。我们通过创建一个可以映射到预测的 future 日期序列来解决这个问题。

这是一个详细的解决方案。 forecastxts 包用于重新创建预测。 timekit 包用于创建 future 的日期。 ggplot2 包用于绘图。

问题的关键是创建 future 日期。请注意,您所拥有的是不规则间隔的。 tk_make_future_timeseries() 使用匹配输入时间索引的周期。如果这不正确,您可以根据需要分别使用 skip_valuesinsert_values 删除和插入日期。


library(forecast)
library(xts)
library(ggplot2)
library(timekit)

# Recreate xts data, d.arima and d.forecast
data <- data.frame(idDate = c("12-12-2012", "13-12-2012", "14-12-2012", "16-12-2012", 
                              "19-12-2012"), 
                   score= c(110, 120, 130, 200, 180))
date <- as.Date(as.character(data$idDate), "%d-%m-%Y")
score <- as.numeric(data$score)
myxts <- xts(score, date)
d.arima <- auto.arima(myxts)
d.forecast <- forecast(d.arima, level = c(95), h = 3)

# Extract index
idx <- tk_index(myxts)
idx
#> [1] "2012-12-12" "2012-12-13" "2012-12-14" "2012-12-16" "2012-12-19"

# Make future index
idx_future <- tk_make_future_timeseries(idx, n_future = 3)
idx_future
#> [1] "2012-12-20" "2012-12-22" "2012-12-23"

# Build xts object from forecast
myts_future <- cbind(y = d.forecast$mean, y.lo = d.forecast$lower, y.hi = d.forecast$upper)
myxts_future <- xts(myts_future, idx_future)
myxts_future
#>              y     y.lo     y.hi
#> 2012-12-20 148 70.33991 225.6601
#> 2012-12-22 148 70.33991 225.6601
#> 2012-12-23 148 70.33991 225.6601

# Format original xts object
myxts_reformatted <- cbind(y = myxts, y.lo = NA, y.hi = NA)
myxts_final <- rbind(myxts_reformatted, myxts_future)

# Plot forecast - Note ggplot uses data frames, tk_tbl() converts to df
tk_tbl(myxts_final) %>%
    ggplot(aes(x = index, y = y)) +
    geom_point() +
    geom_line() +
    geom_ribbon(aes(ymin = y.lo, ymax = y.hi), alpha = 0.2)

关于r - 如何在预测后保留 xts 时间序列数据中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44478893/

相关文章:

r - ggplot2 直方图图例太大

python - 使用 matplotlib 绘制大量时间序列数据点

r - 如何在 R 中对 2x2x2 设计进行纵向分析?

r - 是否有函数可以反转 data.table 中值的出现次数?

r - 使用函数参数作为名称在 R 中保存对象

arrays - 将 3 维数组转换为数据框

r - R 的同比百分比变化

mysql - 通过 R 中的所有表运行 MySQL 查询

r - 将 ggplot 对象转换为使用 Open Sans Semibold 字体的 svg

r - 如何使用R精确匹配整个数据集中的两列值