将常规zoo对象转换为ts

时间:2013-07-22 16:38:57

标签: r time-series zoo forecasting

我是ts()zoo()zooreg()的新手。我正在处理每日时间序列数据,并且难以在zooreg和ts对象之间切换。具体来说,我想拟合一个模型来预测未来7天。

尝试下面的#3似乎有效,但有没有比使用coredata更好的方法?另外,我已经阅读了ts()对象中每日数据的频率是365还是7的矛盾建议。尝试#1和#2显示我的尝试失败。

提前致谢。
罗布

#===================================
# load libraries
#===================================
require(zoo)
require(fpp)

#===================================
# create dummy dataset
#===================================
Lines <-
"2013-02-08  686160160
2013-02-09  765196250
2013-02-10          0
2013-02-11          0
2013-02-12 1208385570
2013-02-13  817502700
2013-02-14  640140270
2013-02-15  616020930
2013-02-16  735370160
2013-02-17          0
2013-02-18          0
2013-02-19          0
2013-02-20 1503211500
2013-02-21  831274360
2013-02-22  627096330
2013-02-23  721884800
2013-02-24  721884800
2013-02-25          0
2013-02-26 1169370020
2013-02-27  804955410
2013-02-28  628113780
2013-03-01  654291400
2013-03-02  815497620
2013-03-03          0
2013-03-04          0
2013-03-05 1406186740
2013-03-06  992812660
2013-03-07  768179720
2013-03-08  712639690
2013-03-09  795140640
2013-03-10          0
2013-03-11          0
2013-03-12 1230958890
2013-03-13  851839940
2013-03-14  667805530
2013-03-15          0
2013-03-16 1383085620
2013-03-17          0
2013-03-18          0
2013-03-19 1181950630
2013-03-20  828667350
2013-03-21  637237160
2013-03-22  615793920
"

#===================================
# read data in as zoo object
#===================================
a.zoo <- read.zoo(textConnection(Lines),
 col.names = c("dates", "counts"), 
 colClasses = c("character", "numeric"),
 index = 1, format = "%Y-%m-%d")

#===================================
# attempt #1
#===================================

length(a.zoo)               # length is 43
a.ts <- as.ts(a.zoo)            # convert to ts object
length(a.ts)                # length is 43

# decompose a time series into seasonal, trend and irregular components using loess
frequency(a.ts)             # frequency is 1
stl(a.ts, s.window=7)           # gives error saying frequency < 2

#===================================
# attempt #2
#===================================

# add frequency of 365 to represent daily data
b.zooreg <- zoo(a.zoo, frequency = 365)     
frequency(b.zooreg)             # frequency is 365
str(b.zooreg)               # length is 43, frequency = 365
b.ts <- as.ts(b.zooreg)         # convert to ts object
length(b.ts)                # length is NA padded to 15331

#===================================
# attempt #3
#===================================

# seems like a hack but works
ts2 <- ts(coredata(a.zoo),frequency=7,start=start(a.zoo))
ts2                     # shows correct frequency and length
                        # strange "Start = c(15744, 1)" though

stl(ts2, s.window=7)            # seems to work
plot(forecast(ts2))

0 个答案:

没有答案