我正在尝试对面板数据运行HoltWinters程序,以便为公司列表提供销售预测。我的数据框有“公司”,“年”和“销售”字段。我有兴趣在此数据框中添加一个额外的列,显示使用HoltWinters获得的拟合销售额。
对于一家公司来说,这项工作很简单,因为我可以运行HoltWinters。我可以通过循环跨公司将这种方法扩展到我的情况,但我正在寻找一种避免循环的解决方案。
有什么想法?
答案 0 :(得分:1)
阅读HoltWinters
的帮助文件,它看起来不像是矢量化的,所以我认为你不能避免循环。我能做的最好的事情就是用lapply
使你的循环变得漂亮(速度增益也可能很小)。假设您将个人作为单独的时间序列(或时间序列联盟):
set.seed(0)
a <- ts(rnorm(10), start=c(2001, 5), freq=12)
b <- ts(rnorm(10), start=c(2001, 5), freq=12)
c <- ts(rnorm(10), start=c(2001, 5), freq=12)
d <- ts(rnorm(10), start=c(2001, 5), freq=12)
e <- ts(rnorm(10), start=c(2001, 5), freq=12)
f <- ts(rnorm(10), start=c(2001, 5), freq=12)
individual.one <- ts.union(a, b, c)
individual.two <- ts.union(d, e, f)
panel <- list(individual.one, individual.two)
ans <- lapply(panel, HoltWinters)
收率:
> ans
Holt-Winters exponential smoothing with trend and additive seasonal component.
Call:
FUN(x = X[[1L]])
Smoothing parameters:
alpha: 0
beta : 0
gamma: 0
Coefficients:
[,1]
a -0.504984544
b -0.035336155
s1 -1.085615710
s2 -0.352859142
s3 0.002437573
s4 2.550897907
s5 0.986769568
s6 -0.596066930
s7 -1.028559659
s8 -0.187923905
s9 -0.149289171
s10 -0.168011617
s11 0.606452449
s12 -0.578231362
[[2]]
Holt-Winters exponential smoothing with trend and additive seasonal component.
Call:
FUN(x = X[[2L]])
Smoothing parameters:
alpha: 0
beta : 0
gamma: 0
Coefficients:
[,1]
a -0.39575955
b -0.04035375
s1 0.75505039
s2 -0.64553006
s3 1.06488778
s4 -0.40487180
s5 1.74515472
s6 0.64324387
s7 -0.36380752
s8 -0.74481981
s9 -1.04726447
s10 -0.90172103
s11 -1.42433355
s12 1.32401148
其中:
> panel
[[1]]
a b c
May 2001 1.262954285 0.7635935 -0.22426789
Jun 2001 -0.326233361 -0.7990092 0.37739565
Jul 2001 1.329799263 -1.1476570 0.13333636
Aug 2001 1.272429321 -0.2894616 0.80418951
Sep 2001 0.414641434 -0.2992151 -0.05710677
Oct 2001 -1.539950042 -0.4115108 0.50360797
Nov 2001 -0.928567035 0.2522234 1.08576936
Dec 2001 -0.294720447 -0.8919211 -0.69095384
Jan 2002 -0.005767173 0.4356833 -1.28459935
Feb 2002 2.404653389 -1.2375384 0.04672617
[[2]]
d e f
May 2001 -0.2357066 1.7579031 0.26613736
Jun 2001 -0.5428883 0.5607461 -0.37670272
Jul 2001 -0.4333103 -0.4527840 2.44136463
Aug 2001 -0.6494716 -0.8320433 -0.79533912
Sep 2001 0.7267507 -1.1665705 -0.05487747
Oct 2001 1.1519118 -1.0655906 0.25014132
Nov 2001 0.9921604 -1.5637821 0.61824329
Dec 2001 -0.4295131 1.1565370 -0.17262350
Jan 2002 1.2383041 0.8320471 -2.22390027
Feb 2002 -0.2793463 -0.2273287 -1.26361438