Search code examples
rexport-to-csv

Save result to csv or an excel file during each iteration or simulation


I am trying to save result from simulation as an excel or csv file. I would like to export the result after each iteration to one of these files. Is there an easy way to do it? Following is the toy example that I tried:

for(i in  1 : 10){
  if(i==1){write.csv(i,"test.csv")}
  if(i > 2){write.csv(i,"test.csv",append=TRUE)}
}

In this case, only the last value of 10 is saved.


Solution

  • As Ian pointed out we can't change some argument for write.csv, so we need to use write.table, here is a simpler version of loop avoiding if statements:

    for(i in  1:10){
      write.table(i, "test.csv", sep = ",",
                  row.names = FALSE, col.names = i== 1, append = i > 1)
      }
    

    Outputs below test.scv

    "x"
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10