尝试在 dygraphs 中绘制每周 ts 对象时无法将索引转换为适当的类型

could not convert index to appropriate type while attempting to plot weekly ts object in dygraphs

我正在尝试根据每周时间序列创建一个 Holt-Winters 预测,然后绘制原始序列并使用 dygraphs 进行预测。我有 144 周的周五周末数据。出于我的目的,我忽略了某些年份有 53 周的情况。数据的结构可以模拟为:

## create data similar to what I have

week_date <- seq.Date(from = as.Date("2012/05/11"),
                      by = "week",
                      length.out = 144)
set.seed(1)
var1 <- diffinv(rnorm(143))
df <- data.frame(cbind(week_date, var1))

## convert to ts object then
## create Holt Winters forecast

dfts <- ts(df[,2],freq=52, start=c(2012,19))

hw <- HoltWinters(dfts)
p <- predict(hw, 4)
all <- cbind(dfts, p)

## create plots

dygraph(all, "time series dygraph") %>%
      dySeries("var1", label = "Actual") %>%
      dySeries(c("p.lwr", "p.fit", "p.upr"), label = "Predicted")

这会产生以下错误:

Error in as.xts.ts(data) : could not convert index to appropriate type

我尝试了 提出的解决方案,但出现了同样的错误:

> all <- cbind(dfts = as.xts(dfts), p = as.xts(p))
Error in as.xts.ts(dfts) : could not convert index to appropriate type

这里发生了一些事情。问题的根源在于 dygraphdata 参数需要 "Time series data (must be an xts object or an object which is convertible to xts)"(参见 ?dygraph)。

如您所见,将 dfts 转换为 xts 对象失败:

> library(xts)
> dfts <- as.xts(dfts)
Error in as.xts.ts(dfts) : could not convert index to appropriate type 

如果您尝试直接创建 xts 对象:

> dfts <- xts(dfts)
Error in xts(dfts) : order.by requires an appropriate time-based object

这是因为,默认情况下 xts 使用 index(x) 作为 order.by 参数。来自 ?xts:

order.by    a corresponding vector of unique times/dates - 
            must be of a known time-based class
...
Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, 
as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.

如果你查看 dfts 上的索引:

> str(index(dfts))
 num [1:148] 2012 2012 2012 2012 2012 ...

> head(index(dfts))
[1] 2012.346 2012.365 2012.385 2012.404 2012.423 2012.442

索引是数字,而 xts 需要某种类型的日期对象,因此您需要对其进行转换。

首先,我通过将每个对象转换为 zoo 对象然后合并来创建 all 对象:

> library(zoo)
> # You'll need prediction.interval=TRUE to get the bounds:
> p <- predict(hw, 4, prediction.interval=TRUE)
> all <- merge(actual=as.zoo(dfts), predicted=as.zoo(p))
> head(all)
             actual fit upr lwr
2012(19)  0.0000000  NA  NA  NA
2012(20) -0.6264538  NA  NA  NA
2012(21) -0.4428105  NA  NA  NA
2012(22) -1.2784391  NA  NA  NA
2012(23)  0.3168417  NA  NA  NA
2012(24)  0.6463495  NA  NA  NA

然后,您可以通过将十进制索引转换为日期来将其转换为 xts 对象。有几种方法可以做到这一点,但最简单的可能是使用 lubridate 包中的 date_decimal 函数:

> library(lubridate)
> all.xts <- xts(all, date_decimal(index(all)))

现在,调整 dygraph 函数中的参数:

> dygraph(all.xts, "time series dygraph") %>%
      dySeries("actual", label = "Actual") %>%
      dySeries(c("lwr", "fit", "upr"), label = "Predicted")