[R] How to get rid of loop?

Uwe Ligges ligges at statistik.tu-dortmund.de
Mon Apr 27 10:53:48 CEST 2009



Ken-JP wrote:
> 
> The code below shows what I'm trying to get rid of.
> 
> If there is no way to get rid of the loop, I will try to use package( inline
> ).
> I'm just curious as to whether there is a "vector way" of doing this
> algorithm.


I don't see a vector way. If speed is an issue, I'd suggest to port this 
small part to C, it's very simple and may yield a considerable 
performance boost (untested). It can probably be used as a textbook 
example for code where porting to C make sense.

Best,
Uwe Ligges



> #
> -----------------------------------------------------------------------------------------
> 
> set.seed(1)
> x <- runif(100)
> n <- length( x )
> y <- rep(NA, n)
> yprev <- 0;
> for ( i in (1:n)) {
> 	if ( x[i]>0.75 ) {
> 		y[i] <- 1;
> 	} else if ( x[i]<0.25 ) {
> 		y[i] <- -1;
> 	} else if ( yprev==1 & x[i]<0.5) {
> 		y[i] <- 0;
> 	} else if ( yprev==-1 & x[i]>0.5) {
> 		y[i] <- 0;
> 	} else {
> 		y[i] <- yprev
> 	}
> 	yprev <- y[i];
> }
> 
>> y
>   [1]  0  0  0  1 -1  1  1  1  1 -1 -1 -1  0  0  1  0  0  1  0  1  1 -1  0
> -1 -1
>  [26] -1 -1 -1  1  0  0  0  0 -1  1  1  1 -1  0  0  1  1  1  1  1  1 -1 -1 
> 0  0
>  [51]  0  1  0 -1 -1 -1 -1  0  0  0  1  0  0  0  0  0  0  1 -1  1  0  1  0 
> 0  0
>  [76]  1  1  0  1  1  0  0  0  0  1 -1  0 -1 -1 -1 -1 -1  0  1  1  1  0  0 
> 1  1
> 
>




More information about the R-help mailing list