将r中的多个时间序列预测的准确度导出到csv-document

时间:2017-01-05 16:58:31

标签: r time-series forecasting

我正在使用fpp包来同时预测不同客户的多个时间序列。我已经能够将不同的简单预测方法(snaivemeanf等)的点预测提取到csv文档中。但是,我仍然试图弄清楚如何同时将每个时间序列的accuracy()命令的度量提取到csv文件中。

我构建了一个例子:

# loading of the "fpp"-package into R 
install.packages("fpp")
require("fpp")

# Example customers 
customer1 <- c(0,3,1,3,0,5,1,4,8,9,1,0,1,2,6,0)   
customer2 <- c(1,3,0,1,7,8,2,0,1,3,6,8,2,5,0,0)    
customer3 <- c(1,6,9,9,3,1,5,0,5,2,0,3,2,6,4,2)  
customer4 <- c(1,4,8,0,3,5,2,3,0,0,0,0,3,2,4,5)   
customer5 <- c(0,0,0,0,4,9,0,1,3,0,0,2,0,0,1,3)

#constructing the timeseries
all   <- ts(data.frame(customer1,customer2,customer3,customer4,customer5),
            f=12, start=2015)    
train <- window(all, start=2015, end=2016-0.01)   
test  <- window(all, start=2016)
CustomerQuantity <- ncol(train)

# Example of extracting easy forecast method into csv-document 
horizon   <- 4
fc_snaive <- matrix(NA, nrow=horizon, ncol=CustomerQuantity)   
for(i in 1:CustomerQuantity){        
  fc_snaive [,i] <- snaive (train[,i], h=horizon)$mean
}
write.csv2(fc_snaive, file ="fc_snaive.csv")

以下部分正是我需要一些帮助的部分 - 我想同时将准确性度量提取到csv文件中。在我的真实数据集中,我有4000个客户,而不仅仅是5个!我尝试使用循环和lapply(),但不幸的是我的代码没有用。

accuracy(fc_snaive[,1], test[,1])  
accuracy(fc_snaive[,2], test[,2]) 
accuracy(fc_snaive[,3], test[,3])  
accuracy(fc_snaive[,4], test[,4]) 
accuracy(fc_snaive[,5], test[,5])

1 个答案:

答案 0 :(得分:2)

以下使用lapply为{1}中的每个元素运行accuracyfc_snaive中的列数与test中的相应元素相对应。

然后,使用do.call,我们按行(rbind)绑定结果,因此我们最终得到一个矩阵,然后我们可以使用write.csv导出。

new_matrix <- do.call(what = rbind, 
                      args = lapply(1:ncol(fc_snaive), function(x){
                        accuracy(fc_snaive[, x], test[, x])
                      }))

write.csv(x = new_matrix,
          file = "a_filename.csv")