我已经看到了非常相似的问题的一些答案,但所有问题都引用了ts
个对象(由ts
直接创建),而不是zoo
个。
我有一张大型销售表,总结为每周需求,如下所示(在原始汇总表中,每周有121次观察,我减少到20只以保留一个小例子):
> dput(dda1)
structure(list(floor_date = structure(c(16068, 16894, 16719,
16474, 16705, 16530, 16516, 16670, 16502, 16824, 16467, 16390,
16488, 16859, 16327, 16313, 16789, 16845, 16642, 16929), class = "Date"),
V1 = c(1809.32, 50866.125, 42822.7775, 45450.085, 37962.295,
50802.2175, 69953.8, 56294.485, 46702.88, 49460.9525, 54223.47,
85252.15, 46455.15, 65523.745, 63216.985, 50868.92, 23372.025,
46291.405, 60290.86, 29907.02)), .Names = c("floor_date",
"V1"), class = "data.frame", row.names = c(NA, -20L))
为了避免在创建时间序列时丢失我已经拥有的日期,我将使用zoo
函数:
library(zoo)
library(forecast)
dda1_zoo <- zoo(dda1$V1, order.by = dda1$floor_date)
# there are a lot of missing values (since this is sales,
# those are weeks with zero sale). I'll fill them with merge:
z0 <- seq(min(dda1$floor_date), max(dda1$floor_date), by = "week")
dda2 <- merge(dda1_zoo, zoo(order.by = z0), fill = 0)
# check if it's periodic and timespan
library(xts)
periodicity(dda2_zoo)
## Weekly periodicity from 2013-12-29 to 2016-05-08
# run stl
stl(dda2_zoo)
## Error in stl(dda2_zoo) :
## series is not periodic or has less than two periods
我做错了什么,如何制作这个时间序列的stl
分解?
答案 0 :(得分:0)
关于此错误,请查看答案here
为了获得每周数据的STL值,您需要至少有2个完整的周期周期。这意味着超过 104个数据点。
关于数据的其他部分,如果我理解正确,那么每周数据都会丢失。您可以查看以下代码以获得STL。
require(zoo)
### creating a weekly zoo object for 123 weeks with some missing values
seq_dates<- seq.Date(from=as.Date("2014-01-01"), by= "week" ,length.out = 123)
zoo_obj <- zoo(c(NA,NA,rnorm(118,100,2),NA,NA), seq_dates)
## assuming you are at this stage where you have a zoo object which has missing values too
## extract the dates from the zoo object and store then in a variable
ts_dates<- index(zoo_obj)
## extract actual sales value which has missing values too
ts_values<- as.numeric(zoo_obj)
## replace missing values with zero
ts_values[is.na(ts_values)]<- 0
## create a ts object
## you can figure out the value of start from ts_dates created above
ts_weekly<- ts(ts_values, frequency = 52, start = c(2014,1))
## now apply stl on this ts object
stl_obj <- stl(ts_weekly, s.window = "periodic")
## build back your zoo object : this will not have missing values either
zoo_obj<- zoo(ts_values, ts_dates)
希望它有所帮助!