stats_noob
stats_noob

Reputation: 5907

Saving the intermediate results of a loop

I am trying to learn how to store the intermediate results of loop. That is, if I were to interrupt the loop, the existing results would be available upon interruption.

For example:

list_results <- list()

for (i in 1:100000){

    num_1_i = sample(1:100 , 1)
    num_2_i = sample(1:100 , 1)
    num_3_i = sample(1:100 , 1)

inter_results_i <- data.frame(i, num_1_i, num_2_i, num_3_i)
list_results[[i]] <- inter_results_i
}

When I interrupt this loop, the existing results seem to have been saved.

Have I done this correctly?

Upvotes: 1

Views: 207

Answers (1)

Dan Adams
Dan Adams

Reputation: 5204

The code you gave is a for loop, but the same works in a while loop. If the loop modifies a variable with it's output at each iteration, that result will persist after the loop completes or is interrupted.

As user2554330 noted in the comments, if you know a priori how long the result should be, your loop will run a little faster if you create it at that length rather than growing it with each iteration of the loop.

results <- list()

counter <- 2

set.seed(1)
while (counter %% 3 != 0) {
  results[[length(results) + 1]] <- sample(100, counter)
  counter <- counter + sample(2:6, 1)
}

results
#> [[1]]
#> [1] 68 39
#> 
#> [[2]]
#> [1] 34 87 43 14
#> 
#> [[3]]
#> [1] 59 51 97 85 21 54 74

Created on 2022-07-17 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions