Re: [R] Avoiding a loop

From: Niels Richard Hansen <Niels.R.Hansen+lists_at_math.ku.dk>
Date: Fri, 08 Apr 2011 11:05:32 -0700

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.

On 08/04/11 00.58, Juan Carlos Borrás wrote:
> Kenn,
> I find your solution more elegant.
>
> 2011/4/8 Kenn Konstabel<lebatsnok_at_gmail.com>:
>> 2011/4/8 Juan Carlos Borrás<jcborras_at_gmail.com>:
>>> #Use the indexes of S in a sapply function.
>>>
>>> N<- 10
>>> S<- sample(c(0,1), size=N, replace=TRUE)
>>> v1<- sapply(c(1:N-1), function(i) S[i]&&S[i+1])
>>
>> You can achieve the same v1 using
>>
>> v1.2<- S[2:N-1]& S[2:N]
>>
>> .. or if you insist on having NA as the first element, -- c(NA, v1.2)
>>
>> Vectorization is more efficient than loops but this need not be true
>> for the *apply functions.
>>
>>>
>>> # Then
>>> v2<- (P> m)
>>>
>
> ______________________________________________
> R-help_at_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.

-- 
Niels Richard Hansen                     Web:   www.math.ku.dk/~richard	
Associate Professor                      Email: Niels.R.Hansen_at_math.ku.dk
Department of Mathematical Sciences             nielsrichardhansen_at_gmail.com
University of Copenhagen                 Skype: nielsrichardhansen.dk	
Universitetsparken 5                     Phone: +1 510 502 8161	
2100 Copenhagen Ø
Denmark

______________________________________________
R-help_at_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.
Received on Fri 08 Apr 2011 - 18:07:45 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 08 Apr 2011 - 19:00:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive