【问题标题】:Export accuracy of multiple timeseries forecasts in r into csv-document将 r 中多个时间序列预测的准确性导出到 csv-document
【发布时间】:2017-01-05 16:58:30
【问题描述】:

我正在使用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])

【问题讨论】:

    标签: r time-series forecasting


    【解决方案1】:

    以下使用lapplyfc_snaive 中从1 到列数的每个元素运行accuracy 以及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")
    

    【讨论】:

    • 非常感谢胡安:)!!!您的代码完美运行!在写入新 csv.file 的行中只有一个小错字:使用“x=new.matrix”而不是“x=new_matrix”
    猜你喜欢
    • 2021-01-09
    • 2019-04-23
    • 2020-02-08
    • 2021-10-10
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2015-05-19
    • 2018-08-13
    相关资源
    最近更新 更多