Search code examples
riterationnested-loops

Loop inside a loop in R


I am trying to create an R code that puts another loop inside of the one I've already created. Here is my code:

t <- rep(1,1000) 
omega <- seq(from=1,to=12,by=1)
for(i in 1:1000){
    omega <- setdiff(omega,sample(1:12,1))
    t[i] <- length(omega)
    remove <- 0
    f <- length(t [! t %in% remove]) + 1
 }

When I run this code, I get a number a trials it takes f to reach the zero vector, but I want to do 10000 iterations of this experiment.


Solution

  • replicate is probably how you want to run the outer loop. There's also no need for the f assignment to be inside the loop. Here I've moved it outside and converted it to simply count of the elements of t that are greater than 0, plus 1.

    result <- replicate(10000, {
      t <- rep(1, 1000) 
      omega <- 1:12
      for(i in seq_along(t)) {
        omega <- setdiff(omega,sample(1:12,1))
        t[i] <- length(omega)
      }
      sum(t > 0) + 1
    })
    

    I suspect your code could be simplified in other ways as well, and also that you could just write down the distribution that you're looking for without simulation. I believe your variable of interest is just how long until you get at least one of each of the numbers 1:12, yes?