我的数据有不同的起点和终点。
structure(list(item = c("Card", "Card", "Card", "Card", "Card",
"Card", "Card", "Card", "battery", "battery", "battery", "battery",
"battery", "laptop", "laptop", "laptop", "laptop", "laptop",
"laptop", "laptop"), sales = c(20.4, 29, 26, 40, 35, 36, 28,
41, 70, 75, 78, 99, 40, 100, 132, 123, 145, 125, 145, 124), Date = structure(c(17784,
17791, 17798, 17805, 17812, 17819, 17826, 17833, 17608, 17615,
17622, 17629, 17636, 17713, 17726, 17739, 17752, 17765, 17778,
17791), class = "Date")), row.names = c(NA, -20L), class = "data.frame")
我尝试做
ts_test <- ts(multiple_ts, frequency=52)
转换为时间序列,但失败
structure(c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 20.4, 29, 26, 40, 35, 36, 28, 41,
70, 75, 78, 99, 40, 100, 132, 123, 145, 125, 145, 124, 17784,
17791, 17798, 17805, 17812, 17819, 17826, 17833, 17608, 17615,
17622, 17629, 17636, 17713, 17726, 17739, 17752, 17765, 17778,
17791), .Dim = c(20L, 3L), .Dimnames = list(NULL, c("item", "sales",
"Date")), .Tsp = c(1, 1.36538461538462, 52), class = c("mts",
"ts", "matrix"))
有人可以帮助我如何逐项转换为时间序列,并对每个项应用指数平滑。 预先感谢!
答案 0 :(得分:0)
将数据帧转换为3列动物园对象z
,并从z
创建ts
对象L
的列表。对L
的每个分量应用指数平滑,得到HW
。然后绘制每个。请注意,ts
对象不能直接表示Date
类,因此我们省略了X轴,并在pltHW
中自己绘制了它。
library(zoo)
z <- read.zoo(multiple_ts, index = "Date", split = "item")
L <- lapply(as.list(z), function(x) as.ts(na.omit(x)))
HW <- lapply(L, HoltWinters, beta = FALSE, gamma = FALSE)
# given HoltWinters object x get fitted values as zooreg object
fitHW <- function(x) {
fitted <- fitted(x)
zooreg(fitted[, 1], as.Date(start(fitted)), frequency = frequency(fit))
}
# plot
pltHW <- function(x, sub) {
plot(x, sub = sub, xaxt = "n")
fit <- fit(x)
Axis(time(fit), side = 1)
invisible(x)
}
par.old <- par(mfrow = c(3, 1))
junk <- Map(pltHW, HW, names(HW))
par(par.old)