Gabriel123 Gabriel123 - 3 years ago 219
R Question

Save loop results as csv table

I have simple loop that generate a value at each step, and I want to save all results as a single table. Problem is that each step overwrites the previous.

for(i in 1:5){
x = 3*i

This gives

[1] 1 3
[1] 2 6
[1] 3 9
[1] 4 12
[1] 5 15

Now I create a matrix that I will then save as a csv file, but it only shows the final step of the loop.

results = matrix(c(i,x), ncol = 2)
[,1] [,2]
[1,] 5 15

write.table(results, file = "Results.csv", col.names=NA, append = T)

How to show the entire list of results? Thanks in advance!

(ps.- I know that a similar question has been posted previously, e.g. Write output of R loop to file, but the problem was quite specific and I did not manage to adapt the answers to my case).

Answer Source

Your loop only prints, to the console, the results. The matrix you're creating only relies on the single (and last) value of i. There are many ways to do it but if you really want to write a matrix, then you need to store them somewhere to export all iteration intermediate results. You can try something like:

results <- matrix(NA, nrow=5, ncol=2)
for(i in 1:5){
  results[i, ] <- c(i, 3*i)
write.table(results, file = "Results.csv", col.names=NA, append = T)

And by the way you don't really need a loop here:

i <- 1:5
m <- matrix(c(i, 3*i), nrow=5)

would do the job.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download