Export accuracy of multiple timeseries forecasts in r into csv-document

[亡魂溺海] 提交于 2019-12-25 08:20:00

问题


I am using the fpp package to forecast multiple time series of different customers at the same time. I am already able to extract the point forecasts of different easy forecast methods (snaive, meanf, etc.) into a csv document. However, I am still trying to figure out how to extract the measures of the accuracy() command of every time series into a csv file at the same time.

I constructed an example:

# 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")

The following part is exactly the part, where I would needed some help - I would like to extract the accuracy-measures into a csv file all at the same time. In my real dataset, I have 4000 customers, and not only 5! I tried to use loops and lapply(), but unfortunately my code didn't work.

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:


The following uses lapply to run accuracy for each element from 1 to the number of columns in fc_snaive with the corresponding element in test.

Then, with do.call, we bind the results by row (rbind), so we end up with a matrix that we can, in turn, export using 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")


来源:https://stackoverflow.com/questions/41492474/export-accuracy-of-multiple-timeseries-forecasts-in-r-into-csv-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!