[R] avoiding a loop

Jerome Asselin jerome.asselin at crchum.qc.ca
Tue Oct 24 20:53:54 CEST 2006


On Tue, 2006-10-24 at 14:36 -0400, Leeds, Mark (IED) wrote:
> I think I asked a similar question 3 years ago to the  Splus list and I
> think the answer was no or noone answered so noone should spend more
> than 5 minutes on this 
> because it could definitely be a waste of time.
>  
> My question is whether the function below can be rewritten without a for
> loop. apply is fine if it can be done that way but i doubt it. I call it
> a lot and would
> prefer to not loop.
>  
> #-----------------------------------------------------------------------
> --------------------------
>  
> constructLt<-function(invector) {
>  
> outvector<-invector
>  
>  for ( i in 2:length(invector) ) {
>  if ( invector[i] < 1 ) {
>   outvector[i]<-invector[i]*outvector[i-1]
>  }
> }
>  
> return(outvector)
>  
> }

You sure can vectorize this. Try this below... I haven't tested, but it
should be close to your solution. There's also 

a <- invector[-1]
outvector <- invector
wh <- which(a<1)+1
outvector[wh] <- a[wh] * invector[-length(invector)][wh-1]
outvector

HTH,
Jerome

-- 
Jerome Asselin, M.Sc., Agent de recherche, RHCE
CHUM -- Centre de recherche
3875 rue St-Urbain, 3e etage // Montreal QC  H2W 1V1
Tel.: 514-890-8000 Poste 15914; Fax: 514-412-7106



More information about the R-help mailing list