[R] How to speed up multiple for loop over list of data frames

James jctoll at gmail.com
Thu Oct 18 03:57:37 CEST 2007

On Oct 17, 2007, at 4:36 PM, James wrote:

> On Oct 17, 2007, at 10:18 AM, Waterman, DG ((David)) wrote:
>> I agree. Avoid the lines like:
>> iv     = c( iv, min(i, j) )
>> I had code that was sped up by 70 times after fixing the size of my
>> output object before entering a loop.
> I'm in the process of replacing that very kind of command.  In my  
> case, I'm trying to iterate over a non-integer sequence that  
> doesn't begin at 1.
> x<-seq(15,25,0.10)
> So when I'm iterating over that sequence in my for loop, I don't  
> have nice, easy integers that I can also use for the assignment to  
> my vector.  Is there a way to know where I am in the for loops  
> progress through the vector x, without having to create a separate  
> variable that I increment each time the loop executes?  Something  
> along the lines of this:
> y<-numeric(length(x))
> for(i in x) {
>      y[i] <- GBSGreeks(Selection = 'delta', TypeFlag="c", S=i,  
> X=20, Time=1/12, r=.05, b=.05, sigma=0.4)
> }
> But that obviously doesn't work.  The vector x is length=101.  My  
> vector assignment only works on the 11 integers from 15 to 25.
> Is there a clever way to fix this without the use of a separate  
> variable to track the loops progress through the vector x and for  
> assignment to the equal size y vector?
> thanks
> James

I guess in answer to my own question I found that on page 46 of  "An  
Introduction to R" it describes this usage:

 > for (i in 1:length(yc)) {
plot(xc[[i]], yc[[i]]);
abline(lsfit(xc[[i]], yc[[i]]))

So in my case that turns into:

for(i in 1:length(x)) {
      y[i]<-GBSGreeks(Selection = 'delta', TypeFlag="c", S=x[i],  
X=20, Time=.0000001, r=.05, b=.05, sigma=0.4)

Sorry for the noise.


More information about the R-help mailing list