[R] Avoiding a loop

jim holtman jholtman at gmail.com
Fri Apr 8 14:15:03 CEST 2011


Use 'diff' to determine where the changes are:

> S <- sample(0:1,30,TRUE)
> S
 [1] 0 0 1 1 0 1 1 1 1 0 0 0 1 0 1 0 1 1 0 1 1 0 1 0 0 0 0 0 1 0
> which(diff(S) == -1)
[1]  4  9 13 15 18 21 23 29
>

then use the indices for the other processing.

On Thu, Apr 7, 2011 at 10:30 PM, Worik R <worikr at gmail.com> wrote:
> Friends.
>
> I cannot simplify this much, and I think the loop is unavoidable.  As a
> recovering C programmer I want to avoid loops and in cases like this I
> almost allways can by using an apply function.  But I suspect in this case
> there is nothing I can do.
>
> It is a finance example where a price series is compared to a moving
> average.  If the price goes above the average, plus a bit, buy the
> security.  If we are holding the security and the price dips below the
> moving average sell it.
>
> P is the series of prices
>
> m is the moving average series
>
> S <- P>(m*1.005)
> S[S]<-1
>
> Now S is my signal it is 1 when P > m plus a margin of 0.005 x m
>
> But now I need to control when S goes from 1 to 0.  As far as I can tell
> this is the only way...
>
> for(i in 2:length(S)){
>  if(S[i]==0 && S[i-1] == 1){
>    ## Was long, now short.  SHould I be short?  Is P>m still?
>    if(P[i] > m[i]){
>      ## Stay long
>      S[i] <- 1
>    }
>  }
> }
>
> As I mentioned I am a recovering C programmer, so I have a buit in loop
> reflex, but I am struggling to adapt.  But this one has me beat!  Can anyone
> help?
>
> cheers
> W
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list