Question

This is what I am trying to do..

arima_fits <- group_by(Insample, Region) %>% do(fit=auto.arima(.$Sales)) for(i in 1:64) { fitarima <- forecast.Arima(arima_fits$fit[[i]], h=32) write.csv(fitarima,file="fitarima.csv") }

How do I make R save the forecast results of all 64 outputs together in a new file?

Here's how the sample looks like (from 121 to 152 in this case) 32 lines of output every time the loop runs:

Point Forecast Lo 80 Hi 80 Lo 95 Hi 95 121 56.63080 54.28690 58.97471 53.04611 60.21549 122 56.94228 54.44269 59.44187 53.11949 60.76507 123 57.24700 54.62258 59.87141 53.23330 61.26070 124 57.54115 54.81863 60.26367 53.37741 61.70489 125 57.82130 55.02380 60.61881 53.54288 62.09972 126 58.08443 55.23172 60.93715 53.72158 62.44729 127 58.32794 55.43658 61.21929 53.90599 62.74988

Was it helpful?

Solution

Method 1:

You can use the append feature, and use write.table instead of write.csv of write

arima_fits <- group_by(Insample, Region) %>% do(fit=auto.arima(.$Sales)) 

for(i in 1:64) { 
fitarima <- forecast.Arima(arima_fits$fit[[i]], h=32) 
write.table(fitarima,file="fitarima.csv", append=TRUE,sep=",",col.names=FALSE,row.names=FALSE) 
}

This will get rid of the column names. If column names are important, you may do something like this:

Lets first remove the old file:

file.remove("fitarima.csv")

Allow the column names on the first write:

fitarima <- forecast.Arima(arima_fits$fit[[1]], h=32) 
write.table(fitarima,file="fitarima.csv", append=TRUE,sep=",",row.names=FALSE) 

Then do the remaining without column names:

for(i in 2:64) { 
fitarima <- forecast.Arima(arima_fits$fit[[i]], h=32) 
write.table(fitarima,file="fitarima.csv", append=TRUE,sep=",",col.names=FALSE,row.names=FALSE) 
}

Method 2:

You can also generate all the result together, and then write them in one shot:

Lets first remove the old file:

file.remove("fitarima.csv")

Now, start afresh:

fitarima <- NULL 
for(i in 1:64) { 
fitarima <- rbind(fitarima, forecast.Arima(arima_fits$fit[[i]], h=32) )
}

Now write the file:

write.csv(fitarima,file="fitarima.csv") 

Hope this helps!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top