0

I need some suggestions on how to solve this problem. I have a number of zoo objects on which I want to perform a Causal Impact analysis in R, using the homonym package developed by Google. To automatize the process, I want to run a loop over the zoo objects and automatically save the results in a file to be exported in either word or csv.

So far, my solution has been to include the zoo objects into a zoo list by

    zoolist<-list(ts1, 
                ts2,
                ts3 
                 )

and then run a for loop like:

    for (i in zoolist)
{
  experiment_impact<-CausalImpact(i, 
                                  pre.period, 
                                  post.period, 
                                  model.args = list(nseasons = 7, season.duration = 1))
  summary(experiment_impact)
}

The code seems to work, however I don't have idea on how to export all the outputs in a csv or doc or whatever format, provided that it is compact and readable.

Any idea? Thank you for your help!

  • It would be helpful if you posted the code that creates ts1, ts2, and ts3 as well as an example of how you would like the output to be structured. – Geoffrey Poole May 01 '20 at 04:05

1 Answers1

0

If the only thing you want to do is capture the summary, exactly as printed to the screen, you can use capture.output. Replace the second line in your loop with:

capture.output(summary(experiment_impact), file = 'example.txt', append = T)

A more elegant solution might be to use lapply to run the analysis on each item in the list, so that you end up with a list of output items:

resultList = 
  lapply(
    zoolist, 
    CausalImpact, 
    pre.period, 
    post.period,
    model.args = list(nseasons = 7, season.duration = 1)
  )

You could then extract desired values from each of the CausalImpact objects in the list and format the values in a data.frame, which you could output using write.csv.

Geoffrey Poole
  • 1,102
  • 8
  • 10
  • Thank you very much for your answer. It put me on the right way: since the Causal Impact object cannot be directly transformed in a dataframe, and your solution provides me with a large list object, I had to access the specific list inside my list of interest via export = lapply(resultList, "[[" , "summary") and then finally write the csv. Thank you! – Giant Steps May 06 '20 at 09:56