[R] long algo

Uwe Ligges ligges at statistik.uni-dortmund.de
Wed Oct 29 10:51:49 CET 2003


william ritchie wrote:

> Hi everyone,
> 
>  I ve been using R for months and find it really
> practical and straight forward.
> However (the inevitable however), I am finding it very
> slow for one of my operations:
> it s basically an itertation over i and j in a pretty
> big table (4* 4608). It takes 30 minutes!!!!
> 
> Thanks

There was a suggestion to use C or Fortran, but in your particular case 
it looks like you can choose a simpler way to get more performance (even 
if not that much as in C) by vectorizing a bit more, see below.



> Ps:if it can help here is the source:
> 
> median1<-matrix(nrow=4608,ncol=1)
> median2<-matrix(nrow=4608,ncol=1)
> median3<-matrix(nrow=4608,ncol=1)
> median4<-matrix(nrow=4608,ncol=1)
> v<-c(18,19,20,21,23)
> for (i in 0:11)
>     {
>      for (j in 1:384)
>         {    
>          
> median1[j+(i*384),]<-puce[j+(i*384),5]+median(puce[v+384*i,2]-puce[v+384*i,5])
>         
> median2[j+(i*384),]<-puce[j+(i*384),19]+median(puce[v+384*i,16]-puce[v+384*i,19])
>         
> median3[j+(i*384),]<-puce[j+(i*384),12]+median(puce[v+384*i,9]-puce[v+384*i,12])
>         
> median4[j+(i*384),]<-puce[j+(i*384),26]+median(puce[v+384*i,23]-puce[v+384*i,26])
>          
>        
>           puce[,5]<-median1
>          puce[,19]<-median2
>          puce[,12]<-median3
>          puce[,26]<-median4
> 
> 
>          }
>      }


The obvious (well, I haven't tried) *first* step (I don't want to 
rewrite your code here!) is, e.g.,


median1 <- median2 <- median3 <- median4 <- numeric(4608)
v <- c(18,19,20,21,23)
for (i in 0:11)
   {
  j <- 1:384
median1[j+(i*384)]<-puce[j+(i*384),5]+median(puce[v+384*i,2]-puce[v+384*i,5])
median2[j+(i*384)]<-puce[j+(i*384),19]+median(puce[v+384*i,16]-puce[v+384*i,19])
median3[j+(i*384)]<-puce[j+(i*384),12]+median(puce[v+384*i,9]-puce[v+384*i,12])
median4[j+(i*384)]<-puce[j+(i*384),26]+median(puce[v+384*i,23]-puce[v+384*i,26])
}
puce[,5]<-median1
puce[,19]<-median2
puce[,12]<-median3
puce[,26]<-median4


Uwe Ligges




More information about the R-help mailing list