Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: Recording the Index of a LOOP in which a certain "Behavior" happens?

I am working with the R programming language.

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 (e.g. 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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!

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading