R预测了几种型号

时间:2013-12-27 12:23:25

标签: r plyr apply forecasting

我有几个回归 - 我想预测的模型,并轻松提取“x-ahead-ahead”预测。我想用简单易用的代码完成这项工作,因此我可以更改模型并轻松重新运行它们。

所以,一个简单的多元回归模型的例子:

library(plyr)
library(forecast)

# Historical Data
df.h <- data.frame( 
  hour     = factor(rep(1:24, each = 21)),
  price    = runif(504, min = -10, max = 125),
  wind     = runif(504, min = 0, max = 2500),
  temp     = runif(504, min = - 10, max = 25)  
)

# Forecasting Data

df.f <- data.frame(
  hour     = factor(rep(1:24, each = 9)),
  wind     = runif(216, min = 0, max = 2500),
  temp     = runif(216, min = - 10, max = 25)  
)

models <- dlply(df.h, "hour", function(x) (lm(price ~ wind + temp, data = df.h)))
# Now I have 24 different regression-models, I would like to forecast on each one and
# be able to extract 1 step ahead forecast easily and 2 step ahead, and etc.
# I've done it like this, but it is cumbersome to work with and to extract the data I want 

f1 <- forecast(models[[1]], newdata = subset(df.f, df.f$hour == 1))
f2 <- forecast(models[[2]], newdata = subset(df.f, df.f$hour == 2))
....
f24 <- forecast(models[[24]], newdata = subset(df.f, df.f$hour == 24))

# Getting the first-predictive day:

predict.1 <- cbind(f1$mean[1], f2$mean[1], f24$mean[1] )

理想情况下,我希望数据框或列表包含每小时的每个步进预测,如下所示:

df.prediction
hour step1 step2 .... step9
1        
2
3
...
24

但我不确定这是否可行/如何做到这一点?

1 个答案:

答案 0 :(得分:2)

假设你所谓的“步骤”对应于f * $ mean中的每个值(即第1小时的第1步是f1 $ mean [1],第2步是f1 $ mean [2],那么我认为以下将做你想做的事:

t(
  mapply(
    function(model, data) {
      forecast(model, newdata=data)$mean
    },
    models, 
    split(df.f, df.f$hour)
  )
)

基本上,我们一致地遍历每个模型和相应的数据集,并预测,输出整个9元素(步骤?)点预测结果。 mapply然后将这些绑定在一起,我们将结果转换为t ransposing的步骤。结果是一个矩阵,但如果你想把它作为一个简单的数据框架。在这里,我们有(四舍五入以适应):

      1    2    3    4    5    6    7    8    9
1  57.8 59.6 58.2 57.9 60.4 64.5 59.2 59.8 62.0
2  55.8 59.4 63.2 61.7 60.9 62.8 60.0 66.2 58.7
3  58.8 60.1 62.7 61.8 64.9 58.8 61.4 60.3 60.7
4  59.9 63.9 62.4 62.4 65.2 60.7 61.3 57.8 61.2
5  57.0 59.4 64.5 56.5 56.8 61.6 59.9 61.9 64.6
6  55.7 65.3 57.5 59.5 62.9 56.1 62.1 63.2 58.4
7  64.7 58.7 60.3 56.6 53.8 63.8 64.8 60.5 64.0
8  57.6 53.5 55.3 56.9 61.8 60.1 60.4 63.0 62.1
9  62.5 63.0 64.4 59.0 62.6 63.9 57.8 57.5 58.5
10 61.0 61.2 58.6 59.9 55.8 65.6 60.0 57.1 61.0
11 63.0 57.9 65.6 60.8 61.2 60.9 63.0 66.4 63.8
12 55.9 55.2 59.0 58.4 63.4 62.3 63.1 62.1 61.3
13 55.8 63.0 66.1 56.0 59.4 63.8 59.8 61.8 59.7
14 58.3 59.7 53.5 54.5 63.3 59.3 60.4 57.8 54.8
15 56.4 58.1 58.9 60.5 59.6 60.8 57.9 65.5 59.2
16 60.5 57.3 57.4 59.9 59.9 58.6 59.1 58.9 57.5
17 59.7 60.6 58.6 58.0 60.7 58.0 58.8 56.9 62.0
18 61.7 60.6 57.2 59.0 61.5 61.7 60.1 58.5 60.9
19 62.1 61.8 64.0 62.1 62.8 59.1 58.3 63.9 60.5
20 58.0 58.1 64.4 61.4 61.0 61.3 64.5 59.4 54.4
21 57.0 63.5 58.0 56.9 53.6 59.2 60.1 57.4 59.0
22 60.7 60.7 59.4 57.4 59.8 60.1 59.9 60.7 61.0
23 58.8 60.0 56.9 60.6 59.7 58.1 56.8 60.5 61.6
24 57.4 55.5 62.6 59.9 62.7 63.8 62.4 57.3 55.5