Skip to content
Prev 256286 / 398506 Next

Avoiding a loop

I believe the solutions proposed ignore the recursive nature of the
original problem and hence produce wrong solutions.

P <- c(5, 7, 6.01, 6.01, 7)
m <- rep(6, 5)
S0 <- as.numeric(P>(m*1.005))

Then the original loop from Worik gives

S <- S0
for(i in 2:length(S)){
   if(S[i]==0 && S[i-1] == 1){
     if(P[i] > m[i]){
       S[i] <- 1
     }
   }
}

 > S
[1] 0 1 1 1 1

The other solutions I have seen on the list suggest looking
upfront on differences in S, and I am pretty sure the intentions
were to produce

S <- S0
v <- c(FALSE, (S[-1] == 0) & (S[-5] == 1)) & (P > m)

where v equals c(FALSE, FALSE, TRUE, FALSE, FALSE) and then

S[v] <- 1

giving

 > S
[1] 0 1 1 0 1

When you recursively update a vector like this I don't know any
general vectorization fix.

- Niels
On 08/04/11 00.58, Juan Carlos Borr?s wrote: