[R] odd behaviour of 'while'?

Spencer Graves spencer.graves at pdf.com
Fri Mar 14 19:59:22 CET 2003


 From ?on.exit:

  `on.exit' records the expression given as its argument as needing
      to be executed when the current function exits (either naturally
      or as the result of an error).

Thus, when "i <- i+1", it then goes to "while", which then exits, 
invoking the "on.exit" command as it does so.

Hope this helps.
Spencer Graves

Edmond Ng wrote:
> Hi all, 
> 
> I have written a program which performs some data simulation, model fitting (to the simulated data) and then  it will save the parameter estimates from each loop into a matrix for later use.  Because convergence will not be met in some sets of the simulated data, I have used a 'while' instead of a 'for' loop for the job. With a 'for' loop I was not able to turn the counter back and repeat the same loop when non-convergence occurred. 
> 
> While my programme seems to be working alright, something rather odd is happening. A sample of my programme is as follows:- (the eaxct codes in 'single quotes' have been omitted for simplicity sake)
> 
> ilim <- 10 
> while (i <= ilim) { 
> y <- 'simulated some data' 
> modelsummary <- try('fitted a model to the simulated data') 
> on.exit( c( cat("non-convergence met at loop ", i) , next) ) 
> i <- i+1
> } 
> 
> When this stopped, it stopped with the warning message that I provided and the number of i was 11. I can't figure out why it is equal to 11 because the condition for the while loop should have failed when i became 11. The loop should have stopped and it should not have got to the 'on.exit' bit  in the loop  automatically. 
> 
> While it does not seem to affect the results of my programme, I would like to know why this quirk is  happening. Any help or suggestion is more than welcome. Thanks in advance. 
> 
> Edmond  
> 
> 
> 
> 
> 
> 
> function to enable R to go to the next round once a non-convergence takes place.
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help



More information about the R-help mailing list