title: how to skip and break a loop in R
body: <p>I am trying write a function that generates simulated data but if the simulated data does not meet the condition, I need to skip it and if it does meet the condition, then I will apply the function summary.  </p>
  
  <p>I would like to loop it until I find 10 valid datasets and then stop. (I actually have to do this until it reaches 10000).  Here is the code.  The code sort of works except it does not stop.  I think I probably placed the next and break function in the wrong place.  I hope someone could help me write this together.  </p>
  
  <p>Another way I could approach this is to generate all the valid data first and then apply the function find_MLE (summary) to the final list. </p>
  
  <p>Edit:  I put break inside repeat. I edit the code to make it reproducible. Still the code keeps generating data and does not break.</p>
  
  <p>here is a reproducible version</p>
  
  <pre><code>      validData &lt;-  function(GM, GSD,sampleSize, p) {
  
              count=0
              for (i in 1:n) {  
                repeat {
                  lod &lt;- quantile(rlnorm(1000000, log(GM), log(GSD)), p = p)
                  X_before &lt;- rlnorm(sampleSize, log(GM), log(GSD))
                  Xs &lt;-  ifelse(X_before &lt;= lod, lod,  X_before)
                  delta &lt;- ifelse(X_before &lt;= lod, 1,  0) 
                  pct_cens &lt;- sum(delta)/length(delta)
                  print(pct_cens)
                  if (pct_cens == 0 &amp; pct_cens ==1) next
  
                  else {
  
                    sumStats &lt;- summary(Xs)
  
                    Med &lt;- sumStats[3]
                    Ave &lt;- sumStats[4]
  
                        }
  
                    count&lt;- count+1
  
                  if (count == 10) break
                }}
              return(c(pct_cens, Med, Ave))
            }
  
  
  
            validData(GM=1,GSD=2,sampleSize=10,p=0.1)            
  </code></pre>