[R] Make a loop more efficient

David Winsemius dwinsemius at comcast.net
Tue Oct 5 14:55:11 CEST 2010


On Oct 5, 2010, at 8:41 AM, Alaios wrote:

> Hello everyone
> I need some advice if the following might be easier implemented.
>
> There are n matrixes
>
> each matrix needs to calculate one value for the rest n-1 matrixes  
> (but not for
> itself). I implemented this one by
>
> two nested loops
>
> for (i in c(1:length(CRX))) {
>
>   for (j in c(1:length(CRX)))
>       if (i!=j)
> # where i and j are the two indexes. If i==j then is the same matrix.
>           calculations()
> }
>
>
> Do you think there might be a more efficient R-wise way to implement  
> this?

Does the result of "calculations()" depend on the order of the two  
selected matrices? If not, then you are doing twice as many  
calculations() as necessary and could use a test like:

if (i < j) # rather than if (i != j)

You could also create 2 way combinations with the combn function, but  
I don't know if that would improve the speed (and I suspect the loop  
is just as fast).

What does performance profiling tell you about where most of the cpu  
time is being spent?

-- 
David.


>
> I would like to thank you in advance for your help
>
> Best Regards
> Alex
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list