exponential time series for multiple time series data

153 views Asked by At

My data has different start and end points.

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")

I tried doing

ts_test <- ts(multiple_ts, frequency=52)

to convert to time series but it failed

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"))

Can some one help me how to convert to time series group by item and apply exponential smoothing to each item. Thanks in Advance!

1

There are 1 answers

6
G. Grothendieck On BEST ANSWER

Convert the data frame into a 3 column zoo object z and from z create a list of ts objects L. Apply exponential smoothing to each component of L giving HW. Then plot each of those. Note that ts objects cannot represent Date class directly so we omit the X axis and draw it ourself in 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)

screenshot