且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在R中分解xts后保留时间戳

更新时间:2023-02-26 20:48:09

这是一个将分解xts系列并返回类"decomposed.xts"的对象的函数.

Here's a function that will decompose an xts series and return an object of class "decomposed.xts".

decompose.xts <-
function (x, type = c("additive", "multiplicative"), filter = NULL) 
{
  dts <- decompose(as.ts(x), type, filter)
  dts$x <- .xts(dts$x, .index(x))
  dts$seasonal <- .xts(dts$seasonal, .index(x))
  dts$trend <- .xts(dts$trend, .index(x))
  dts$random <- .xts(dts$random, .index(x))

  with(dts,
  structure(list(x = x, seasonal = seasonal, trend = trend,
    random = if (type == "additive") x - seasonal - trend else x/seasonal/trend, 
    figure = figure, type = type), class = "decomposed.xts"))
}

这是plot.decomposed.xts()方法:

plot.decomposed.xts <-
function(x, ...)
{
  xx <- x$x
  if (is.null(xx))
    xx <- with(x,
      if (type == "additive") random + trend + seasonal
      else random * trend * seasonal)
  p <- cbind(observed = xx, trend = x$trend, seasonal = x$seasonal, random = x$random)
  plot(p, main = paste("Decomposition of", x$type, "time series"), multi.panel = 4,
       yaxis.same = FALSE, major.ticks = "days", grid.ticks.on = "days", ...)
}

以及在数据上使用它的示例:

And an example of using it on your data:

dex <- decompose.xts(hourplot)
plot(dex)