title: R optim - retrieving values from individual iterations
body: <p>I want to retrieve values of optimized parameters in different iterations of the <code>optim</code> function. The purpose is to check convergence of the error on the validation dataset.</p>
  <p>My question is closely related to <a href="https://stackoverflow.com/questions/23975101/getting-more-details-from-optim-function-from-r">this question</a> and I tried to implement the code therein that I supposed to solve my problem. However, both values of <code>i</code> and <code>$count</code> suggest that the optimized function is called much more times than specified in the <code>maxit</code> parameter:</p>
  <pre><code>vals &lt;- list()
  f1 &lt;- function(x) {
    i &lt;&lt;- i+1
    vals[[i]] &lt;&lt;- x
    
    x1 &lt;- x[1]
    x2 &lt;- x[2]
    x1^2 + 3*x2^2  
  }
  
  # countBFGS 
  i &lt;- 0  
  optim(c(1,1), f1, method=&quot;BFGS&quot;,control = list(trace=1, maxit = 10))$count
  i
  # countCG 
  i &lt;- 0 
  optim(c(1,1), f1, method=&quot;CG&quot;,control = list(trace=1, maxit = 10))$count
  i
  # countSANN
  i &lt;- 0 
  optim(c(1,1), f1, method=&quot;SANN&quot;,control = list(trace=1, maxit = 10))$count
  i
  </code></pre>
  <p>Any suggestions how to capture optimized parameters on-the-fly?</p>
  <p>Sorry for possible duplication of the question mentioned above.</p>