[R] Index of a Loop Variable?

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Tue Apr 6 17:49:43 CEST 2004


This all reminds me of some looping things I was working on a year or so 
ago.

When looping over, say, 1 to 10,000,000 with:

for(i in 1:10000000)

  R creates a 10,000,000-integer long vector, which seems a bit ugly. 
The solution is obviously to have a counter and add one every time, then 
testing. But that's messy. So I started writing some iterator functions. 
They work like this:

  * first create a new loop object:

myLoop <- loop(N=10000000)

  * then iterate over it in a while loop:

while(iterate(myLoop)){
  doStuff()
}

  * within the while loop, you can use a bunch of methods to get the 
current iteration from the myLoop object, and other clever stuff such as 
predicting when the loop is going to end:

while(iterate(myLoop)){
  doStuff()
  cat("Iteration : ",iteration(myLoop),'\n')
  cat("Predicted finish at: ",predictEnd(myLoop),'\n')
}


  * I then extended this class to make a looping class for MCMC runs:

  myMcLoop <- mcmcLoop(N=10000000, burn.in=10000, thin=1000)

  * then defined some new methods for that, so you can tell if the 
current iteration is in the burn-in period, or if the current iteration 
is one selected from the thinning:

while(iterate(myMcLoop)){
  sample <- doMCMC()
  if(saveResults(myLoop))
    x[[indexResult(myLoop)]] <- sample
  }
}

  So, who wants this? I originally wrote it using S3 methods, then had a 
go at doing it with S4 methods and then had yet another go using the 
R.oo package just for the heck of it. The various bits are scattered 
between various machines so it might take some archaeology to find the 
most recent or best code. Something to keep me busy during over Easter 
break perhaps...

Baz




More information about the R-help mailing list