title: Capture iteration output into a data.frame in R
body: <p>I have a simple backtesting program written in R that calculates the testing period's return to date. Very simple. Not annualized, just overall buy-and-hold return. But not for just one set of parameters. It calculates these naive returns for a "set" of parameters. This requires looping and I've started by creating an explicit R loop to perform the operation. Here is the code and what it generates to console. </p>
  
  <pre><code>require(quantmod)
  
  getSymbols("GLD")
  
  for(i in seq(5, 15, 5))
    for(j in seq(50, 80, 15))
  
  {
  GLD$fast     &lt;- SMA(Cl(GLD), n=i)     
  GLD$slow     &lt;- SMA(Cl(GLD), n=j)         
  
  golden_cross &lt;- Lag(ifelse(GLD$fast &gt; GLD$slow, 1, -1))
  golden_cross &lt;- na.locf(golden_cross, na.rm=TRUE)
  
  coin         &lt;- ROC(Cl(GLD))*golden_cross
  
  coin_box     &lt;- cumprod(1+coin)
  last_coin    &lt;- coin_box[NROW(coin_box),]
  
  coin_value   &lt;- round((last_coin-1)*100, digits=2)
  
  cat(i,j,coin_value,  "\n")
  }
  </code></pre>
  
  <p>output:</p>
  
  <pre><code>5 50 9.96 
  5 65 -26.37 
  5 80 -21.92 
  10 50 3.09 
  10 65 -13.55 
  10 80 -17.98 
  15 50 -6.48 
  15 65 -21.79 
  15 80 -9.73 
  </code></pre>
  
  <p>The output is taken out of the loop with the <code>cat()</code> function. This is useless to me. I'd like to have it return a <code>data.frame</code> object so I can perform analysis on it. Essentially, I'd like to remove the <code>cat()</code> call and use the looping process to create a <code>data.frame</code> object line by line. First column would be <code>i</code>, second column would be <code>j</code> and third column would be a value associated with the unique <code>i,j</code> iteration.  </p>
  
  <p>I'm already contemplating different approaches to vectorizing the script. I'm using the explicit R loop approach for now as a sort of place-holder.  I believe it's useful to solve this problem first before getting into re-factoring. If you disagree, I welcome your input. </p>
  
  <p>EDIT :</p>
  
  <p>The accepted answer below stands. But I was looking into the <code>cat()</code> function a little more closely and asked the question: Is there a way to change the default output of this function from the console to a file? As a matter of fact, there is. The following line redirects the output into a file. I'm saving the file to my home directory for illustration purposes, and calling it "test_result" (with no file extension because it looks cleaner that way). If you don't pass <code>append=TRUE</code> it will only return the last value derived from the loop.</p>
  
  <pre><code>    cat(i,j, coin_value,  "\n", file="~/test_result", append=TRUE) 
  </code></pre>