首页 文章

如何在聚合后将时间序列添加到R中的时间序列

提问于
浏览
0

从2004-07-09到2014-12-31,我在日常销售额R中有两个可变数据帧(df),为期十年 . 并非每个日期都在十年期间出现,但在周一至周五的大多数日子都是如此 .

我的目标是按季度汇总销售额,转换为时间序列对象,并运行季节性分解和其他时间序列预测 .

我在转换时遇到问题,因为我收到错误:

time series has no or less than 2 periods

这是我的代码的结构 .

# create a time series object
library(xts)
x <- xts(df$amount, df$date)
# create a time series object aggregated by quarter
q.x <- apply.quarterly(x, sum)

当我试图跑

fit <- stl(q.x, s.window = "periodic")

我收到错误消息

series is not periodic or has less than two periods

当我试图跑

q.x.components <- decompose(q.x)  
# or  
decompose(x)

我收到错误消息

time series has no or less than 2 periods

那么,如何使用我的原始数据框,使用日期变量和金额变量(销售额),将该季度汇总为时间序列对象,然后运行时间序列分析?

1 回答

  • 0

    我想我能够回答我自己的问题 . 我这样做了任何人都可以确认这种结构是否有意义?

    library(lubridate)
    # add a new variable indicating the calendar year.quarter (i.e. 2004.3) of each observation
    df$year.quarter <- quarter(df$date, with_year = TRUE)
    
    library(plyr)
    # summarize gift amount by year.quarter
    new.data <- ddply(df, .(year.quarter), summarize,
                  sum = round(sum(amount), 2))
    
    # convert the new data to a quarterly time series object beginning
    # in July 2004 (2004, Q3) and ending in December 2014 (2014, Q4)
    nd.ts <- ts(new.data$sum, start = c(2004,3), end = c(2014,4), frequency = 4)
    

相关问题