简体   繁体   中英

Save the number of iterations taken by a "while" loop nested in a "for" loop

In a previous question ( Generating Random Numbers Until Some Condition Is Met ), I learned how to write a while loop that keeps simulating 3 random numbers until these 3 numbers sum to more than 150 - and then repeats this process 100 times:

list_results <- list()

for (i in 1:100){
  num_1_i = num_2_i = num_3_i = 0
  
  while(num_1_i + num_2_i + num_3_i < 150){
    num_1_i = runif(1,0,100)
    num_2_i = runif(1,0,100)
    num_3_i = runif(1,0,100)
  }
  
  inter_results_i <- data.frame(i, num_1_i, num_2_i, num_3_i)
  list_results[[i]] <- inter_results_i
}

In this loop, I figured out how to record each general iteration - but I am not sure how to record the exact sub-iteration at which this happens (eg within the first iteration, how many simulations were required until the condition was met?). For example, I would like the end product to look something like this:

  index num_1 num_2 num_3 sub_index
1     1    89    81    92        44
2     2    62    99    77        21
3     3    76    88    69        17

Can someone please show me how to do this?

Thanks!

list_results <- vector("list", 100)  ## better than list()

for (i in 1:100){
  num_1_i = num_2_i = num_3_i = 0
  
  sub_index <- 1  ## count it
  while(num_1_i + num_2_i + num_3_i < 150){
    num_1_i = runif(1,0,100)
    num_2_i = runif(1,0,100)
    num_3_i = runif(1,0,100)
    sub_index <- sub_index + 1  ## increase it
  }
  
  inter_results_i <- data.frame(i, num_1_i, num_2_i, num_3_i, sub_index)## save it
  list_results[[i]] <- inter_results_i
}

do.call(rbind, list_results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM