Search code examples
rloopssavestoring-data

Storing matrix after every iteration


I have following code.

for(i in 1:100)
{
   for(j in 1:100)
    R[i,j]=gcm(i,j)
}

gcm() is some function which returns a number based on the values of i and j and so, R has all values. But this calculation takes a lot of time. My machine's power was interrupted several times due to which I had to start over. Can somebody please help, how can I save R somewhere after every iteration, so as to be safe? Any help is highly appreciated.


Solution

  • You can use the saveRDS() function to save the result of each calculation in a file.

    To understand the difference between save and saveRDS, here is a link I found useful. http://www.fromthebottomoftheheap.net/2012/04/01/saving-and-loading-r-objects/