title: Try an expression multiple times until it succeeds in R
body: <p>I have R code that sometimes returns an <code>NA</code>, which causes errors downstream.  However, the only reason that it fails stems from a bad random number. Run the expression again with a different starting point, and it produces results that are not <code>NA</code>.      </p>
  
  <p>I've setup a <code>while</code> loop to try the expression multiple times before giving up. Here's an example:</p>
  
  <pre><code>attempts &lt;- 0
  x &lt;- NA
  while(is.na(x) &amp; attempts &lt; 100) {
       attempts &lt;- attempts + 1
       rand &lt;- runif(1)
       x &lt;- ifelse(rand &gt; 0.3, rand, NA)
  }
  if(attempts == 100) stop("My R code failed")
  x
  </code></pre>
  
  <p>I don't like how clunky this is.</p>
  
  <p>Is there a function, package, or method that can help simplify this try-repeat-try-again expression?</p>