[R] odd behaviour of 'while'?

Edmond Ng Edmond.Ng at lshtm.ac.uk
Fri Mar 14 18:40:00 CET 2003


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.



More information about the R-help mailing list