title: R: Hold Values Generated in For Loop
body: <p>I apologize for this question in advance, but I've looked pretty hard and haven't been able to find a solution.</p>
  
  <p>How do I values generated by a for loop in a variable?</p>
  
  <p>For example:</p>
  
  <pre><code>myfunction &lt;- function(x=1:5) {
                  for(i in 1:length(x)) {
                  r&lt;-x[i]
                  }
                  print(r)
                }
  </code></pre>
  
  <p>If I run the above code, I only get the last value for x, in this case 5. I understand that this is because I'm overwriting r each time through the for loop.</p>
  
  <p>I've also tried:</p>
  
  <pre><code>myfunction &lt;- function(x=1:5) {
                  for(i in 1:length(x)) {
                  r[i]&lt;-x[i]
                  }
                  print(r)
                }
  </code></pre>
  
  <p>But I still just get the last value.</p>
  
  <p>The only solution I've found is to specify the length of the variable that will hold the generated values before using r&lt;-numeric(length):</p>
  
  <pre><code>myfunction &lt;- function(x=1:5) {
                  r&lt;-numeric(5)
                  for(i in 1:length(x)) {
                  r[i]&lt;-x[i]
                  }
                  print(r)
                }
  </code></pre>
  
  <p>But this solution will obviously be insufficient if I don't know the length of the vector to be returned beforehand.</p>
  
  <p>Thanks for any help!</p>