提取预测的下限和上限以及附加到R中的数据集

时间:2016-06-27 20:38:30

标签: r dataframe append

我有一个数据框,其中包含特定ID组的预测值。我可以使用purchaseforecast$lowerpurchaseforecast$upper提取它们,但无法将它们附加到我在下面创建的空数据框中。我还想将循环中的id添加到空数据框中。任何帮助表示赞赏。

空数据框:

finaloutput <- data.frame(id =integer,
                 lowerlimit=integer(length = 0L),
                 upperlimit=integer(length = 0L)) 

预测数据框:

purchaseforecastmn <- forecast.HoltWinters(object = daily_seasonality, level = 95, h =30)

除了循环中的id值之外,我想附加到下限的值是purchaseforecastmn$lower,上限是purchaseforecastmn$upper

示例代码:

dailyseasonality1 <- c(1:365)

dailyseasonality2 <- HoltWinters(dailyseasonality1, gamma = FALSE,beta = FALSE)

purchaseforecastmn <- forecast.HoltWinters(object = dailyseasonality2, level = 95, h =30)

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解这个问题,但下面的代码会返回data.frame,其中包含purchaseforecastmn中的所有内容以及id变量:

# install.packages('forecast')

library(forecast)

n.ids <- 30

id <- 1:n.ids

dailyseasonality1 <- c(1:365)
dailyseasonality2 <- HoltWinters(dailyseasonality1, gamma = FALSE,beta = FALSE)
purchaseforecastmn <- forecast.HoltWinters(object = dailyseasonality2, level = 95, h = n.ids)
purchaseforecastmn

my.data <- as.data.frame(purchaseforecastmn)
my.data <- data.frame(id, my.data)

以下是输出data.frame my.data

    id Point.Forecast    Lo.95 Hi.95
366  1       364.9999 364.9999   365
367  2       364.9999 364.9999   365
368  3       364.9999 364.9999   365
369  4       364.9999 364.9999   365
370  5       364.9999 364.9999   365
371  6       364.9999 364.9999   365
372  7       364.9999 364.9999   365
373  8       364.9999 364.9999   365
374  9       364.9999 364.9999   365
375 10       364.9999 364.9999   365
376 11       364.9999 364.9999   365
377 12       364.9999 364.9999   365
378 13       364.9999 364.9999   365
379 14       364.9999 364.9999   365
380 15       364.9999 364.9999   365
381 16       364.9999 364.9999   365
382 17       364.9999 364.9999   365
383 18       364.9999 364.9999   365
384 19       364.9999 364.9999   365
385 20       364.9999 364.9999   365
386 21       364.9999 364.9999   365
387 22       364.9999 364.9999   365
388 23       364.9999 364.9999   365
389 24       364.9999 364.9999   365
390 25       364.9999 364.9999   365
391 26       364.9999 364.9999   365
392 27       364.9999 364.9999   365
393 28       364.9999 364.9999   365
394 29       364.9999 364.9999   365
395 30       364.9999 364.9999   365

如果您只想要my.data的第一行,可以使用以下内容提取它:

my.output <- my.data[1,]

关于循环,我想我需要查看运行代码的示例。这可能有用。

library(forecast)

n.iters <- 30

my.output <- matrix(NA, ncol = 4, nrow = n.iters)

for(i in 1:n.iters) {

     dailyseasonality1 <- c(1:365)
     dailyseasonality2 <- HoltWinters(dailyseasonality1, gamma = FALSE,beta = FALSE)
     purchaseforecastmn <- forecast.HoltWinters(object = dailyseasonality2, level = 95, h = 30)
     my.data <- as.matrix(as.data.frame(purchaseforecastmn))

     my.output[i,1] <- i
     my.output[i,2:4] <- my.data[1,1:3]

}

colnames(my.output) <- c('id', 'Point.Forecast', 'Lo.95', 'Hi.95')
my.output