r语言 - 如何分解 xts 半小时时间序列数据



>我有下面的数据集,其中包含半小时的时间序列数据。

Date <- c("2018-01-01 08:00:00", "2018-01-01 08:30:00", 
          "2018-01-01 08:59:59","2018-01-01 09:29:59")
Volume <- c(195, 188, 345, 123)
Dataset <- data.frame(Date, Volume)

我使用以下方法转换为日期格式:

Dataset$Date <- as.POSIXct(Dataset$Date)

创建 xts 对象

library(xts)
Dataset.xts <- xts(Dataset$Volume, order.by=Dataset$Date)

当我尝试根据此 Q 分解它时:

attr(Dataset.xts, 'frequency')<- 48
decompose(ts(Dataset.xts, frequency = 48))

我得到:

Error in decompose(ts(Dataset.xts, frequency = 48)) : 
  time series has no or less than 2 periods

正如我在评论中提到的,您需要as.ts而不是ts。此外,您指定的频率高于您拥有的记录数。两者都会导致错误。

此代码有效:

library(xts)
df1 <- data.frame(date = as.POSIXct(c("2018-01-01 08:00:00", "2018-01-01 08:30:00", 
                                          "2018-01-01 08:59:59","2018-01-01 09:29:59")),
                      volume =  c(195, 188, 345, 123))
df1_xts <- xts(df1$volume, order.by = df1$date)
attr(df1_xts, 'frequency') <- 2
decompose(as.ts(df1_xts))

这不会(频率高于记录数(:

attr(df1_xts, 'frequency') <- 48
decompose(as.ts(df1_xts))
Error in decompose(as.ts(df1_xts)) : 
  time series has no or less than 2 periods

这也不是(ts而不是as.ts(:

attr(df1_xts, 'frequency') <- 2
decompose(ts(df1_xts))
Error in decompose(ts(df1_xts)) : 
  time series has no or less than 2 periods

最新更新