Hello
Hello

Reputation: 181

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.

Upvotes: 1

Views: 327

Answers (3)

zx8754
zx8754

Reputation: 56004

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

Upvotes: 1

broti
broti

Reputation: 1382

How about saving your results in a data frame first and then exporting to csv? Like:

df <- data.frame(result = NA)
for (i in 1:10) {
  df[i, "result"] <- i
}
write.csv(df, file = "test.csv")

Upvotes: 2

Ian Campbell
Ian Campbell

Reputation: 24770

I believe that write.table accepts append = TRUE and write.csv does not.

help(write.table)

... arguments to write.table: append, col.names, sep, dec and qmethod cannot be altered.

for(i in 1:3){
df <- data.frame(a = sample(1:10,10), b = sample(1:10,10), c = sample(1:10,10))
write.table(df, file = "test.csv",append = TRUE,sep=",",quote=TRUE,col.names = FALSE)
}

Upvotes: 2

Related Questions