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
______________________________________________
R-help@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.