title: Calculate vector whose length is not known beforehand - should I "grow" it?
body: <p>I need to calculate entries of a vector <em>whose length I do not know beforehand</em>. How to do so efficiently?</p>
  
  <p>A trivial solution is to "grow" it: start with a small or empty vector and successively append new entries until the stopping criterion is reached. For example:</p>
  
  <pre><code>foo &lt;- numeric(0)
  while ( sum(foo) &lt; 100 ) foo &lt;- c(foo,runif(1))
  length(foo)
  # 195
  </code></pre>
  
  <p>However, "growing" vectors is frowned upon in R for performance reasons.</p>
  
  <p>Of course, I could "grow it in chunks": pre-allocate a "good-sized" vector, fill it, double its length when it is full, and finally cut it down to size. But this feels error-prone and will make for inelegant code.</p>
  
  <p>Is there a better or canonical way to do this? (In my actual application, the calculation and the stopping criterion are a bit more complicated, of course.)</p>
  
  <hr>
  
  <p><strong>In reply to some useful comments</strong></p>
  
  <blockquote>
    <p>Even if you don't know the length beforehand, do you know the maximum possible length it can theoretically have? In such cases I tend to initialize the vector with that length and after the loop cut the NAs or remove the unused entries based on the latest index value.</p>
  </blockquote>
  
  <p>No, the maximum length is not known in advance.</p>
  
  <blockquote>
    <p>Do you need to keep all values as the vector grows?</p>
  </blockquote>
  
  <p>Yes, I do.</p>
  
  <blockquote>
    <p>What about something like <code>rand_num &lt;- runif(300); rand_num[cumsum(rand_num) &lt; 100]</code> where you choose a sufficiently large vector that you know for a high probability that the condition will be met? You can of course check it and use an even bigger number if it's not met. I've tested up till <code>runif(10000)</code> it's still faster than "growing".</p>
  </blockquote>
  
  <p>My actual use case involves a dynamic calculation, which I can't simply vectorize (otherwise I would not be asking).</p>
  
  <p>Specifically, to approximate the convolution of negative binomial random variables, I need to calculate the probability masses of the integer random variable $K$ in Theorem 2 in <a href="https://doi.org/10.1016/j.spl.2006.06.007" rel="nofollow noreferrer">Furman, 2007</a> up to a high cumulative probability. These masses $pr_k$ involve some intricate recursive sums.</p>