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

Time:07-31

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:

  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!

CodePudding user response:

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)
  • Related